1. 程式人生 > >JavaWeb---資料分頁

JavaWeb---資料分頁

資料分頁


這個東西就像是百度最下端的那個東西一樣的功能的,如下:


功能說明:

1、在不使用上方搜尋功能時,能夠檢視到所有的資料

2、下面的分頁功能將資料分成了許多頁,下方的分頁我規定只讓他顯示十頁(總共不止十頁,後面的要所在頁面移動才能夠顯示出其他的頁面,就像百度的分頁功能一樣的),每一頁只顯示十行資料

3、上面的查詢功能也是借用了資料庫的模糊查詢功能實現的


當然了,這個小專案還需要使用到三個jar包:c3p0-0.9.1.2.jar、commons-dbutils-1.4.jar、mysql-connector-java-5.1.5-bin.jar

下面是程式碼:

配置檔案:c3p0-config.xml

<c3p0-config>
	<!-- 預設配置,如果沒有指定則使用這個配置 -->
	<default-config>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="jdbcUrl">
			<![CDATA[jdbc:mysql://127.0.0.1:3306/mydata?useUnicode=true&characterEncoding=UTF-8]]>
		</property>
		<property name="user">root</property>
		<property name="password"></property>
		<!-- 初始化池大小 -->
		<property name="initialPoolSize">2</property>
		<!-- 最大空閒時間 -->
		<property name="maxIdleTime">30</property>
		<!-- 最多有多少個連線 -->
		<property name="maxPoolSize">10</property>
		<!-- 最少幾個連線 -->
		<property name="minPoolSize">2</property>
		<!-- 每次最多可以執行多少個批處理語句 -->
		<property name="maxStatements">50</property>
	</default-config> 
	<!-- 命名的配置 -->
	<named-config name="hncu">
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/mydb</property>
		<property name="user">root</property>
		<property name="password"></property>
		<property name="acquireIncrement">5</property><!-- 如果池中資料連線不夠時一次增長多少個 -->
		<property name="initialPoolSize">100</property>
		<property name="minPoolSize">50</property>
		<property name="maxPoolSize">1000</property>
		<property name="maxStatements">0</property>
		<property name="maxStatementsPerConnection">5</property> <!-- he's important, but there's only one of him -->
	</named-config>
</c3p0-config> 


index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>PagesDivided</title>
  </head>
  
  <body>
    <a href="<c:url value='PageServlet2'/>">資料分頁的分頁</a>
  </body>
</html>

show2.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>showDividedPage</title>
    <link rel="stylesheet" href="<c:url value='/css/table.css'/>"/>
    <script type="text/javascript">
    	function change(obj){
    		window.location.href="<c:url value='/PageServlet2?page='/>"+obj.value;
    	}
    </script>
  </head>
  
  <body>
  	<h3>資料查詢</h3>
  	<form action='<c:url value="/PageServlet2"/>' method="post">
  		ID:<input type="text" name="id" value="${stud.id}"/> 
  		Name:<input type="text" name="name" value="${stud.name}"/> 
  		<input type="submit" value="模糊查詢"/>
  	</form>
  	<hr/>
    <h3 align="center">當前頁面內容</h3>
    <table>
    	<tr><th>學號</th><th>姓名</th></tr>
    	<c:forEach items="${result.datas}" var="map">
    		<tr>
    			<td>${map.id}</td>
    			<td>${map.name}</td>
    		</tr>
    	</c:forEach>
    </table>
    <br/><br/>
    <c:if test="${1!=result.currentPage}">
    	<a href="<c:url value='/PageServlet2?page=${result.currentPage-1}'/>">上一頁</a>
    </c:if>
   	<c:forEach begin="${showStart}" end="${showEnd}" var="idx">
   		<c:if test="${idx==result.currentPage}">
   			${idx}
   		</c:if>
   		<c:if test="${idx!=result.currentPage}">
   			<span id="unselectedPage">
   				<a href="<c:url value='/PageServlet2?page=${idx}'/>">${idx}</a>
   			</span>
   		</c:if>
   		 
   	</c:forEach>
    <c:if test="${result.pageCount!=result.currentPage}">
    	<a href="<c:url value='/PageServlet2?page=${result.currentPage+1}'/>">下一頁</a>
    </c:if>
    
    <select onchange="change(this)">
    	<c:forEach begin="1" end="${result.pageCount}" var="idx">
    		<option <c:if test="${idx==result.currentPage}">selected</c:if> value="${idx}">
    			第${idx}頁
    		</option>
    	</c:forEach>
    </select>
  </body>
</html>

table.css

table{
	clear:left;
	border: 1px solid blue;
	width:500px;
	border-collapse: collapse;
	margin: auto;
}
td{
	border: 1px solid blue;
	text-align: center;
}
th{
	border: 1px solid blue;
}
body{
	text-align: center;
}
a{
	text-decoration: none;
}
#unselectedPage{
	border: 1px solid blue;
	width:500px;
	margin: auto;
}

公共類C3p0Pool.java

package cn.hncu.pubs;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

//我們的這個包裝,只是為了把c3p0池做成讓每個執行緒(客戶端)獲得的是同一個連線,方便做b/s框架下的事務
public class C3p0Pool {
	private static DataSource pool;
	private static ThreadLocal<Connection> t=new ThreadLocal<Connection>();
	static {
		pool=new ComboPooledDataSource();
	}
	
	public static DataSource getDataSource(){
		return pool;
	}
	
	public static Connection getConnection() throws SQLException{
		Connection con=t.get();
		if (con==null){
			con=pool.getConnection();
			t.set(con);
		}
		return con;
	}
}

DAO層

介面:IPageDAO2.java

package cn.hncu.page2.dao;

import java.util.Map;

import cn.hncu.page2.domain.Stud;

public interface IPageDAO2 {
	public Map<String, Object> query(Integer pageNo, Stud stud) throws Exception;
}
實現類:PageJdbc2.java

package cn.hncu.page2.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.hncu.page2.domain.Stud;
import cn.hncu.pubs.C3p0Pool;

public class PageJdbc2 implements IPageDAO2 {
	private final int pageSize=10;
	@Override
	public Map<String, Object> query(Integer pageNo, Stud stud) throws Exception {
		Map<String, Object> result=new HashMap<String, Object>();
		//總行數
		String sql="select count(1) from dbutilsstud where 1=1 ";//查總行數
		String sql2="select * from dbutilsstud where 1=1 ";//查內容
		if (stud.getId()!=null&&stud.getId().trim().length()!=0){
			sql+="and id like '%"+stud.getId()+"%'";
			sql2+="and id like '%"+stud.getId()+"%'";
		}
		if (stud.getName()!=null&&stud.getName().trim().length()!=0){
			sql+="and name like '%"+stud.getName()+"%'";
			sql2+="and name like '%"+stud.getName()+"%'";
		}
		
		QueryRunner run=new QueryRunner(C3p0Pool.getDataSource());
		int rows=Integer.parseInt(""+run.query(sql, new ScalarHandler()));
		
		//總頁數
		int pageCount=rows/pageSize + (rows%pageSize==0 ? 0:1);
		result.put("pageCount", pageCount);
		
		//分頁面內容
		int startNo=(pageNo-1)*pageSize;
		sql2=sql2+" limit "+startNo+", "+pageSize;
		List<Map<String, Object>> datas=run.query(sql2, new MapListHandler());
		result.put("datas", datas);
		
		return result;
	}
}

service層

介面:IPageService2.java

package cn.hncu.page2.service;

import java.util.Map;

import cn.hncu.page2.domain.Stud;

public interface IPageService2 {
	public Map<String, Object> query(Integer pageNo, Stud stud) throws Exception;
}
實現類:PageServiceImpl2.java

package cn.hncu.page2.service;

import java.util.Map;

import cn.hncu.page2.dao.IPageDAO2;
import cn.hncu.page2.dao.PageJdbc2;
import cn.hncu.page2.domain.Stud;

public class PageServiceImpl2 implements IPageService2 {
	//注入dao
	IPageDAO2 dao=new PageJdbc2();
	@Override
	public Map<String, Object> query(Integer pageNo, Stud stud) throws Exception {
		return dao.query(pageNo, stud);
	}
}

servlet :PageServlet2.java

package cn.hncu.page2.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hncu.page2.domain.Stud;
import cn.hncu.page2.service.IPageService2;
import cn.hncu.page2.service.PageServiceImpl2;

public class PageServlet2 extends HttpServlet {
	//注入service
	IPageService2 service=new PageServiceImpl2();
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String pageNo=request.getParameter("page");
		if (pageNo==null||pageNo.trim().length()==0){
			pageNo="1";
		}
		
		Stud stud=null;
		if (request.getMethod().equalsIgnoreCase("GET")){
			stud=(Stud) request.getSession().getAttribute("stud");
			if (stud==null){
				stud=new Stud();
			}
		} else {
			stud=new Stud();
			String id=request.getParameter("id");
			String name=request.getParameter("name");
			stud.setId(id);
			stud.setName(name);
			request.getSession().setAttribute("stud", stud);
		}
		
		try {
			Integer iPageNo=Integer.parseInt(pageNo);
			Map<String, Object> result=service.query(iPageNo,stud);
			
			//給結果集補一個數據: currentPage
			result.put("currentPage", iPageNo);
			
			//把結果集放入容器中
			request.setAttribute("result", result);
			
			int showSize=10;
			int showStart=0;
			int showEnd=0;
			int pageCount=Integer.parseInt(""+result.get("pageCount"));
			if (pageCount<showSize){
				showStart=1;
				showEnd=pageCount;
			} else {
				if (iPageNo<=(showSize/2+(showSize%2==0?0:1))){
					showStart=1;
					showEnd=showSize;
				} else {
					showStart=iPageNo-showSize/2;
					showEnd=showStart+showSize-1;
				}
				if (showEnd>pageCount){
					showEnd=pageCount;
					showStart=showEnd-showSize+1;
				}
			}
			
			request.setAttribute("showStart", showStart);
			request.setAttribute("showEnd", showEnd);
			//轉到結果頁面
			request.getRequestDispatcher("/jsps/show2.jsp").forward(request, response);
		} catch (NumberFormatException e) {
			throw new RuntimeException("當前頁格式轉換錯誤", e);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

值物件層:Stud.java

package cn.hncu.page2.domain;

public class Stud {
	private String id;
	private String name;
	
	public Stud() {
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Stud other = (Stud) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}
}


具體的分包影象如下:


這個小專案我是放在了page2這個包裡面的,page1是這個專案的另一個版本,就沒貼上來了;另外下面的show.jsp也是給另一個用的,這個專案使用的是show2.jsp