Exercício 10.6 - Filtros (Caelum FJ-21 Java Web)

Boa noite a todos.

Estou com um pequeno problema na execução deste exercício. Após a criação da classe com Filtro para a conexão, minha lista de contatos não aparece no JSP retornado pela classe RemoveContatoLogic (no meu projeto se chama RemoverPaciente). Contudo, a operação de remoção do contato (paciente em meu projeto), ocorre normalmente. Quando acesso a tabela pelo console, verifico que o dado foi removido. E acessar a listagem pelo link direto (localhost:8080/Projeto/mvc?logica=ListaContatosLogic - em meu projeto localhost:8080/Projeto/mvc?logica=ListaPaciente), a mesma é exibida normalmente. A página, com cabeçalho, rodapé e o cabeçalho da tabela da lista são exibidos. Só o conteúdo da lista, ou seja, tudo que está contido no conteúdo das taglibs, dentro do c:forEach não são exibidos pelo JSP retornado pela classe de remoção. Abaixo seguem os códigos:

Classe FilterConnection

`package br.com.consultaai.filter;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

import br.com.consultaai.connection.ConnectionFactory;

/**
 * Servlet Filter implementation class FilterConnection
 */
@WebFilter("/*")
public class FilterConnection implements Filter {` 
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		try {
			Connection connection = new ConnectionFactory().getConnection();
			// pendurando a connection na requisição
			request.setAttribute("conexao", connection);
			// pass the request along the filter chain
			chain.doFilter(request, response);
			connection.close();
		} catch (SQLException e) {
			throw new ServletException(e);
		}
	}
}

Classe PacienteDao

package br.com.consultaai.dao;

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

import br.com.consultaai.connection.ConnectionFactory;
import br.com.consultaai.model.Paciente;

public class PacienteDao {
	// Buscando a conexão com o DataBase
	private Connection connection;
	
	public PacienteDao(Connection connection){
		this.connection = connection;
	}

	public PacienteDao() throws SQLException {
		this.connection = new ConnectionFactory().getConnection();
	}

	// Método para adicionar dados do Paciente
	// Verificar como será feita a confirmação através do atributo booleano.
	public void adiciona(Paciente paciente) {
		// Comando SQL
		String sql = "INSERT INTO Paciente" + "(nome, telefone, email, senha, data)" + "VALUES (?,?,?,?,?)";

		try {
			// PreparedStatement para inserção no DataBase
			PreparedStatement stmt = connection.prepareStatement(sql);
			// Setando os valores
			stmt.setString(1, paciente.getNome());
			stmt.setString(2, paciente.getTelefone());
			stmt.setString(3, paciente.getEmail());
			stmt.setString(4, paciente.getSenha());
			stmt.setDate(5, new Date(paciente.getData().getTimeInMillis()));
			// Executa
			stmt.execute();
			stmt.close();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	// Método para remover dados da Agenda
	// Verificar uma correção para este método. Ao invés de deletar, o software
	// deve desativar o cadastro.
	public void remove(Paciente paciente) {
		String sql = "DELETE FROM Paciente WHERE idPaciente=?";
		try {
			PreparedStatement stmt = connection.prepareStatement(sql);
			stmt.setInt(1, paciente.getIdPaciente());
			stmt.execute();
			stmt.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public List<Paciente> getLista() {
		try {
			List<Paciente> pacientes = new ArrayList<Paciente>();
			PreparedStatement stmt = this.connection.prepareStatement("SELECT*FROM Paciente");
			ResultSet rs = stmt.executeQuery();

			while (rs.next()) {
				Paciente paciente = new Paciente();
				paciente.setIdPaciente(rs.getInt("idPaciente"));
				paciente.setNome(rs.getString("nome"));
				paciente.setTelefone(rs.getString("telefone"));
				paciente.setEmail(rs.getString("email"));
				pacientes.add(paciente);
			}
			rs.close();
			stmt.close();
			return pacientes;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void altera(Paciente paciente) {
		String sql = "UPDATE Paciente SET nome=?, telefone=?," + "email=?, WHERE idPaciente=?";
		try {
			PreparedStatement stmt = connection.prepareStatement(sql);
			stmt.setString(1, paciente.getNome());
			stmt.setString(2, paciente.getTelefone());
			stmt.setString(3, paciente.getEmail());
			stmt.setInt(5, paciente.getIdPaciente());
			stmt.execute();
			stmt.close();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
}

Classe RemoverPaciente

package br.com.consultaai.mvc.logica;

import java.sql.Connection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.consultaai.dao.PacienteDao;
import br.com.consultaai.model.Paciente;

public class RemoverPaciente implements Logica {

	@Override
	public String executa(HttpServletRequest req, HttpServletResponse res) throws Exception {
		int idPaciente = Integer.parseInt(req.getParameter("idPaciente"));
		Paciente paciente = new Paciente();
		paciente.setIdPaciente(idPaciente);
		Connection connection = (Connection) req.getAttribute("conexao");
		PacienteDao dao = new PacienteDao(connection);
		dao.remove(paciente);
		return "lista-pacientes.jsp";
	}

}

Classe ListarPaciente

package br.com.consultaai.mvc.logica;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.consultaai.dao.PacienteDao;
import br.com.consultaai.model.Paciente;

public class ListaPaciente implements Logica {

	@Override
	public String executa(HttpServletRequest req, HttpServletResponse res) throws Exception {
		List<Paciente> pacientes = new PacienteDao().getLista();
		// Guarda a lista no Request
		req.setAttribute("pacientes", pacientes);
		return "lista-pacientes.jsp";
	}

}

JSP lista-pacientes

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="ConsultaAí - Lista de Pacientes">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap-responsive.css">
<link rel="stylesheet" href="css/style.css">
<title>ConsultaAí - Lista Pacientes</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
	window.jQuery
			|| document
					.write('<script src="js/jquery-1.7.1.min.js"><\/script>')
</script>
<script type="text/javascript" src="js/bootstrap.js"></script>
</head>
<body>
	<div class="container-fluid">
		<div class="row-fluid">
			<div class="span12">
				<!-- Cabeçalho -->
				<c:import url="header.jsp" />
				<h3>Seja bem vindo ao ConsultaAí!</h3>
				<h4>Login</h4>
				<form action="">
					<label>E-mail</label> <input type="email" name="email"
						required="required"><br /> <label>Senha</label> <input
						type="password" name="senha" required="required"><br /> <input
						type="submit" value="Entrar">
				</form>
				<h4>Cadastro</h4>
				<c:import url="cadastro-medico.jsp" />
				<br />
				<c:import url="cadastro-paciente.jsp" />
				<br />
				<table class="table table-striped table-bordered">
					<thead>
						<tr>
							<th>Nome</th>
							<th>Telefone</th>
							<th>E-mail</th>
							<th>Remover</th>
							<th>Editar</th>
						</tr>
					</thead>
					<tbody>
						<!-- Percorre os contatos montando as linhas das tabelas -->
						<c:forEach var="paciente" items="${pacientes}">
							<tr>
								<td>${paciente.nome}</td>
								<td>${paciente.telefone}</td>
								<td><c:if test="${not empty paciente.email}">
										<a href="mailto:${paciente.email}">${paciente.email}</a>
									</c:if> <c:if test="${empty paciente.email }">
									E-mail não informado.
								</c:if></td>
								<!--Verificar erro de conversão de data oriunda do Calendar  
								<td><fmt:formatDate value="${paciente.data.time}"
									pattern="dd/MM/yyyy" /></td>-->
								<!-- Remover com MVC -->
								<td><a
									href="mvc?logica=RemoverPaciente&idPaciente=${paciente.idPaciente}">X</a></td>
								<td><a href="mvc?logica=AlteraPaciente">Editar</a></td>
							</tr>
						</c:forEach>
					</tbody>
				</table>
				<!-- Rodapé -->
				<c:import url="footer.jsp" />
			</div>
		</div>
	</div>
</body>
</html>