Como Listar do mysql para o JSP

Boa tarde, estou tentando exibir uma lista pelo jsp, tentei chamar do servlet e do managerBean e nao consegui, alguem me socorre…rsrsrs.

Chamando do ManagerBean

<%@ 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>

<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 items="${mb.torcedores }" var="linha">

		<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>

${msg}


</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;
	}
	

}

Cadê o servlet que gerencia isso?
Faltou mandar pra view (pagina jsp)

Vê isso aqui e qualquer duvida pode chamar.
https://github.com/lukaz-sampaio/simple-java-crud/tree/master/src/java/pessoa

eu chamei pelo managerBean e tbm chamei pelo servlet

esse é o 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("cadastrarTorcedor.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(torcedor!=null){				
				request.getRequestDispatcher("visualizarTime.jsp");
				}else{
					request.getRequestDispatcher("cadastrarTorcedor.jsp");
				}
			
		}catch (Exception e) {
			e.printStackTrace();
			
			
		}
				
	
	}
	protected void listar (HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
		try{
			request.setAttribute("lst", new TorcedorDao().findAll());
		}catch(Exception e){
			e.printStackTrace();
		
		}finally {
			request.getRequestDispatcher("visualizarTime.jsp");
		}
	}
}

quando chamo pelo servlet faço dessa forma

<%@ 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 items="${mb.torcedores}" var="linha">

		<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>
${msg}


</body>
</html>

Essa linha

<c:forEach items="${mb.torcedores}" var="linha">

Não deveria ser o parâmetro atribuido no request?

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

Creio que você está confundindo os conceitos, ManagerBean é coisa do JSF e você está usando JSP, são coisas diferentes… além do mais JSF usa variáveis com #{} em arquivos .xhtml e JSP usa com ${} em arquivos .jsp

ja coloquei dessa forma, porem nao busca os dados do banco

Alguma mensagem de erro?

Outra, você não está encaminhando corretamente no método listar…

request.getRequestDispatcher("visualizarTime.jsp");

Não seria

request.getRequestDispatcher("visualizarTime.jsp").forward(request, response);

o problema que ele nao esta resgatando os dados do banco, a pagina abre, só nao vem com os dados

Alguem sabe como consigo listar no jsp, ja tentei todos o metodos ai em cima e nada.:disappointed_relieved:

Posta o método que faz o acesso ao banco. O método DAO que lista os dados.

No Sevlet:
Usa o método service(HttpServletRequest request, HttpServletResponse response) no lugar do doGet e do doPost.
Na criação do Tocedor (new Torcedor(null, ...)) tira o id do construtor e tira esse null daí tambem.

No .jsp:
O que é esse mb.torcedores? Sendo que tu tá mandando um attributo lst (request.setAttribute("lst", new TorcedorDao().findAll()))

Mais uma coisa. se tiver acc no github, coloca esses arquivos (os arquivos em questão: Servlet, jsp, classe DAO) como gist e manda o link.

mb.torcedores pq primeiro tentei chamar do managerBean depois tentei chamar pelo listar do servlet, so que nao funcionou nenhum dos dois jeitos

package persistence;

import java.util.ArrayList;
import java.util.List;



import entity.Torcedor;


public class TorcedorDao extends Dao {
	
	public void gravar(Torcedor t)throws Exception{
		open();
		
		stmt = con.prepareStatement("insert into torcedor values(null,?,?,?,?,?)");
		
		stmt.setString(1,t.getNome());
		stmt.setString(2, t.getEmail());
		stmt.setString(3,t.getSexo());
		stmt.setString(4, t.getDataNascimento());
		stmt.setString(5, t.getTime());
		stmt.execute();
		stmt.close();
		close();
		
	}
	
	public  List<Torcedor>findAll() throws Exception{
		open();
		
		stmt = con.prepareStatement("select*from torcedor");
		rs= stmt.executeQuery();
		List<Torcedor>lst = new ArrayList<Torcedor>();
		while(rs.next()){
		Torcedor t = new Torcedor();
		t.setIdTorcedor(rs.getInt("idTorcedor"));
		t.setNome(rs.getString("nome"));
		t.setEmail(rs.getString("email"));
		t.setSexo(rs.getString("sexo"));
		t.setDataNascimento(rs.getString("dataNascimento"));
		t.setTime(rs.getString("time"));
		lst.add(t);
				
	}
	close();
	return lst;
	}
	public Torcedor findByEmail(String t)throws Exception{
		open();
		
		stmt = con.prepareStatement("select*from torcedor where email =?");
		stmt.setString(1, t);
		rs = stmt.executeQuery();
		Torcedor to= null;
		if(rs.next()){
			to = new Torcedor();
			to.setIdTorcedor(rs.getInt("idTorcedor"));
			to.setNome(rs.getString("nome"));
			to.setEmail(rs.getString("email"));
			to.setSexo(rs.getString("Sexo"));
			to.setDataNascimento(rs.getString("dataNascimento"));
			to.setTime(rs.getString("time"));			
		
		}
		close();
		return to;
	}
}

Cara, agora que estou vendo, não faz sentido você ter um form mandando get…

<form id="vt" action="Controle?cmd=listar" method="get">

Se é apenas para listar, basta retirar esse form, pois se sua intenção é ele ser autosubmit esqueça. sem javascript não é possível essa função…

Deixe o doGet do Controle apenas para listar, sem precisar testar o cmd…

listar(response,request);

Por padrão, qualquer página é requisitada via get, logo você só precisa testar o cmd quando for post, pegou?

ficou assim , porem nao esta listando

protected void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		
    			listar(response, request);
    	}


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

    		}
    	}


    <%@ 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" %>

    <!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>
    <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>




    </body>
    </html>

Critiano, você já debugou nessa linha na hora que tu chama o findAll para ver se os dados estão vindo?
request.setAttribute(“listar”,new TorcedorDao().findAll());

Se sim, após carregar os dados e setar no atributo da requisição, você tem que “encaminhar” a requisição e resposta para a JSP, ai na JSP você referencia no items do forEach o atributo que você setou na requisição que no teu caso é o “listar”.

Ficaria mais ou menos assim:
request.setAttribute(“listar”, new TorcedorDao().findAll());
request.getRequestDispatcher(“visualizarTime.jsp”).forward(request, response);

Obrigado a todos por ajudarem, estava com um erro no banco de dados, apos resolver esse erro nao conseguia listar, para resolver esse problema utilizei criei a classe com o nome de managerBean para listar e chamei ela pelo jsp para exibir a lista, estarei postando como ficou a classe managerBean e o jsp.
OBS: Não consegui listar pelo servlet.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ page import="entity.*, persistence.*, java.util.*" %>

<jsp:useBean id="mb" scope="request" class="manager.ManagerBean"></jsp:useBean>

<!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>
<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="${mb.torcedores}">

		<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>




</body>
</html>

Essa foi a classe que utilizei para listar.

    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;
    	}
    	

    }

Que bom que conseguiu.
Uma coisa que achei interessante foi você usar o método close(); antes de do return list;.
Outra coisa que notei é que você tá usando isso solto. Ou seja, não está explicitando que quer abrir e fechar um PreparedStatement. Dá pra ver que você é iniciante, o importante é fazer funcionar, mas aconselho que depois de conseguir fazer funcionar, tente seguir boas práticas e busque sempre manter um código organizado.
E qualquer dúvida posterior não deixe de perguntar.