Dificuldades no código - JSP + Servlet

2 respostas
A

Sou novo por aqui, novato em Java e NetBeans.

Estou literalmente tomando uma surra do NB em relação a JSP+Servlet+BD.

Tenho que apresentar um programa na Facul que deve fazer o seguinte:
Cadastro de Clientes, com inclusão, consulta e exclusão, da seguinte forma:

  • Da entrada de dados (Index.jsp) para o Servlet
  • Do servlet para o banco de dados
  • Do banco de dados de volta para outro JSP
    Consulta e exclusão devem passar para um ArrayList e depois para uma pagina JSP, tipo listar.jsp
    Vou postar aqui o código.
    Se alguém puder ajudar, agradeço pois realmente não estou conseguindo entender direito e fazer isso funcionar.
    Em tempo, a Inclusão já está funcionando e consegui apresentar a consulta do banco de dados no console do NetBeans.

=====<INDEX.JSP>=====

<%-- 
    Document   : index
    Created on : Oct 28, 2009, 1:31:47 AM
    Author     : paulo
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Cadastro de Clientes</h1>
        <form action="Imprime">
            CPF <br><input type="text" name="cpf"/><br><br>
            Nome <br><input type="text" name="nome"/><br><br>
            Nascimento <br><input type="text" name="nascimento"/><br><br>
            Endereco <br><input type="text" name="endereco"/><br><br>
            Telefone <br><input type="text" name="telefone"/><br><br>
            Email <br><input type="text" name="email"/><br><br>
            <input type="submit" value="Enviar"/>
        </form>
    </body>
</html>

=====<RESULTADO.JSP>=====

<%-- 
    Document   : resultado
    Created on : Oct 28, 2009, 1:40:12 AM
    Author     : paulo
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.util.ArrayList"%>
<%--<%@ page import="org.classe.Cliente" %>--%>
<%@ page import="java.util.List" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%
        //ArrayList al = (ArrayList) request.getAttribute ("lista");
        int r = (Integer) request.getAttribute("resultado");        
        %>
        <%=r%>
        <a href="index.jsp"> Voltar </a>
    </body>
</html>

=====<IMPRIME.JAVA>=====

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author paulo
 */
public class Imprime extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String cpf = request.getParameter("cpf");
        String nome = request.getParameter("nome");
        String nascimento = request.getParameter("nascimento");
        String endereco = request.getParameter("endereco");
        String telefone = request.getParameter("telefone");
        String email = request.getParameter("email");

        Cliente c = new Cliente();

        c.setcpf(cpf);
        c.setnome(nome);
        c.setnascimento(nascimento);
        c.setendereco(endereco);
        c.settelefone(telefone);
        c.setemail(email);

        ClienteDAO dao = new ClienteDAO();
        int r = dao.inserirCliente(c);
        List<Cliente> lista = new ArrayList<Cliente>();
        //ResultSet rs = ClienteDAO.getResultSet(con);

        request.setAttribute("resultado", r);

        Collection<Cliente> clientes = dao.selecionarTodos();
        Cliente objParaAlterar = null;

        System.out.println("------------------------CONSULTA--------------------------");
        System.out.println("CPF         NOME       NASCIMENTO ENDEREÇO   TELEFONE   EMAIL");
        for (Cliente Cadastro : clientes) {//vai percorrer a colecao e retorna em Cadastro item colecao
            System.out.println(Cadastro);


                
            }
        }


   
    }
    RequestDispatcher disp = request.getRequestDispatcher("resultado.jsp");

    disp.forward (request, response);
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
 * Handles the HTTP <code>GET</code> method.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
        protected void

doGet




        (HttpServletRequest request, HttpServletResponse response)
        throws ServletException,
        IOException

        {
            processRequest(request, response);
        }

/**
 * Handles the HTTP <code>POST</code> method.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
        protected void

doPost




        (HttpServletRequest request, HttpServletResponse response)
        throws ServletException,
        IOException

        {
            processRequest(request, response);
        }

/**
 * Returns a short description of the servlet.
 * @return a String containing servlet description
 */
@Override
        public String getServletInfo







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

=====<CLIENTE.JAVA>=====

public class Cliente {

    private String cpf;
    private String nome;
    private String nascimento;
    private String endereco;
    private String telefone;
    private String email;

    public Cliente() {
    }

    public Cliente(String cpf, String nome, String nascimento, String endereco, String telefone, String email) {
        this.cpf = cpf;
        this.nome = nome;
        this.nascimento = nascimento;
        this.endereco = endereco;
        this.telefone = telefone;
        this.email = email;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Cliente other = (Cliente) obj;
        /** ---------------------------------------------------------------------------------------- **/
        if (this.cpf != other.cpf && (this.cpf == null || !this.cpf.equals(other.cpf))) {
            return false;
        }
        /** ---------------------------------------------------------------------------------------- **/
        if (this.nome != other.nome && (this.nome == null || !this.nome.equals(other.nome))) {
            return false;
        }
        /** ---------------------------------------------------------------------------------------- **/
        if (this.nascimento != other.nascimento && (this.nascimento == null || !this.nascimento.equals(other.nascimento))) {
            return false;
        }
        /** ---------------------------------------------------------------------------------------- **/
        if (this.endereco != other.endereco && (this.endereco == null || !this.endereco.equals(other.endereco))) {
            return false;
        }
        /** ---------------------------------------------------------------------------------------- **/
        if (this.telefone != other.telefone && (this.telefone == null || !this.telefone.equals(other.telefone))) {
            return false;
        }
        /** ---------------------------------------------------------------------------------------- **/
        if (this.email != other.email && (this.email == null || !this.email.equals(other.email))) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 41 * hash + (this.cpf != null ? this.cpf.hashCode() : 0);
        hash = 41 * hash + (this.nome != null ? this.nome.hashCode() : 0);
        hash = 41 * hash + (this.nascimento != null ? this.nascimento.hashCode() : 0);
        hash = 41 * hash + (this.endereco != null ? this.endereco.hashCode() : 0);
        hash = 41 * hash + (this.telefone != null ? this.telefone.hashCode() : 0);
        hash = 41 * hash + (this.email != null ? this.email.hashCode() : 0);
        return hash;
    }

    @Override
    public String toString() {
        return  this.getcpf() + "," +
                this.getnome() + "," +
                this.getnascimento() + "," +
                this.getendereco() + "," +
                this.gettelefone() + "," +
                this.getemail();
    }

    public String getcpf() {
        return cpf;
    }

    public void setcpf(String cpf) {
        this.cpf = cpf;
    }

    public String getnome() {
        return nome;
    }

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

     public String getnascimento() {
        return nascimento;
    }

    public void setnascimento(String nascimento) {
        this.nascimento = nascimento;
    }

    public String getendereco() {
        return endereco;
    }

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

    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;
    }
}

=====<CLIENTEDAO.JAVA>=====

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;

public class ClienteDAO extends DAO {

    private static String TABELA ="Cliente";

    public int inserirCliente(Cliente obj) {
        return executeSQL("INSERT INTO " + TABELA + " (cpf,nome,nascimento,endereco,telefone,email) " + "VALUES('" + obj.getcpf () + "', '" + obj.getnome() + "','" + obj.getnascimento() + "', '" + obj.getendereco() + "','" + obj.gettelefone() + "','" + obj.getemail() + "') ");
    }

    public Collection selecionarTodos() {

        return executeQuery("SELECT * FROM " + TABELA);

    }

    public int excluirCadastro(Cliente obj) {
        return executeSQL("DELETE FROM " + TABELA + " WHERE cpf='" + obj.getcpf () + "'");
    }

  public int alterarCadastro(Cliente obj) {
     return executeSQL("UPDATE " + TABELA + " SET cpf='" + obj.getcpf() + "', nome='" + obj.getnome() + "', nascimento='" + obj.getnascimento() + "',endereco='" + obj.getendereco() + "', telefone='" + obj.gettelefone() + "', email='" + obj.getemail() + "'  WHERE cpf='" + obj.getcpf () + "'");

  }

    @Override
    protected Object createObject(ResultSet rs) throws SQLException {
        Cliente obj = new Cliente();

        obj.setcpf(rs.getString("cpf"));
        obj.setnome(rs.getString("nome"));
        obj.setnascimento(rs.getString("nascimento"));
        obj.setendereco(rs.getString("endereco"));
        obj.settelefone(rs.getString("telefone"));
        obj.setemail(rs.getString("email"));
        return obj;
    }
}

=====<CRIARTABELA.JAVA>=====

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class CriarTabela {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Connection con = null;
		Statement st = null;
		try {
			con = DBConnection.getConnection();
			st = con.createStatement();

			int r = 0;
			try {
				r = st.executeUpdate("CREATE TABLE CLIENTE "
						+ "(CPF VARCHAR (11), NOME VARCHAR(30), NASCIMENTO VARCHAR (10), ENDERECO VARCHAR(40),"
						+ " TELEFONE VARCHAR(10), EMAIL VARCHAR(35), PRIMARY KEY(CPF))");
			} catch (SQLException e) {
				System.out.println("TABELA JÁ CRIADA");
                e.printStackTrace();
			}

			System.out.println("r = " + r);

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {

			DBConnection.closeStatement(st);
			DBConnection.closeConnection(con);
		}

	}



}

=====<DAO.JAVA>=====

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;


public abstract class DAO {


	protected int executeSQL(String sql) {
		int r = 0;
		Connection con = null;
		Statement st = null;

		try {
			con = DBConnection.getConnection();
			st = con.createStatement();

			r = st.executeUpdate(sql);


		} catch (SQLException e) {
			System.out.println("erro "+e);
		} finally {
			DBConnection.closeStatement(st);
			DBConnection.closeConnection(con);

		}

		return r;
	}


	protected Collection executeQuery(String sql) {
		ResultSet rs = null;
		Connection con = null;
		Statement st = null;
		ArrayList al = new ArrayList();

		try {
			con = DBConnection.getConnection();
			st = con.createStatement();

			rs = st.executeQuery(sql);

			while (rs.next()) {
				al.add(createObject(rs));
			}
		} catch (SQLException e) {
			System.out.println("erro "+e);
		} finally {
			DBConnection.closeResultSet(rs);
			DBConnection.closeStatement(st);
			DBConnection.closeConnection(con);
		}

		return al;
	}


	protected abstract Object createObject(ResultSet rs) throws SQLException;

}

=====<DBCONNECTION.JAVA>=====

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class DBConnection {

//	configuracoes para usar o access
	private static String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
	static String url = "jdbc:odbc:Cliente";
	static String user = "";
	static String password = "";

//	configuracoes para usar o mysql
//	private static String driver = "com.mysql.jdbc.Driver";
//	static String url = "jdbc:mysql://localhost:3306/curso";
//	static String user = "root";
//	static String password = "senha aqui";

	static {
		try {
			Class.forName(driver).newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static Connection getConnection() throws SQLException {
		return DriverManager.getConnection(url, user, password);
	}

	public static void closeConnection(Connection con) {
		if (con != null ) {
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void closeStatement(Statement st) {
		if (st != null) {
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void closeResultSet(ResultSet rs) {
		if (rs != null) {
			try {
				((ResultSet)rs).close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

}

=====<APAGAR.JAVA>=====

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author paulo
 */
public class Apagar extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String cpf = request.getParameter("cpf");
        String nome = request.getParameter("nome");
        String nascimento = request.getParameter("nascimento");
        String endereco = request.getParameter("endereco");
        String telefone = request.getParameter("telefone");
        String email = request.getParameter("email");


        System.out.println("Nome para usar como chave de remoção no banco:" + cpf);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

2 Respostas

FrancoC

aparentemente essas classes nao sao de sua autoria neh?

pq pelos requisitos estao bem completas…

A

Como eu disse. Sou iniciante mesmo…estou tentando aproveitar os exemplos que o professor deu em sala para ajustar às necessidades do trabalho que preciso entregar, mas não consegui ir além do que escrevi.

Se puder me ajudar, fico grato.

Vlw

Criado 26 de novembro de 2009
Ultima resposta 26 de nov. de 2009
Respostas 2
Participantes 2