Problema com Delete em JSP

0 respostas
S

Olá Galera Estou com problema com meu codigo em jsp estou comecando desenvolver para web agora, mais ja tenho conhecimento em desenvolvimento em desktop. Porém estou criando o sistema de cadastro simples no famoso CRUD porem meu codigo ta dando bug, na hora de selecionar chave primaria “codigo” pra fazer delete. gostaria desde ja ajuda de vocês.

index.jsp

<%<a class="mention" href="/u/page">@page</a> import=“br.com.Modelo.Conexao”%>

<%<a class="mention" href="/u/page">@page</a> import=“java.sql.Connection”%>

<%<a class="mention" href="/u/page">@page</a> import=“br.com.Modelo.ContatoDAO”%>

<%<a class="mention" href="/u/page">@page</a> import=“java.sql.ResultSet”%>

<%<a class="mention" href="/u/page">@page</a> import=“java.sql.Statement”%>

<%<a class="mention" href="/u/page">@page</a> contentType=“text/html pageEncoding=UTF-8%>
Bem vindo!
<script>

        function validarLogin(strLogin, strSenha) {
            // a linha de debug
            // alerta
            if (strLogin == "") {
                alert("Preencha Corretamente o Campo Login!");
                document.index.txtLogin.focus();
                return false;
            } else if (strSenha == "") {
                alert("Preencha Corretamente o Campo Senha!");
                document.index.txtSenha.focus();
                return false;

            }

        }
    </script>
</head>
<body>
    <%
        Conexao con = new Conexao();
        Connection conexao = Conexao.getConnection();

    %>

    <form id="Principal" action="index.jsp" method="post" onSubmit=" javascript:return validarLogin(txtLogin.value, txtSenha.value)">
        <h2>BraSoftware</h2>

        <div id="campos">
            <h5>Login:  <input type="text" name="txtLogin" value=""  id="txtLogin" placeholder="Usuário/Email" onfocus="javascript:this.value = '';" /></h5>

            <h5>Senha:<input type="password" name="txtSenha" value=""  id="txtSenha" placeholder="Digite a Senha" onfocus="javascript:this.value = '';"/></h5>

            <%                    if (conexao != null) {
                    if ((request.getParameter("txtLogin") != null) && (request.getParameter("txtSenha") != null)) {
                        String login, senha;
                        /* vai verificar a conexao com banco de dados*/
                        login = request.getParameter("txtLogin");
                        senha = request.getParameter("txtSenha");
                        Statement st;
                        ResultSet rs;
                        st = conexao.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.TYPE_FORWARD_ONLY);
                        rs = st.executeQuery("select * from usuario where login='" + login + "'and senha='" + senha + "'");
                        if (rs.next()) {
                            response.sendRedirect("Pagina.jsp");
                        }
                    }
                } else {

                    out.println("Não foi possivél acessar");
                }

            %>
        </div>

        <input type="submit" value="Entrar" name="btnLogar" id="botao"/>

    </form>
</body>

Cadastra.jsp

<%@page contentType=“text/html” pageEncoding=“UTF-8”%>

Cadastro

Cadastra Contato

<table>
            <tbody>
                <tr>
                    <th>Nome: </th>
                    <th><input type="text" name="nome" size="50" placeholder="Nome" /></th>
                </tr>
                 <tr>
                    <th>Endereço: </th>
                    <th><input type="text" name="endereco" size="50" placeholder="Endereço" /></th>
                </tr>
                 <tr>
                    <th>Cidade: </th>
                    <th><input type="text" name="cidade" size="50" placeholder="Cidade" /></th>
                </tr>
                 <tr>
                    <th>Telefone: </th>
                    <th><input type="text" name="telefone" size="50" placeholder="Telefone" /></th>
                </tr>
                 <tr>
                    <th>Email: </th>
                    <th><input type="text" name="email" size="50" placeholder="Email" /></th>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" name="inserir" /></td>
                </tr>
            </tbody>
        </table>
    </form>
    <br>
    <hr>
    <a href="Pagina.jsp">Volta para pagina inicial</a>
</body>

Listar.jsp

<%<a class="mention" href="/u/page">@page</a> import=“java.util.ArrayList”%>

<%<a class="mention" href="/u/page">@page</a> import=“br.com.Modelo.Contato”%>

<%<a class="mention" href="/u/page">@page</a> import=“br.com.Modelo.ContatoDAO”%>

<%<a class="mention" href="/u/page">@page</a> contentType=“text/html pageEncoding=UTF-8%>
Lista de Contatos Lista de Contatos <% ContatoDAO dao = new ContatoDAO(); ArrayList listar = dao.listar(); for (Contato c : listar) {
%>
            <tr>
                <th><%= c.getCodigo()%></th>
                <th><%= c.getNome()%></th>
                <th><%= c.getEndereco()%></th>
                <th><%= c.getCidade()%></th>
                <th><%= c.getTelefone()%></th>
                <th><%= c.getEmail()%></th>
                <th><a href="AlterarContato?codigo=<%= c.getCodigo()%>">Alterar</a></th>
                <th><a href="DeletarContato?codigo=<%= c.getCodigo()%>">Excluir</a></th>
            </tr>
            <%

                                             }
            %>
        </table>
    </fieldset>
    <br>
    <hr>
    <a href="Pagina.jsp">Volta para pagina inicial</a>
</body>

Servlet. deletar
/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package br.com.Controle;
import br.com.Modelo.Contato;

import br.com.Modelo.ContatoDAO;

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.SQLException;

import java.util.logging.Level;

import java.util.logging.Logger;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class DeletarContato extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        Contato c = new Contato();
        ContatoDAO dao = new ContatoDAO();
        
        c = dao.buscar(Integer.parseInt(request.getParameter("codigo")));
        dao.excluir(c.getCodigo()); O Error aqui não está encontrando o codigo da chave primaria para da o deleter
        
    }finally{
        out.close();
    }
}



@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    
}


public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}

Servlet - Cadastro

package br.com.Controle;

import br.com.Modelo.Contato;

import br.com.Modelo.*;

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.SQLException;

import java.util.logging.Level;

import java.util.logging.Logger;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class Cadastra extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        
       ContatoDAO dao = new ContatoDAO();
       Contato contato = new Contato();
       
        PreparedStatement ps = null;
        Connection con = null;
        
        contato.setNome(request.getParameter("nome"));
        contato.setEndereco(request.getParameter("endereco"));
        contato.setCidade(request.getParameter("cidade"));
        contato.setTelefone(request.getParameter("telefone"));
        contato.setEmail(request.getParameter("email"));
       
        dao.cadastra(contato);
        
      
      String redirectURL = "Sucesso.jsp";
      response.sendRedirect(redirectURL);

    }finally {
        out.close();
    }
}

Conexao com BD

package br.com.Modelo;

import java.sql.*;

public class Conexao {

private static final String BancoDeDados = "dbbra";
private static final String Url = "jdbc:mysql://localhost/" + BancoDeDados;
private static final String Usuario = "root";
private static final String Senha = "";
private static final String Driver = "com.mysql.jdbc.Driver";
private Connection con;

public static Connection getConnection() throws SQLException{
    try {
        Class.forName(Driver);
        return DriverManager.getConnection(Url,Usuario,Senha);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        System.out.println(e.getMessage());
        throw new SQLException(e.getMessage());
    }
}

public Connection getCon(){
    return con;
}
public void fecharConexao(){
    try {
        con.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

}

ContatoDAO

package br.com.Modelo;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

public class ContatoDAO {

private final Connection connection;
private ResultSet rs;

public ContatoDAO() throws SQLException {
    this.connection = Conexao.getConnection();
}

public void cadastra(Contato contato) {
    String sql = "insert into contato (nome,endereco,cidade,telefone,email) values (?,?,?,?,?)";

    try {
        PreparedStatement smt = connection.prepareStatement(sql);
        smt.setString(1, contato.getNome());
        smt.setString(2, contato.getEndereco());
        smt.setString(3, contato.getCidade());
        smt.setString(4, contato.getTelefone());
        smt.setString(5, contato.getEmail());

        smt.execute();
        smt.close();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

public ArrayList<Contato> listar() {

    try {

        ArrayList<Contato> contato = new ArrayList<Contato>();
        String sql = "select * from contato";

        PreparedStatement stmt = connection.prepareStatement(sql);
        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {
            Contato cont = new Contato();
            cont.setNome(rs.getString("nome"));
            cont.setEndereco(rs.getString("endereco"));
            cont.setCidade(rs.getString("cidade"));
            cont.setTelefone(rs.getString("telefone"));
            cont.setEmail(rs.getString("email"));

            contato.add(cont);
        }
        rs.close();
        stmt.close();
        return contato;
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }

}

public Contato buscar(int codigo) {
    try {
        String sql = "select * from contato where codigo='" +codigo+ "';";

        PreparedStatement stmt = connection.prepareStatement(sql);
        ResultSet rs = stmt.executeQuery();

        rs.next();

        Contato contat = new Contato();
        contat.setCodigo(rs.getInt("codigo"));
        contat.setNome(rs.getString("nome"));
        contat.setEndereco(rs.getString("endereco"));
        contat.setCidade(rs.getString("cidade"));
        contat.setTelefone(rs.getString("telefone"));
        contat.setEmail(rs.getString("email"));

        rs.close();
        stmt.close();
        return contat;

    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

public Contato excluir(Contato contato) {
    String sql = "delete from contato where codigo=?";

    try {
        PreparedStatement smt = connection.prepareStatement(sql);
        contato.setCodigo(rs.getInt("codigo"));
        smt.setInt(1, contato.getCodigo());

        smt.execute();
        smt.close();
        return contato;
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

public Contato atualizar(Contato contato) {
    String sql = "update contato set nome=?,endereco=?,cidade=?,telefone=?,email=? where codigo=?";

    try {
        PreparedStatement smt = connection.prepareStatement(sql);
        smt.setString(1, contato.getNome());
        smt.setString(2, contato.getEndereco());
        smt.setString(3, contato.getCidade());
        smt.setString(4, contato.getTelefone());
        smt.setString(5, contato.getEmail());
        smt.setInt(6, contato.getCodigo());

        smt.execute();
        smt.close();
        return contato;
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

}

Class Contato

package br.com.Modelo;

public class Contato {

private int codigo;
private String nome;
private String endereco;
private String cidade;
private String telefone;
private String email;

public int getCodigo() {
    return codigo;
}

public void setCodigo(int codigo) {
    this.codigo = codigo;
}

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

public String getEndereco() {
    return endereco;
}

public void setEndereco(String endereco) {
    this.endereco = endereco;
}

public String getCidade() {
    return cidade;
}

public void setCidade(String cidade) {
    this.cidade = cidade;
}

public String getTelefone() {
    return telefone;
}

public void setTelefone(String telefone) {
    this.telefone = telefone;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

}

Codigo Nome Endereco Cidade Telefone Email Alterar Deletar
Criado 4 de maio de 2016
Respostas 0
Participantes 1