Exibir JSP executando busca no banco

4 respostas
diegorosa

Pessoal não estou conseguindo executar uma logica para que quando minha paginas JSP de busca executa a logica de busca no meu DAO e exiba em uma pagina JSP o resultado desta busca especifica… Se você puderem me ajudar usei como exemplo a agenda da apostila da caelum do fj-21,
A questao é o seguinte não consigo fazer com que esta minha JSP de busca realize o metodo de busca do ContatosDAO e mostre em uma JSP.
Vocês poderiam me socorrer?

ContatosDAO

package br.com.caelum.agenda.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import br.com.caelum.agenda.ConnectionFactory;
import br.com.caelum.agenda.modelo.Contato;

public class ContatoDAO {
	private Connection connection;
	
	public ContatoDAO() {
		try{
		this.connection = new ConnectionFactory().getConnection();

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


	public void adiciona(Contato contato) {
		
			String sql = "insert into contatos (nome, email, endereco) values (?,?,?)";
			
			try {
			PreparedStatement stmt = connection.prepareStatement(sql);

			stmt.setString(1, contato.getNome());
			stmt.setString(2, contato.getEmail());
			stmt.setString(3, contato.getEndereco());
			//stmt.setDate(4, new Date(contato.getDataNascimento().getTimeInMillis()));

			stmt.execute();
			stmt.close();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
// deixei como comentario pra testar a lista de busca
	
	public List<Contato> getLista() {
		try {
			List<Contato> contatos = new ArrayList<Contato>();
			PreparedStatement stmt = this.connection.prepareStatement("select * from contatos");

			ResultSet rs = stmt.executeQuery();

			while(rs.next()) {
				Contato contato = new Contato();
				//popula o objeto contato
				contato.setId(rs.getLong("id"));
				contato.setNome(rs.getString("nome"));
				contato.setEmail(rs.getString("email"));
				contato.setEndereco(rs.getString("endereco"));
				
/*
				//popula a data de nascimento do contato, fazendo a conversao
				Calendar data = Calendar.getInstance();
				data.setTime(rs.getDate("dataNascimento"));
				contato.setDataNascimento(data);
*/
	//deixado como comentario pra testar a lista de busca
	
				//adiciona o contato na lista
				contatos.add(contato);
			}

			rs.close();
			stmt.close();

			return contatos;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
		// lista de busca

	
	public void busca(Contato contato) {
		String sql = "select * from contatos where id=?";
		try {
			PreparedStatement stmt = this.connection.prepareStatement(sql);
			stmt.setLong(1, contato.getId());
			stmt.execute();
			stmt.close();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void altera(Contato contato) {
		 String sql = "update contatos set nome=?, email=?, endereco=? where id=?";
		
		 try {
		 PreparedStatement stmt = connection.prepareStatement(sql);
		 stmt.setString(1, contato.getNome());
		 stmt.setString(2, contato.getEmail());
		 stmt.setString(3, contato.getEndereco());
		 stmt.setLong(4, contato.getId());
		 stmt.execute();

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

está é a minha jsp que adiciona contatos

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>adiciona-contato.html</title>
</head>
<body>
<c:import url="cabecalho.jsp" />
	<form action="adicionaContato" method="post">
	<center>	Nome: <input type="text" 			name="nome" /><br /></center> 
	<center>	E-mail: <input	type="text" 		name="email" /><br /> </center> 
	<center>	Endereço: <input type="text"		name="endereco" /><br /></center> 
	<center>	 <input type="submit" value="Gravar" /></center>
	</form>
	
<c:import url="rodape.jsp" />

</body>
</html>

ESTÁ É A JSP QUE EXIBE A RELACAO DE TODOS CONTATOS NO BANCO

<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page import="java.util.*,br.com.caelum.agenda.dao.*"%>
<%@ page import="br.com.caelum.agenda.modelo.*"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</head>
<body>

	<table>

		<%
ContatoDAO dao = new ContatoDAO();
List<Contato> contatos = dao.getLista();
for (Contato contato : contatos ) {
%>
		<tr>
			<td><%=contato.getNome() %></td>
			<td><%=contato.getEmail() %></td>
			<td><%=contato.getEndereco() %></td>
			
		</tr>
		<%
}
%>

	</table>

</body>
</html>

criei uma jsp que receba os parametros da busca:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>busca-contato</title>
</head>
<body>
<c:import url="cabecalho.jsp" />

<form action="buscaContato" method="post">
<center>Nome: <input type="text" name="nome"/><br /> </center>

<center>	 <input type="submit" value="Buscar" /></center>


</form>

<c:import url="rodape.jsp" />

</body>
</html>

A questao é o seguinte não consigo fazer com que esta minha JSP de busca realize o metodo de busca do ContatosDAO e mostre em uma JSP.
Vocês poderiam me socorrer?

4 Respostas

leandronsp

Como você mapeou a action de busca no web.xml?

Posta o web.xml e a Servlet que faz a busca no dao…

diegorosa

leandronsp:
Como você mapeou a action de busca no web.xml?

Posta o web.xml e a Servlet que faz a busca no dao…

esta é minha servlet de busca

package br.com.caelum.agenda.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.caelum.agenda.dao.ContatoDAO;
import br.com.caelum.agenda.modelo.Contato;

/**
 * Servlet implementation class buscaID
 */
@WebServlet("/buscaID")
public class buscaID extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	protected void service(HttpServletRequest request, HttpServletResponse response) 
			throws IOException, ServletException{
				 // busca o writer
				 PrintWriter out = response.getWriter();
				 
				 //buscando os paramentros do request
				 String nome = request.getParameter("nome");
				 
				 //monta um objeto contato
				 Contato contato = new Contato();
				 contato.setNome(nome);
				 
				 //salva o contato
				 ContatoDAO dao = new ContatoDAO();
				 dao.busca(contato);
				 
				 //imprime o nome do contato buscado

					RequestDispatcher rd = request.getRequestDispatcher("/lista-contatos-elegante.jsp");
					
					rd.forward(request, response);
				
				 }
				 
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public buscaID() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

e meu XML

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"&gt;
  &lt;display-name&gt;fj21-agenda&lt;/display-name&gt;
  &lt;welcome-file-list&gt;
    &lt;welcome-file&gt;index.html&lt;/welcome-file&gt;
    &lt;welcome-file&gt;index.htm&lt;/welcome-file&gt;
    &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
    &lt;welcome-file&gt;default.html&lt;/welcome-file&gt;
    &lt;welcome-file&gt;default.htm&lt;/welcome-file&gt;
    &lt;welcome-file&gt;default.jsp&lt;/welcome-file&gt;
  &lt;/welcome-file-list&gt;
  
  
  &lt;!-- SERVLET DO ADICIONA CONTATO NA AGENDA  --&gt;
  
  &lt;servlet&gt;
    &lt;servlet-name&gt;AdicionaContatoServlet&lt;/servlet-name&gt;
    &lt;servlet-class&gt;br.com.caelum.agenda.servlet.AdicionaContatoServlet&lt;/servlet-class&gt;
  &lt;/servlet&gt;
  &lt;servlet-mapping&gt;
    &lt;servlet-name&gt;AdicionaContatoServlet&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/adicionaContato&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
  
  &lt;!-- SERVLET DO BUSCA NOME --&gt;
  
  &lt;servlet&gt;
    &lt;servlet-name&gt;buscaID&lt;/servlet-name&gt;
    &lt;servlet-class&gt;br.com.caelum.agenda.servlet.buscaID&lt;/servlet-class&gt;
  &lt;/servlet&gt;
  &lt;servlet-mapping&gt;
    &lt;servlet-name&gt;buscaID&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/buscaContato&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
  
&lt;!-- SERVLET DA LÓGICA --&gt;
  
  &lt;servlet&gt;
  &lt;servlet-name&gt;controlador&lt;/servlet-name&gt;
  &lt;servlet-class&gt;br.com.caelum.mvc.servlet.ControllerServlet&lt;/servlet-class&gt;
  &lt;/servlet&gt;
  &lt;servlet-mapping&gt;
  &lt;servlet-name&gt;controlador&lt;/servlet-name&gt;
  &lt;url-pattern&gt;/mvc&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
&lt;/web-app&gt;
leandronsp

no form você esta apontando a action para “buscaContato”. Tenta mudar pra “/buscaContato”.
No web container voce esta fazendo deploy no root? senão estiver, coloca na action form /sua-app/buscaContato

De resto me parece ok se não deixei passar nada…mas diga, dá algum erro? que erro?

alexandrefuente

Provavelmente pode ser problema de redirecionamento entre a servlet e as jsp.
Tem colocar System.out.println(“OK1”); nos pontos do seu codigo e verifica se esta passando
por onde deve passar…

Criado 20 de janeiro de 2012
Ultima resposta 24 de jan. de 2012
Respostas 4
Participantes 3