jsp分页访问数据库实用的例子介绍



jsp分页访问数据库实用的例子介绍.

在jsp开发中,在前台的数据展示页面,经常遇到这样的情况,很多条的数据,有几十上百条,而只显示10条,然后翻页显示下面的十条,如下图所示:

 

 

处理方式:一:首先sql语句,使用not in的方式处理,

在dao类里写一个方法

public List<> getAllByPage(int pageSize,pageNum){

……

 

String sql=”select top”+pageSize +” * from 表名x where 字段A not in (select top “+pageSize*(pageNum-1)+”  字段A from 表名x)”;

…….

rerun list;

}

其中,pageSize是页面要显示的条数,pageNum是要显示的页码,其中的sql语句基本是固定的,返回一个list对象。

二:在Biz里写一个方法,调用Dao里的这个getAllByPage方法,传入的也是两个参数,返回的也是list结果集。

三:在jsp页面以url传参的方式进行页面处理和数据的显示。

使用request对象获取传入的值,然后进行强制类型转换之后就可以作为参数,传入到Biz业务类的方法中去处理,返回的就是list结果集,然后使用表达式的方式在页面中进行显示就可以了。

综上:这就是分页显示数据的一个方法,

 

下面是一个小小的例子。


问题需求:开发一个小的留言板页面,页面能够以分页的形式显示所有留言信息,下放是一个发表留言的表单。

所有代码如下:

数据库如图:

实体类(entity)如下:

  1. package com.rz.entity;
  2. import java.util.Date;
  3. public class Message {
  4.     private int id;             //留言id
  5.     private String message;     //留言信息
  6.     private String author;      //留言作者
  7.     private Date postTime;      //留言时间
  8.     public int getId() {
  9.         return id;
  10.     }
  11.     public void setId(int id) {
  12.         this.id = id;
  13.     }
  14.     public String getMessage() {
  15.         return message;
  16.     }
  17.     public void setMessage(String message) {
  18.         this.message = message;
  19.     }
  20.     public String getAuthor() {
  21.         return author;
  22.     }
  23.     public void setAuthor(String author) {
  24.         this.author = author;
  25.     }
  26.     public Date getPostTime() {
  27.         return postTime;
  28.     }
  29.     public void setPostTime(Date postTime) {
  30.         this.postTime = postTime;
  31.     }
  32. }
package com.rz.entity;

import java.util.Date;

public class Message {
	private int id;				//留言id
	private String message;		//留言信息
	private String author;		//留言作者
	private Date postTime;		//留言时间

	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public Date getPostTime() {
		return postTime;
	}
	public void setPostTime(Date postTime) {
		this.postTime = postTime;
	}

}

 

 

dao类如下:(包括链接jdbc数据库)

  1. package com.rz.dao;
  2. import com.rz.entity.*;
  3. import java.sql.*;
  4. import java.util.*;
  5. public class MessageDao {
  6.     private String driver=”com.microsoft.sqlserver.jdbc.SQLServerDriver”;
  7.     private String url=”jdbc:sqlserver://localhost:1433;DataBaseName=message”;
  8.     private String name=”sa”;
  9.     private String password=”lishiyuzuji”;
  10.     /**
  11.      * 保存一条记录
  12.      * @param message
  13.      * @return
  14.      */
  15.     public int save(Message message){
  16.         int line=0;             //保存记录的行数
  17.         Connection con=null;
  18.         PreparedStatement pstat=null;
  19.         try{
  20.             con=getConn();
  21.             pstat=con.prepareStatement(“insert into TBL_MESSAGE(message,author,postTime) values(?,?,getdate())”);
  22.             pstat.setString(1,message.getMessage());
  23.             pstat.setString(2,message.getAuthor());
  24.             line=pstat.executeUpdate();
  25.         }catch(SQLException e){
  26.             e.printStackTrace();
  27.         }finally{
  28.             closeAll(null,pstat,con);
  29.         }
  30.         return line;
  31.     }
  32.     /**
  33.      * 分页显示信息
  34.      * @param pageSize 每页显示的信息数量
  35.      * @param pageNum  定位到那一页
  36.      * @return
  37.      */
  38.     public List<Message> listByPage(int pageSize,int pageNum){
  39.         Connection con=null;
  40.         PreparedStatement pstat=null;
  41.         ResultSet res=null;
  42.         List<Message> list=new ArrayList<Message>();
  43.         try{
  44.             con=getConn();
  45.             pstat=con.prepareStatement(“select top “+pageSize+
  46.                     ” * from TBL_MESSAGE where id not in (select top “+pageSize*(pageNum-1)+
  47.                     ” id from TBL_MESSAGE order by postTime) order by postTime”);
  48.             res=pstat.executeQuery();
  49.             while(res.next()){
  50.                 Message message=new Message();
  51.                 message.setId(res.getInt(1));
  52.                 message.setMessage(res.getString(2));
  53.                 message.setAuthor(res.getString(3));
  54.                 message.setPostTime(res.getDate(4));
  55.                 list.add(message);
  56.             }
  57.         }catch(SQLException e){
  58.             e.printStackTrace();
  59.         }finally{
  60.             closeAll(res,pstat,con);
  61.         }
  62.         return list;
  63.     }
  64.     /**
  65.      * 获得记录的总条数
  66.      * @return  返回查询到的所有记录的总条数
  67.      */
  68.     public int getAllUserCount(){
  69.         Connection con=null;
  70.         PreparedStatement pstat=null;
  71.         ResultSet res=null;
  72.         int ret = 0;
  73.         try{
  74.             con=getConn();
  75.             pstat=con.prepareStatement(“select count(*) from TBL_MESSAGE”);
  76.             res=pstat.executeQuery();
  77.             if(res.next()){
  78.                 ret=res.getInt(1);
  79.             }
  80.         }catch(SQLException e){
  81.             e.printStackTrace();
  82.         }finally{
  83.             closeAll(res,pstat,con);
  84.         }
  85.         return ret;
  86.     }
  87.     /**
  88.      * 连接数据库
  89.      */
  90.     public Connection getConn(){
  91.         Connection con=null;
  92.         try{
  93.             Class.forName(driver);
  94.             con=DriverManager.getConnection(url,name,password);
  95.         }catch(ClassNotFoundException e){
  96.             e.printStackTrace();
  97.         }catch(SQLException e){
  98.             e.printStackTrace();
  99.         }
  100.         return con;
  101.     }
  102.     /**
  103.      * 关闭数据库连接,而且三者是有顺序的,先关闭ResultSet连接,接着关闭Statement连接,最后关闭Connection连接
  104.      * 并且还要抛出异常。数据库连接使用完毕以后需要关闭连接的,否则,连接数据库的“通道”就会继续增加,而数据库的连接
  105.      * 能力也是有限的,大约是200个,因此需要在使用完数据库后将连接关闭掉。
  106.      * @param res
  107.      * @param stat
  108.      * @param conn
  109.      */
  110.     public void closeAll(ResultSet res,PreparedStatement pstat,Connection con){
  111.         try{
  112.             if(res!=null){
  113.                 res.close();
  114.                 res=null;
  115.             }
  116.             if(pstat!=null){
  117.                 pstat.close();
  118.                 pstat=null;
  119.             }
  120.             if(con!=null){
  121.                 con.close();
  122.             }
  123.         }catch(SQLException e){
  124.             e.printStackTrace();
  125.         }
  126.     }
  127. }
package com.rz.dao;

import com.rz.entity.*;
import java.sql.*;
import java.util.*;

public class MessageDao {
	private String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
	private String url="jdbc:sqlserver://localhost:1433;DataBaseName=message";
	private String name="sa";
	private String password="lishiyuzuji";

	/**
	 * 保存一条记录
	 * @param message
	 * @return
	 */
	public int save(Message message){
		int line=0;				//保存记录的行数
		Connection con=null;
		PreparedStatement pstat=null;
		try{
			con=getConn();
			pstat=con.prepareStatement("insert into TBL_MESSAGE(message,author,postTime) values(?,?,getdate())");
			pstat.setString(1,message.getMessage());
			pstat.setString(2,message.getAuthor());
			line=pstat.executeUpdate();

		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			closeAll(null,pstat,con);
		}
		return line;
	}

	/**
	 * 分页显示信息
	 * @param pageSize 每页显示的信息数量
	 * @param pageNum  定位到那一页
	 * @return
	 */
	public List<Message> listByPage(int pageSize,int pageNum){
		Connection con=null;
		PreparedStatement pstat=null;
		ResultSet res=null;
		List<Message> list=new ArrayList<Message>();
		try{
			con=getConn();
			pstat=con.prepareStatement("select top "+pageSize+
					" * from TBL_MESSAGE where id not in (select top "+pageSize*(pageNum-1)+
					" id from TBL_MESSAGE order by postTime) order by postTime");
			res=pstat.executeQuery();
			while(res.next()){
				Message message=new Message();
				message.setId(res.getInt(1));
				message.setMessage(res.getString(2));
				message.setAuthor(res.getString(3));
				message.setPostTime(res.getDate(4));
				list.add(message);
			}
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			closeAll(res,pstat,con);
		}
		return list;
	}

	/**
	 * 获得记录的总条数
	 * @return	返回查询到的所有记录的总条数
	 */
	public int getAllUserCount(){
		Connection con=null;
		PreparedStatement pstat=null;
		ResultSet res=null;
		int ret = 0;
		try{
			con=getConn();
			pstat=con.prepareStatement("select count(*) from TBL_MESSAGE");
			res=pstat.executeQuery();
			if(res.next()){
				ret=res.getInt(1);
			}
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			closeAll(res,pstat,con);
		}
		return ret;
	}

	/**
	 * 连接数据库
	 */
	public Connection getConn(){
		Connection con=null;
		try{
			Class.forName(driver);
			con=DriverManager.getConnection(url,name,password);
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}catch(SQLException e){
			e.printStackTrace();
		}
		return con;
	}

	/**
	 * 关闭数据库连接,而且三者是有顺序的,先关闭ResultSet连接,接着关闭Statement连接,最后关闭Connection连接
	 * 并且还要抛出异常。数据库连接使用完毕以后需要关闭连接的,否则,连接数据库的“通道”就会继续增加,而数据库的连接
	 * 能力也是有限的,大约是200个,因此需要在使用完数据库后将连接关闭掉。
	 * @param res
	 * @param stat
	 * @param conn
	 */
	public void closeAll(ResultSet res,PreparedStatement pstat,Connection con){
		try{
			if(res!=null){
				res.close();
				res=null;
			}
			if(pstat!=null){
				pstat.close();
				pstat=null;
			}
			if(con!=null){
				con.close();
			}
		}catch(SQLException e){
			e.printStackTrace();
		}

	}

}

 

Biz类如下(调用dao的相关方法来实现业务处理):

 

  1. package com.rz.Biz;
  2. import java.util.*;
  3. import com.rz.dao.*;
  4. import com.rz.entity.*;
  5. public class MessageBiz {
  6.     /**
  7.      * 保存一条信息
  8.      * @param message
  9.      */
  10.     public void saveMessage(Message message){
  11.         MessageDao messageDao=new MessageDao();
  12.         messageDao.save(message);
  13.     }
  14.     /**
  15.      * 根据页码来查询数据
  16.      * @param page
  17.      * @return
  18.      */
  19.     public List<Message> listByPage(int pageSize,int pageNum){
  20.         MessageDao messageDao=new MessageDao();
  21.         return messageDao.listByPage(pageSize,pageNum);
  22.     }
  23.     /**
  24.      * 返回查询到的记录的总条数
  25.      * @return
  26.      */
  27.     public int getAllUserCount(){
  28.         MessageDao messageDao=new MessageDao();
  29.         return messageDao.getAllUserCount();
  30.     }
  31. }
package com.rz.Biz;
import java.util.*;
import com.rz.dao.*;
import com.rz.entity.*;
public class MessageBiz {
	/**
	 * 保存一条信息
	 * @param message
	 */
	public void saveMessage(Message message){
		MessageDao messageDao=new MessageDao();
		messageDao.save(message);
	}
	/**
	 * 根据页码来查询数据
	 * @param page
	 * @return
	 */
	public List<Message> listByPage(int pageSize,int pageNum){
		MessageDao messageDao=new MessageDao();
		return messageDao.listByPage(pageSize,pageNum);
	}

	/**
	 * 返回查询到的记录的总条数
	 * @return
	 */
	public int getAllUserCount(){
		MessageDao messageDao=new MessageDao();
		return messageDao.getAllUserCount();
	}
}

测试index页面代码如下:

  1. <%@ page language=”java” import=”java.util.*,com.rz.Biz.*, com.rz.entity.*” contentType=”text/html; charset=utf-8″%>
  2. <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
  3. <html>
  4.   <head>
  5.     <title>留言板系统</title>
  6.      <script>
  7.         function check(){
  8.             var name=document.form.text.value;
  9.             var pass=document.form.textarea.value;
  10.             if(name.length==0){
  11.                 alert(“用户名不得为空!”);
  12.                 return false;
  13.             }
  14.             if(pass.length==0){
  15.                 alert(“留言信息不能为空!”);
  16.                 return false;
  17.             }
  18.             return true;
  19.         }
  20.     </script>
  21.   </head>
  22.   <body style=”text-align:center;”>
  23.     <h1>Beta留言板</h1>
  24.     <div style=”width:800px; border:#CCCCCC solid 1px;”>
  25.         <%
  26.             String p=request.getParameter(“p”);
  27.             int pageNum=1;          //定义页数
  28.             int pageSize=10;        //定义每一页显示的个数
  29.             if(p!=null){            //判断传入的输入值是否为空,并且进行强制类型转换
  30.                 pageNum=Integer.parseInt(p);
  31.             }
  32.             MessageBiz messageBiz=new MessageBiz();
  33.             List<Message> list=messageBiz.listByPage(pageSize,pageNum); //根据传入的两个参数,返回一个list集合
  34.             for(int i=list.size()-1;i>=0;i–){
  35.                 Message message=new Message();
  36.                 message=(Message)list.get(i);
  37.         %>
  38.         <div style=”width:800px;”>
  39.             <div style=”background-color:#CCCCCC; text-align:left;”>作者:<%=message.getAuthor() %>
  40.                        <%=message.getPostTime() %>
  41.             </div>
  42.             <div style=”text-align:right;”><%=i+1+(pageNum-1)*pageSize %>#</div>
  43.             <div><%=message.getMessage() %>
  44.             </div>
  45.         </div>
  46.         <%
  47.             }
  48.             //获得最大页码
  49.             int maxPage;
  50.             int reCount=messageBiz.getAllUserCount();
  51.             if(reCount%pageSize==0)
  52.                 maxPage=reCount/pageSize;
  53.             else
  54.                 maxPage=(reCount/pageSize)+1;
  55.             int backPage=(pageNum==1) ? 1 :pageNum-1;
  56.             int nextPage=(pageNum==maxPage) ? maxPage : pageNum+1;
  57.         %>
  58.     </div>
  59.     <div style=”width:800px; height:30px; border:#000033 solid 0px; margin-top:12px; text-align:right;”>
  60.         <div style=”width:50px; height:15px; border:#CCCCCC solid 1px; display:inline; cursor:pointer;”>
  61.             <a href=”index.jsp?p=<%=backPage %>”>上一页</a>
  62.         </div>
  63.         <div style=”width:50px; height:15px; border:#CCCCCC solid 1px; display:inline; margin-left:12px; margin-right:20px; cursor:pointer;”>
  64.             <a href=”index.jsp?p=<%=nextPage %>”>下一页</a>
  65.         </div>
  66.     </div>
  67.     <div style=” width:800px; height:300px; border:#333333 solid 0px;”>
  68.         <form name=”form” action=”doPost.jsp” method=”post” onSubmit=”return check()”>
  69.             <table>
  70.                     <tr>
  71.                         <td>用户名:</td>
  72.                         <td><input type=”text” name=”text”/></td>
  73.                     </tr>
  74.                     <tr>
  75.                         <td>留言信息:</td>
  76.                         <td><textarea name=”textarea” style=”width:400px; height:200px;”></textarea></td>
  77.                     </tr>
  78.                     <tr><td><input type=”submit” value=”提交”/></td></tr>
  79.                 </table>
  80.         </form>
  81.     </div>
  82.   </body>
  83. </html>
<%@ page language="java" import="java.util.*,com.rz.Biz.*, com.rz.entity.*" contentType="text/html; charset=utf-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>留言板系统</title>
     <script>
    	function check(){
    		var name=document.form.text.value;
    		var pass=document.form.textarea.value;
    		if(name.length==0){
    			alert("用户名不得为空!");
    			return false;
    		}
    		if(pass.length==0){
    			alert("留言信息不能为空!");
    			return false;
    		}
    		return true;
    	}
    </script>
  </head>

  <body style="text-align:center;">
  	<h1>Beta留言板</h1>
	<div style="width:800px; border:#CCCCCC solid 1px;">
		<%
			String p=request.getParameter("p");
			int pageNum=1;			//定义页数
			int pageSize=10;		//定义每一页显示的个数
			if(p!=null){			//判断传入的输入值是否为空,并且进行强制类型转换
			 	pageNum=Integer.parseInt(p);
		 	}

  			MessageBiz messageBiz=new MessageBiz();
  			List<Message> list=messageBiz.listByPage(pageSize,pageNum); //根据传入的两个参数,返回一个list集合

  			for(int i=list.size()-1;i>=0;i--){
  				Message message=new Message();
  				message=(Message)list.get(i);
  		%>

		<div style="width:800px;">
			<div style="background-color:#CCCCCC; text-align:left;">作者:<%=message.getAuthor() %>
				       <%=message.getPostTime() %>
			</div>
			<div style="text-align:right;"><%=i+1+(pageNum-1)*pageSize %>#</div>
			<div><%=message.getMessage() %>
			</div>
		</div>
		<%
			}
			//获得最大页码
			int maxPage;
			int reCount=messageBiz.getAllUserCount();
			if(reCount%pageSize==0)
				maxPage=reCount/pageSize;
			else
				maxPage=(reCount/pageSize)+1;

			int backPage=(pageNum==1) ? 1 :pageNum-1;
			int nextPage=(pageNum==maxPage) ? maxPage : pageNum+1;
  	 	%>
	</div>

	<div style="width:800px; height:30px; border:#000033 solid 0px; margin-top:12px; text-align:right;">
		<div style="width:50px; height:15px; border:#CCCCCC solid 1px; display:inline; cursor:pointer;">
			<a href="index.jsp?p=<%=backPage %>">上一页</a>
		</div>
		<div style="width:50px; height:15px; border:#CCCCCC solid 1px; display:inline; margin-left:12px; margin-right:20px; cursor:pointer;">
			<a href="index.jsp?p=<%=nextPage %>">下一页</a>
		</div>
	</div>
	<div style=" width:800px; height:300px; border:#333333 solid 0px;">
		<form name="form" action="doPost.jsp" method="post" onSubmit="return check()">
			<table>
		    		<tr>
		    			<td>用户名:</td>
		    			<td><input type="text" name="text"/></td>
		    		</tr>
		    		<tr>
		    			<td>留言信息:</td>
		    			<td><textarea name="textarea" style="width:400px; height:200px;"></textarea></td>
		    		</tr>
		    		<tr><td><input type="submit" value="提交"/></td></tr>
		       	</table>
		</form>
	</div>
  </body>
</html>

处理表单提交的jsp页面doPost.jsp如下:

  1. <%@ page language=”java” import=”java.util.*,com.rz.Biz.*, com.rz.entity.*” contentType=”text/html; charset=utf-8″%>
  2. <%
  3.     request.setCharacterEncoding(“utf-8″);
  4.     String author=request.getParameter(“text”);
  5.     String message=request.getParameter(“textarea”);
  6.     Message messages=new Message();
  7.     messages.setAuthor(author);
  8.     messages.setMessage(message);
  9.     MessageBiz messageBiz=new MessageBiz();
  10.     messageBiz.saveMessage(messages);
  11.     response.sendRedirect(“index.jsp”);
  12. %>
<%@ page language="java" import="java.util.*,com.rz.Biz.*, com.rz.entity.*" contentType="text/html; charset=utf-8"%>
<%
	request.setCharacterEncoding("utf-8");
	String author=request.getParameter("text");
	String message=request.getParameter("textarea");

	Message messages=new Message();
	messages.setAuthor(author);
	messages.setMessage(message);
	MessageBiz messageBiz=new MessageBiz();
	messageBiz.saveMessage(messages);
	response.sendRedirect("index.jsp");
 %>

页面效果如下:

http://blog.csdn.net/lishiyuzuji/article/details/6758257