Return a SELECT * FROM" in the Javaweb browser

Asked

Viewed 245 times

0

Hello guys I am studying Javaweb and I came across a boring mistake!! I’ve done a lot of research on the subject but I couldn’t solve this mistake.

I have this method that is pulling all data from the table "contacts" from the database and returning 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 will display this list it returns only the last repeated contact several times, as in the image below: inserir a descrição da imagem aqui

Follow the code by calling the method:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, 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!

3 answers

1

tested here and rode! , passes its JSP to see how this foreach.

public List<User> buscarTodos() throws Exception {

    List<User> results = new ArrayList<>();
    String sql = "SELECT * FROM contatos;";

    try (PreparedStatement stmt = con.prepareStatement(sql); 
            ResultSet resultSet = stmt.executeQuery()) {

        while (resultSet.next()) {
            results.add(populate(resultSet));
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {

    }
    return results;
}

// population with this method

private User populate(ResultSet resultado) throws SQLException {

    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"));

    return contato;
}

0

Some tips that can help you:

1) Check your table in the database.

2) Check the List returned exactly by DAO, without going through the screen.

3) Place the method of listing contacts in the constructor of the class. Because GET can be called for each row of the table.

4) Try to pass your SQL as parameter executeQuery

        ResultSet rs = statement.executeQuery(sql.toString());

0

Follow the JSP:

(It was giving error when I put it complete so follow the image with the markers "<% %>".) inserir a descrição da imagem aqui

List<User> lista = (List<User>) request.getAttribute("lista");

for (User contato : lista){



<tr>
<td><%= contato.getContato_id() %> </td> 
<td><%= contato.getContato_nome() %></td>
<td><%= contato.getContato_sobrenome()%></td> 
<td><%= contato.getContato_tel() %></td> 
<td><%= contato.getContato_email() %></td>
<td><a href = "contatocontroller.do?acao=exc&id=<%= contato.getContato_id() %>">Excluir

    <a href = "contatocontroller.do?acao=alt&id=<%= contato.getContato_id() %>">Alterar
</td>
</tr>


<%

} 

%>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.