how to retrieve a list of data and display in jsp

1

Good evening, I'm not able to display a list that is saved in the database on the jsp page. I would like to know how I do, tried some forms, call the menagerBean and the servlet

jsp calling by servlet

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@page import="entity.*, persistence.*"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:useBean id="mb" class="manager.ManagerBean" scope="request"/>
<!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=ISO-8859-1">
<title>Times</title>
</head>
<body>
<form id="vt" action="Controle?cmd=listar" method="get">
<table border=1 >

        <tr>
            <th> Codigo </th>
            <th> Nome </th>
            <th> Email</th>
            <th> Sexo</th>
            <th> Nascimento</th>
            <th> Time</th>      

        </tr>



    <c:forEach  var="linha" items="${listar}" >

        <tr>
            <td> ${linha.idTorcedor}</td>       
            <td> ${linha.nome}</td>
            <td> ${linha.email}</td>
            <td> ${linha.sexo}</td>
            <td> ${linha.dataNascimento}</td>
            <td> ${linha.time}</td>

        </tr>
    </c:forEach>

</table>
</form>



</body>
</html>

jsp calling by manager bean

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@page import="entity.*, persistence.*"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:useBean id="mb" class="manager.ManagerBean" scope="request"/>
<!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=ISO-8859-1">
<title>Times</title>
</head>
<body>
<form id="vt" action="Controle?cmd=listar" method="get">
<table border=1 >

        <tr>
            <th> Codigo </th>
            <th> Nome </th>
            <th> Email</th>
            <th> Sexo</th>
            <th> Nascimento</th>
            <th> Time</th>      

        </tr>



    <c:forEach  var="linha" items="${listar}" >

        <tr>
            <td> ${linha.idTorcedor}</td>       
            <td> ${linha.nome}</td>
            <td> ${linha.email}</td>
            <td> ${linha.sexo}</td>
            <td> ${linha.dataNascimento}</td>
            <td> ${linha.time}</td>

        </tr>
    </c:forEach>

</table>
</form>



</body>
</html>

ManagerBean

package manager;

import java.util.List;

import entity.Torcedor;
import persistence.TorcedorDao;

public class ManagerBean {
    private List<Torcedor>torcedores;

    public ManagerBean() {
        // TODO Auto-generated constructor stub
    }

    public List<Torcedor> getTorcedores() {
        try{
            TorcedorDao td = new TorcedorDao();
            torcedores = td.findAll();
        }catch(Exception e){

        }
        return torcedores;

    }

    public void setTorcedores(List<Torcedor> torcedores) {
        this.torcedores = torcedores;
    }


}

servlet

package control;

import java.io.IOException;
import java.util.Date;

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 entity.Torcedor;
import persistence.TorcedorDao;

/**
 * Servlet implementation class Controle
 */
@WebServlet("/Controle")
public class Controle extends HttpServlet {
    private static final long serialVersionUID = 1L;


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String cmd = request.getParameter("cmd");
        if(cmd.equalsIgnoreCase("listar")){
            listar(response,request);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String cmd = request.getParameter("cmd");
        if(cmd.equalsIgnoreCase("login")){
            login(response,request);
        }

        if(cmd.equalsIgnoreCase("gravar"));
        gravar(request,response);
    }
    protected void gravar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String msg= "";

        try {
            String nome = request.getParameter("nome");
            String email = request.getParameter("email");
            String sexo = request.getParameter("sexo");
            String dataNascimento= request.getParameter("dataNascimento");
            String time= request.getParameter("time");

            Torcedor t= new Torcedor(null,nome,email,sexo,dataNascimento,time);
            new TorcedorDao().gravar(t);
            msg="Dados Gravados com Sucesso";


        } catch (Exception e) {
            msg = "Erro" + e.getMessage();
            e.printStackTrace();

        }finally{
            request.setAttribute("msg", msg);
            request.getRequestDispatcher("visualizarTime.jsp").forward(request,response);
        }
    }

    protected void login (HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        String email = request.getParameter("email");
        Torcedor torcedor = null;
        try{
            torcedor= new TorcedorDao().findByEmail(email);

                request.setAttribute("torcedor", torcedor);
                if(email==null){                
                request.getRequestDispatcher("visualizarTime.jsp").forward(request, response);
                request.setAttribute("listar", new TorcedorDao().findAll());
                }else{
                    request.getRequestDispatcher("cadastrarTorcedor.jsp").forward(request, response);;
                }

        }catch (Exception e) {
            e.printStackTrace();


        }


    }
    protected void listar (HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        try{
            request.setAttribute("listar", new TorcedorDao().findAll());
            request.getRequestDispatcher("visualizarTime.jsp").forward(request,response);
        }catch(Exception e){
            e.printStackTrace();

        }finally {

        }
    }
}
    
asked by anonymous 20.04.2017 / 04:43

1 answer

1

@Mattos (it was last year but still useful!) I implemented / deployed your application on netBeans8 / TomCat8, with minor customizations and worked perfectly: I created an 'index.jsp' (in the root of the Web Context):

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
<c:url var="rootURL" value="/"/>
                    <!-- -->        <h1>Hello World!</h1>
        <a href="${rootURL}Controle?cmd=listar"> Servlet</a>
    </body>
</html>

.. the Servlet 'Control':

/**
 * @author derlon.aliendres
 */
@WebServlet(name = "Controle", urlPatterns = {"/Controle"})
public class Controle 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 {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            //...;
            out.println("</html>");
        }
    }
    protected Collection<Torcedor> listarTodos() {
        List<Torcedor> lstTorcedores = new ArrayList<Torcedor>(2);
        lstTorcedores.add(new Torcedor(null, "nome", "email", "sexo", "dataNascimento", "time") );
        lstTorcedores.add(new Torcedor(null, "eu", "email", "M", "01/01/2000", "Flamengo") );
        return lstTorcedores;
    }
   protected void listar(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        try{
            request**.getSession()**.setAttribute("listar", listarTodos()/*new TorcedorDao().findAll()*/);
            request.getRequestDispatcher("visualizarTime.jsp").forward(request,response);
        }catch(Exception e){
            e.printStackTrace();

        }finally {

        }
    }
    // <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 {
        String cmd = request.getParameter("cmd");
        if(cmd.equalsIgnoreCase("listar")){
            listar(response,request);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String cmd = request.getParameter("cmd");
        if(cmd.equalsIgnoreCase("login")){
            login(response,request);
        }

        if(cmd.equalsIgnoreCase("gravar"));
        gravar(request,response);
    }
    protected void gravar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String msg= "";

        try {
            String nome = request.getParameter("nome");
            String email = request.getParameter("email");
            String sexo = request.getParameter("sexo");
            String dataNascimento= request.getParameter("dataNascimento");
            String time= request.getParameter("time");

            Torcedor t= new Torcedor(null,nome,email,sexo,dataNascimento,time);
        //    new TorcedorDao().gravar(t);
            msg="Dados Gravados com Sucesso";


        } catch (Exception e) {
            msg = "Erro" + e.getMessage();
            e.printStackTrace();

        }finally{
            request.setAttribute("msg", msg);
            request.getRequestDispatcher("visualizarTime.jsp").forward(request,response);
        }
    }

    protected void login (HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        String email = request.getParameter("email");
        Torcedor torcedor = null;
        try{
        //    torcedor= new TorcedorDao().findByEmail(email);

                request.setAttribute("torcedor", torcedor);
                if(email==null){                
                request.getRequestDispatcher("visualizarTime.jsp").forward(request, response);
        //        request.setAttribute("listar", new TorcedorDao().findAll());
                }else{
                    request.getRequestDispatcher("cadastrarTorcedor.jsp").forward(request, response);;
                }

        }catch (Exception e) {
            e.printStackTrace();


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


}

and last (but not least) to 'viewTime.jsp':

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page import="entity.*"%>
<%--, persistence.*<jsp:useBean id="mb" class="manager.ManagerBean" scope="request"/>--%>
<!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=ISO-8859-1">
<title>Times</title>
</head>
<body>
<form id="vt" action="Controle?cmd=listar" method="get">
<table border=1 >
        <tr>
            <th> Codigo </th>
            <th> Nome </th>
            <th> Email</th>
            <th> Sexo</th>
            <th> Nascimento</th>
            <th> Time</th>      
        </tr>
    <c:forEach  var="linha" items="${listar}" >
        <tr>
            <td> ${linha.idTorcedor}</td>       
            <td> ${linha.nome}</td>
            <td> ${linha.email}</td>
            <td> ${linha.sexo}</td>
            <td> ${linha.dataNascimento}</td>
            <td> ${linha.time}</td>
        </tr>
    </c:forEach>
</table>

</form>

</body>
</html>

And the result:

    
16.01.2018 / 19:06