Hello everyone, I'm studying JavaWeb and I came across a boring bug !! I already researched a lot on the subject but I could not solve this error.
I have this method that is pulling all data from the "contacts" table of the database and returning it in a list.
public ArrayList<User> buscarTodos() {
//Monta a Query
String sql = "select * from contatos";
//Constroi PreparedStatement com SQL
ArrayList<User> lista = new ArrayList<User>();
try {
PreparedStatement preparador = con.prepareStatement(sql);
ResultSet resultado = preparador.executeQuery();
while (resultado.next()){
User contato = new User();
contato.setContato_id(resultado.getInt("contato_id"));
contato.setContato_nome(resultado.getString("contato_nome"));
contato.setContato_tel(resultado.getString("contato_tel"));
contato.setContato_email(resultado.getString("contato_email"));
contato.setContato_sobrenome(resultado.getString("contato_sobrenome"));
lista.add (contato);
}
preparador.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return lista;
}
But when I go to show this list it returns only the last repeated contact in several times, as in the image below:
Followthecodebycallingthemethod:
protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{System.out.println("Chamando Método Get");
String acao = request.getParameter("acao");
UsuarioDAO contatoDAO = new UsuarioDAO();
if (acao!= null && acao.equals("exc") ) {
String id = request.getParameter("id");
User contato = new User();
contato.setContato_id(Integer.parseInt(id));
contatoDAO.excluir(contato);
}
List<User> lista = contatoDAO.buscarTodos();
//Atribuir a Lista no request
request.setAttribute("lista", lista );
//Encaminhando para o JSP
RequestDispatcher saida= request.getRequestDispatcher("exibeContatos.jsp");
saida.forward(request, response);
}
Can you help me?
Thank you!