paginação web

10 respostas
S

Boa galera boa tarde a todos,
Assunto paginação:
Temos poucos recursos, certo?
Tentei utilizar as taglib ( display e Page ) sem sucesso ( caso algum amigo tenha um exemplo que possa me passar agradeço [email removido] ).
Recentemente consegui um código bem legal e fácil, nem tudo na vida são rosas... tem uma parte no código que ainda não resolvi e solicito aos amigos ajuda.

Estou recebendo a clausula and por request.getParameter , qual o erro?
Quando clicko no link para o próximo grupo de dados, a pagina fica em branco come se não tivesse dados ... Melhor não passa a String . Teria solução para isso?
Pensei em que, ao invés de receber a passar direto para query, fazer o seguinte armazenar e daí passar para query.... mais infelizmente não sei como fazer, os amigos poderiam me ajudar?

<style type="text/css">
<!--
body,td,th {
	font-family: Verdana;
	font-size: 10px;
	color: #000000;
}
a:link {
	color: #9966FF;
}
a:visited {
	color: #9966FF;
}
a:hover {
	color: #FF0000;
}
.style2 {color: #FFFFFF}
.style3 {color: #FF0000}
body {
	margin-top: 0px;
}
-->
</style>

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ page language="java" %>
<%@ page import="java.sql.*"%>
<%@ page import="java.sql.Date"%>
<%--
The taglib directive below imports the JSTL library. If you uncomment it,
you must also add the JSTL library to the project. The Add Library... action
on Libraries node in Projects view can be used to add the JSTL 1.1 library.
--%>
<%--
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
--%>

<!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=utf-8">
        <title></title>
    </head>
    <body>
       
          <%  
       String setor2 = (String) request.getParameter("grupo");
       
      %> 
          
      <%
    //Connection con = null;
    
    Statement st  = null;
    ResultSet rs   = null;  
    ResultSet rst  = null;             
                
                
                try {
                    String setor = (String) request.getParameter("grupo");
		            String setor3 = (String) request.getParameter("grupo");
                    
  //String dsn     = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:/Atn/DB/RJJ0802.mdb";
  //String usuario = "";
  //String senha   = "";
  //String sql     = "";
  //Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
  //Connection con = DriverManager.getConnection(dsn,usuario,senha);
  
        String url="jdbc:mysql://localhost:3306/shelter"; 
		Class.forName("org.gjt.mm.mysql.Driver");
		Connection con = DriverManager.getConnection(url, "root", "1272");
  
      %>
      <%
			  			 
  st = con.createStatement();
  rst = st.executeQuery
          //("Select * from Ramal");
           
		  //("Select  Sum(IIf(CRJJ02.tipo = 0, 1, 0)) As efetuadas, Sum(IIf(CRJJ02.tipo = 1, 1, 0)) As recebidas From Ramal, CRJJ02 " +
           //"where Ramal.ramal = CRJJ02.origem And grupo = '"+ setor3 +"' And data = date() ");
           
		   ("select count(recebida) as recebidas, count(n_discado) as efetuadas From tb_ligacoes L, ramal R " + 
		   "where R.ramal = L.ramal And R.grupo = '"+ setor3 +"' ");
		   
		   
            while (rst.next()){
            
        %>
        <%
  st = con.createStatement();
  rs = st.executeQuery
         // ("Select ramal, Sum(IIf(CRJJ02.tipo = 0, 1, 0)) As efetuadas, Sum(IIf(CRJJ02.tipo = 1, 1, 0)) As recebidas From Ramal, CRJJ02 " +
          // "where Ramal.ramal = CRJJ02.origem And grupo = '"+ setor +"' And data = date() Group by Ramal.ramal");
		  
		  ("select  R.ramal, count(recebida) as recebidas, count(n_discado) as efetuadas From tb_ligacoes L, ramal R " + 
		   "where R.ramal = L.ramal And R.grupo = '"+ setor +"' Group by R.ramal ");                  
          %>
        <table width="100%">
          <tr>
            <td width="2%" height="125">&nbsp;</td>
            <td width="90%"><fieldset>
              <legend>Sumário por ramal referente ao setor:<span class="style3"> <%=setor2%></span></legend>
<table width="100%">
                <tr>
                  <td width="27%">&nbsp;</td>
                  <td width="20%">&nbsp;</td>
                  <td width="22%">&nbsp;</td>
                  <td width="22%">&nbsp;</td>
                  <td width="9%">&nbsp;</td>
        </tr>
                <tr>
                  <td>&nbsp;</td>
                  <td><div align="center">Ligações Efetuadas</div></td>
                  <td><div align="center">Ligações Recebidas</div></td>
                  <td><div align="center">Ligações não atendidas</div></td>
                  <td>&nbsp;</td>
                </tr>
                <tr>
                  <td>&nbsp;</td>
                  <td><div align="center"><%= rst.getString("efetuadas") %></div></td>
                  <td><div align="center"><%= rst.getString("recebidas") %></div></td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                </tr>
              </table>
          <table width="100%">
<tr bordercolor="#CCCCCC" bgcolor="#CCCCCC">
                  <td width="21%" bgcolor="#006699"><span class="style2"></span></td>
          <td width="12%" bgcolor="#006699"><div align="center" class="style2">Ramal</div></td>
          <td width="21%" bgcolor="#006699"><div align="right" class="style2">Ligações Efetuadas</div></td>
          <td width="26%" bgcolor="#006699"><div align="right" class="style2">Ligações Recebidas</div></td>
          <td width="20%" bgcolor="#006699"><span class="style2"></span></td>
            </tr>
              </table>
            <%
			  while (rs.next()){
                          String grupo = rs.getString("ramal");  
                                                
           %>
<table width="100%">
                <tr>
                  <td width="21%"><div align="center"></div></td>
                  <td width="12%"><div align="center"><% out.print ( "<a href='centroSetor4.jsp?grupo=" +grupo+ "' target=centro>"+grupo+"</a>"); %></div></td> 
                  <td width="19%"><div align="right"><%= rs.getString("efetuadas") %></div></td>
                  <td width="26%"><div align="right"><%= rs.getString("recebidas") %></div></td>
                  <td width="22%"></td> 
                </tr>
            </table>
<%
			  }
              %>
              <p>&nbsp;</p>
            </fieldset>
            </td>
            <td width="8%">&nbsp;</td>
          </tr>
        
    <p>&nbsp;</p>
    <p>&nbsp; </p>
              
    </table>                     
            
            <% 
            
            }               
            } catch (Exception ex) {
            ex.printStackTrace();
            } finally {
            if (rst != null) rst.close();
            if (rs != null) rs.close();
            if (st != null) st.close();
           // if (con != null) con.close();
            }
            %>
</body>
    
</html>

ou caso alguem tenha um codigo exemplo, passe por favor para o e-mail acima.

Grato

10 Respostas

S
o galera foi mal passei o codigo errado, segue o certo:
<%@ page language="java" import="java.sql.*" %>
<html>
<head><title></title>
</head>
<body>

<%

String setor = (String) request.getParameter("grupo");
	//String setor3 = (String) request.getParameter("grupo");
	  
  
 
  String url = "jdbc:mysql://localhost/shelter";
  String usuario = "root";
  String senha = "1272";
  
  Connection conn = null;
  
  try{
  
  	
					
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    conn = DriverManager.getConnection(url, usuario, senha);
  }
  catch(SQLException ex){
    out.println("SQLException: " + ex.getMessage() + "<br>");
    out.println("SQLState: " + ex.getSQLState() + "<br>");
    out.println("VendorError: " + ex.getErrorCode() + "<br>");
  }
  catch(Exception e){
    out.println("Problemas ao tentar conectar com o banco de dados");
  }
  
  // conn é a conexão com o banco de dados
  int limit = 15; // quantidade de resultados por página                
  
  // obtém a quantidade de registros
  PreparedStatement pstmt = conn.prepareStatement
  ("select count(*) as c From ramal R where R.grupo = '"+ setor +"' ");                  
  
  //("select count(*) as c From tb_ligacoes L, ramal R where R.ramal = L.ramal And R.grupo = ativos ");     
  // ("SELECT COUNT(*) AS c FROM TB_LIGACOES where ramal = 1037");
  ResultSet rs = pstmt.executeQuery();
  rs.next();
  int total_rows = Integer.parseInt(rs.getString("c"));
  

  String pagina = request.getParameter("pagina"); // página atual
  if(pagina == null){
    pagina = "1";
  }
  
  int limitValue = (Integer.parseInt(pagina) * limit) - limit;  
  
  PreparedStatement pstmt2 = conn.prepareStatement
  ("select  R.ramal, count(recebida) as recebidas, count(n_discado) as efetuadas From tb_ligacoes L, ramal R " + 
   "where R.ramal = L.ramal And R.grupo = '"+ setor +"' Group by R.ramal LIMIT " + limitValue + ", " + limit );                  
  
  
 // ("SELECT * FROM TB_LIGACOES where ramal = 1037 LIMIT " + limitValue + ", " + limit);
  ResultSet rs2 = pstmt2.executeQuery();
  
  %>
  <table border="0">
  <tr><th>Ramal</th><th>Ligações efetuadas</th><th>Ligações recebidas</th></tr>
   
  <% 
  while(rs2.next()) {
    
      out.print("<tr>\n<td>" + rs2.getString("RAMAL") + "</td>");
      out.print("<td>" + rs2.getString("efetuadas") + "</td>");
      out.print("<td>" + rs2.getString("recebidas") + "</td>");
      out.print("</tr></td>\n</tr>");
      
	
    //int id = rs2.getInt("RAMAL");
    //out.println("ID: " + id + "<br>");
    //String nome = rs2.getString("N_DISCADO");
    //out.println("NOME: " + nome + "<br>");
    //int idade = rs2.getInt("OPERADORA");
    //out.println("IDADE: " + idade + "<br><br>");
      

	
  }
  
  %>
  </tr>
        </table>
  
  <%
  int anterior;
  if(Integer.parseInt(pagina) != 1){  
    anterior = Integer.parseInt(pagina) - 1; 
    out.println("<a href=?pagina=" + anterior + ">" + limit + " Anteriores</a>");
  }
  else 
    out.println(limit + " Anteriores ");
    
  int numOfPages = total_rows / limit;  
  int i;
  
  for(i = 1; i <= numOfPages; i++){ 
    if(i == Integer.parseInt(pagina)){ 
      out.println("<b>" + i + "</b> "); 
    }
    else{ 
      out.println("<a href=?pagina=" + i + ">" + i + "</a> ");  
    } 
  }
  
  if((total_rows % limit) != 0){ 
    if(i == Integer.parseInt(pagina)){ 
      out.println(i + " "); 
    }
    else{ 
      out.println("<a href=?pagina=" + i + ">" + i + "</a> "); 
    } 
  } 

  int proxima;
  if((total_rows - (limit * Integer.parseInt(pagina))) > 0){ 
    proxima = Integer.parseInt(pagina) + 1; 
          
    out.println("<a href=?pagina=" + proxima + ">Próximos " + limit + "</a>");  
  }
  else 
    out.println("Próximos " + limit);   
%>

</body>
</html>
P

estou em busca da solução do mesmo problema se alguém souber gostaria tb…

de saber como é …

S

Vamos manter contato… quem arrumar ajuda o outro
msn [email removido]

Pedrosa

Você já tentou usar a displaytag, é simples e seu código fica bem mais limpo:
http://displaytag.homeip.net/displaytag-examples-1.1/example-paging.jsp

A idéia é jogar uma lista no request e pronto a taglib se vira montando para você.

renanpto

Pedrosa:
Você já tentou usar a displaytag, é simples e seu código fica bem mais limpo:
http://displaytag.homeip.net/displaytag-examples-1.1/example-paging.jsp

A idéia é jogar uma lista no request e pronto a taglib se vira montando para você.


Isso ai, essa é a melhor solucao.
E ainda voce consegue otimizar a paginacao pegando os parametros (numero da pagina corrente, coluna para ordenar,etc) da display tag para montar o sql.

Flw

S

Ta mais oq não consigo e montar o ambiente .
Voce poderia me passar um ex. de tag.

tipo vou usar um bd mysql … e uso o netbeans 5.5…

agradeço pelo ajuda.
Valmir lopes.

S

o galera vamos ajudar aí

saoj

http://forum.mentaframework.org/posts/list/193.page#3276

Tags simples e vc tem uma paginação completa de qualquer lista no estilo Google.

E vc ainda pode customizar a vontade no seu html.

hiroc

exemplo mto fácil e bom de paginação sem usar displaytag…

http://www.laliluna.de/struts-paging-tutorial.html

hiroc

opa, tem um exemplo também usando displaytag no msmo link

Criado 24 de julho de 2008
Ultima resposta 29 de jul. de 2008
Respostas 10
Participantes 6