Artigo estraído do site: www.portaljava.com
Autor: Wendell Miranda
Paginação com JSP e MySQL
Bom, este tutorial é bem simples. Utilizei apenas Scriptles para fazer a paginação no banco de dados MySQL.
É um código bem simples e fácil de entender. Ao testar sua paginação não esqueça de colocar o parâmetro na sua url:
Exemplo: http://localhost:8080/site/page.jsp?pr=0
<%@ page language="java" import="java.sql.*" errorPage="" %><% int limitePorPagina = 5; String pr1 = request.getParameter( "pr" ); try{ Class.forName( "com.mysql.jdbc.Driver" ).newInstance(); } catch( Exception ex ){ out.write( "Não carregou o Driver: " + ex.toString() ); } Connection conn = DriverManager.getConnection( "jdbc:mysql://10.155.251.9/cdrom?user=root&pass=" ); PreparedStatement pstmt = conn.prepareStatement( "SELECT * FROM responsavel LIMIT " + pr1 + "," + String.valueOf( limitePorPagina )); PreparedStatement pstmt2 = conn.prepareStatement( "SELECT count(*) as c FROM responsavel" ); ResultSet resultado = pstmt.executeQuery(); ResultSet rs2 = pstmt2.executeQuery(); rs2.next(); int totalregs = Integer.parseInt( rs2.getString( "c" ) ); int totalpgs = Math.round( totalregs / limitePorPagina ); if( ( totalregs % limitePorPagina ) > 0 ) totalpgs++; int pr = Integer.parseInt( request.getParameter( "pr" ) ); %> <% while( resultado.next() ){ String id = resultado.getString( "id_responsavel" ); String nm = resultado.getString( "nm_resp" ); String mail = resultado.getString( "email_resp" ); %> <%=id%>| <%=nm%>| <%=mail%><br><% }%><% if( pr > 0 ){%>[<a href="?pr=0">Primeira Página</a>][<a href="?pr=<%=pr-limitePorPagina%>">Anteriores</a>]<% }%><% if( pr < ( totalpgs * limitePorPagina ) - limitePorPagina ){%>[<a href="?pr=<%=pr+limitePorPagina%>">Próximo</a>][<a href="?pr=<%=( totalpgs * limitePorPagina ) - limitePorPagina%>">Ultima</a>] <% }%>