Paginação web

6 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"> </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%"> </td>
                  <td width="20%"> </td>
                  <td width="22%"> </td>
                  <td width="22%"> </td>
                  <td width="9%"> </td>
        </tr>
                <tr>
                  <td> </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> </td>
                </tr>
                <tr>
                  <td> </td>
                  <td><div align="center"><%= rst.getString("efetuadas") %></div></td>
                  <td><div align="center"><%= rst.getString("recebidas") %></div></td>
                  <td> </td>
                  <td> </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>
            &lt;/fieldset&gt;
            &lt;/td&gt;
            &lt;td width="8%"&gt;&nbsp;&lt;/td&gt;
          &lt;/tr&gt;
        
    <p>&nbsp;</p>
    <p>&nbsp; </p>
              
    &lt;/table&gt;                     
            
            &lt;% 
            
            }               
            } 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();
            }
            %&gt;
&lt;/body&gt;
    
&lt;/html&gt;

Abraços galera.

6 Respostas

S
O galera passei o codigo errado, segue o certo:
&lt;%@ page language="java" import="java.sql.*" %&gt;
&lt;html&gt;
&lt;head&gt;&lt;title&gt;&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;%

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() + "&lt;br&gt;");
    out.println("SQLState: " + ex.getSQLState() + "&lt;br&gt;");
    out.println("VendorError: " + ex.getErrorCode() + "&lt;br&gt;");
  }
  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();
  
  %&gt;
  &lt;table border="0"&gt;
  &lt;tr&gt;&lt;th&gt;Ramal&lt;/th&gt;&lt;th&gt;Ligações efetuadas&lt;/th&gt;&lt;th&gt;Ligações recebidas&lt;/th&gt;&lt;/tr&gt;
   
  &lt;% 
  while(rs2.next()) {
    
      out.print("&lt;tr&gt;\n&lt;td&gt;" + rs2.getString("RAMAL") + "&lt;/td&gt;");
      out.print("&lt;td&gt;" + rs2.getString("efetuadas") + "&lt;/td&gt;");
      out.print("&lt;td&gt;" + rs2.getString("recebidas") + "&lt;/td&gt;");
      out.print("&lt;/tr&gt;&lt;/td&gt;\n&lt;/tr&gt;");
      
	
    //int id = rs2.getInt("RAMAL");
    //out.println("ID: " + id + "&lt;br&gt;");
    //String nome = rs2.getString("N_DISCADO");
    //out.println("NOME: " + nome + "&lt;br&gt;");
    //int idade = rs2.getInt("OPERADORA");
    //out.println("IDADE: " + idade + "&lt;br&gt;&lt;br&gt;");
      

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

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

&lt;/body&gt;
&lt;/html&gt;
G

Faz tempo que não vejo um código assim. o ideal é você não ter nenhum código java nos JSPs. Leia um pouco sobre MVC.

A Displaytag é uma excelente taglib para criação de grids com paginação e tudo mais que for preciso. É fácil de estender utilizando Decorators, css, etc.

Recomendo fortemente que você troque esse código pela Displaytag. Quais os problemas que você teve com ela ?

L

Nem deu pra ler o código :smiley: Tenta reestruturar sua aplicação cara… mistrurar java com html fica muito ruim

S

Boa concordo com os amigos …

MAIS COMO FALEI ALGUM PODERIA ME PASSAR CODIGO EXEMPLO MAIS LIMPO.

Agradeço a ajuda dos amigos…

Mais aqui mandar ir no displaytag como exemplo … ja fui diversas vezes e não conseguir desenvolver …

Um dos amigos poderiam me ajudar?

abraços

S

O galera vamos ajudar pow

G

Mais mastigado do que os exemplos do site e pacote de download da Displaytag você não vai encontrar.

http://displaytag.sourceforge.net/11/

Criado 24 de julho de 2008
Ultima resposta 30 de jul. de 2008
Respostas 6
Participantes 3