1. 程式人生 > >5.0其他WEB技術——分頁和模糊查詢結合例項

5.0其他WEB技術——分頁和模糊查詢結合例項

JAVAWEB文章索引點這裡
首先分頁的核心是寫一個PageBean物件,將頁面中要使用到的首頁、上頁、下頁、末頁、頁數、查詢出的內容等等進行一個封裝。然後轉發回到頁面中進行一個顯示。而模糊查詢的核心是對sql語句進行一個拼接,達到模糊匹配需要內容的效果。
資料庫Store中有表product(id,name,bar_code,price,producer)
需要用到的jar包郵jstl,sqljdbc4
表sql:

/*
 Navicat Premium Data Transfer

 Source Server         : localhost_3306
 Source Server Type    : MySQL
 Source Server Version : 50721
 Source Host           : localhost:3306
 Source Schema         : store

 Target Server Type    : MySQL
 Target Server Version : 50721
 File Encoding         : 65001

 Date: 15/07/2018 13:22:23
*/
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for product -- ---------------------------- DROP TABLE IF EXISTS `product`; CREATE TABLE `product` ( `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL
DEFAULT NULL, `bar_code` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `price` float(10, 2) NULL DEFAULT NULL, `producer` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 12 CHARACTER
SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ---------------------------- -- Records of product -- ---------------------------- INSERT INTO `product` VALUES (1, 'name1', '123', 3.50, 'sssss'); INSERT INTO `product` VALUES (2, 'name2', '123', 3.50, 'sssss'); INSERT INTO `product` VALUES (3, 'name3', '123', 3.50, 'sssss'); INSERT INTO `product` VALUES (4, 'name4', '123', 3.00, 'sssss'); INSERT INTO `product` VALUES (5, 'name5', '123', 3.00, 'sssss'); INSERT INTO `product` VALUES (6, 'name6', '123', 3.00, 'sssss'); INSERT INTO `product` VALUES (7, 'name7', '123', 3.00, 'sssss'); INSERT INTO `product` VALUES (8, 'name8', '123', 3.00, 'sssss'); INSERT INTO `product` VALUES (9, 'name9', '123', 3.00, 'sssss'); INSERT INTO `product` VALUES (10, 'name10', '123', 3.00, 'sssss'); INSERT INTO `product` VALUES (11, 'name11', '123', 3.00, 'sssss'); SET FOREIGN_KEY_CHECKS = 1;

比較常規的dbutils

package com.dbutil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.sun.xml.internal.ws.Closeable;
public class DBUtils {

    private static String url = "jdbc:mysql://localhost:3306/Store";
    private static String user = "root";
    private static String password = "123456";
    private static Connection conn = null;
    private static PreparedStatement psttm = null;
    static {
        try {

            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() {
        try {
            conn = DriverManager.getConnection(url,user,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    public static PreparedStatement getPreparedStatement(String sql) {

        try {
            psttm = getConnection().prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return psttm;
    }
    public static void close() {
        try {
            if(conn != null) {
                conn.close();
            }
            if(psttm != null) {
                psttm.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

ProductDao:主要用與查詢操作

package com.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.bean.Product;
import com.dbutil.DBUtils;

public class ProductDao {
    /**
     *查詢出指定大小的[模糊]內容 
     * */
    public static List<Product> getList(int startNum, int pageNum,String nameFind){
        List list = new ArrayList<>();
        //進行sql語句拼接
        StringBuffer sql = new StringBuffer("select * from product where 1=1");

        if(nameFind != null && !nameFind.trim().equals("")){//如果nameFind不為空,並且去除前後字串後且不是空字串
            sql.append(" and name like '%"+nameFind+"%'");
        }
        sql.append(" limit ?,?");
        //查詢結果
        try {
            PreparedStatement psttm = DBUtils.getPreparedStatement(sql.toString());
            psttm.setInt(1, startNum);
            psttm.setInt(2, pageNum);
            ResultSet rs = psttm.executeQuery();
            while(rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String bar_code = rs.getString("bar_code");
                float prive = rs.getFloat("price");
                String producer = rs.getString("producer");
                Product product = new Product(id, name, bar_code, prive, producer);
                list.add(product);
            }
            rs.close();
            DBUtils.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
    /**
     * 返回[模糊]查詢結果的大小
     * */
    public static int getCount(String nameFind) {
        int count = 0;
        //sql拼接
        StringBuffer sql = new StringBuffer("SELECT COUNT(id) FROM product");
        if(nameFind != null && !nameFind.trim().equals("")) {
            sql.append(" where name like '%"+nameFind+"%'");
        }
        //查詢結果
        try {
            PreparedStatement psttm = DBUtils.getPreparedStatement(sql.toString());
            ResultSet rs = psttm.executeQuery();
            if(rs.next()) {
                count = rs.getInt(1);
            }
            rs.close();
            DBUtils.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }
}

beans:
PageBean,主要用於封裝頁面的各資訊,以及儲存查詢結果和請求中的模糊查詢條件

package com.bean;

import java.util.*;

public class PageBean {
    private List<Product> list;
    //首頁
    private int firstPage;
    //最後一頁
    private int lastPage;
    //當前頁
    private int nowPage;
    //上頁
    private int backPage;
    //下頁
    private int nextPage;
    //總共頁數
    private int sum;
    //每頁數量
    private int pageSize;
    //查詢引數
    private FindBean findBean = new FindBean();

    public int getFirstPage() {
        return 1;
    }
    public void setFirstPage(int firstPage) {
        this.firstPage = firstPage;
    }
    //獲取末頁
    public int getLastPage() {
        if(sum%pageSize==0) {
            lastPage = sum/pageSize;
        }else {
            lastPage = sum/pageSize + 1;
        }
        return lastPage;
    }
    public void setLastPage(int lastPage) {
        this.lastPage = lastPage;
    }
    public int getNowPage() {
        return nowPage;
    }
    public void setNowPage(int nowPage) {
        this.nowPage = nowPage;
    }
    //獲取上一頁
    public int getBackPage() {
        if(nowPage == 1) {
            backPage = 1;
        }else {
            backPage = nowPage - 1;
        }
        return backPage;
    }
    public void setBackPage(int backPage) {
        this.backPage = backPage;
    }
    //設定下一頁
    public int getNextPage() {
        if(nowPage==lastPage) {
            nextPage = lastPage;
        }else {
            nextPage = nowPage+1;
        }
        return nextPage;
    }
    public void setNextPage(int nextPage) {
        this.nextPage = nextPage;
    }
    public int getSum() {
        return sum;
    }
    public void setSum(int sum) {
        this.sum = sum;
    }
    public int getPageSize() {
        return pageSize;
    }
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
    public List<Product> getList() {
        return list;
    }
    public void setList(List<Product> list) {
        this.list = list;
    }
    public FindBean getFindBean() {
        return findBean;
    }
    public void setFindBean(FindBean findBean) {
        this.findBean = findBean;
    }
}

對應表的product

package com.bean;

public class Product {
    private int id;
    private String name;
    private String bar_code;
    private float price;
    private String producer;

    public Product() {
    }
    public Product(int id, String name, String bar_code, float price, String producer) {
        super();
        this.id = id;
        this.name = name;
        this.bar_code = bar_code;
        this.price = price;
        this.producer = producer;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getBar_code() {
        return bar_code;
    }
    public void setBar_code(String bar_code) {
        this.bar_code = bar_code;
    }

    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
    public String getProducer() {
        return producer;
    }
    public void setProducer(String producer) {
        this.producer = producer;
    }
    public void printInfo() {
        System.out.println(this.getId()+","+this.getName()+","+this.getBar_code()+","
                    +this.getPrice()+this.getProducer());
    }
}

FindBean,用於存放模糊查詢條件,本例只模糊匹配了name屬性,如果要證件匹配項則應該增加本類中的屬性

package com.bean;

public class FindBean {
    private String nameFind;

    public String getNameFind() {
        return nameFind;
    }

    public void setNameFind(String nameFind) {
        this.nameFind = nameFind;
    }
}

servlet,用於接受頁面的資料,傳參方式呼叫service,然後將封裝好的PageBean放入域物件後進行轉發

package com.servlet;

import java.io.IOException;
import java.util.ArrayList;

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

import com.bean.PageBean;
import com.bean.Product;
import com.dao.ProductDao;
import com.service.PageService;

import java.util.List;

@WebServlet("/PageServlet")
public class PageServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1獲取頁面資料
        PageBean pageBean = new PageBean();
        String nowPage = request.getParameter("nowPage");
        String pageSize = request.getParameter("pageSize");
        String nameFind = request.getParameter("nameFind");
        //設定pageBean屬性
        PageService pageService = new PageService();
        pageService.setPageBean(pageBean, nowPage, pageSize,nameFind);
        //2存進域物件
        request.setAttribute("pageBean", pageBean);
        //3轉發
        request.getRequestDispatcher("index.jsp").forward(request, response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

service,將從servlet中得到的引數進行判斷後封裝到PageBean中並返回給servlet,被封裝的內容還包括,呼叫dao得到的查詢結果。

package com.service;

import java.util.List;

import com.bean.PageBean;
import com.bean.Product;
import com.dao.ProductDao;

public class PageService {

    public PageBean setPageBean(PageBean pageBean,String now,String pageSize,String nameFind) {
        //設定當前頁
        if(now==null||now.equals("")) {
            now = "1";
        }
        int nowPage = Integer.parseInt(now);
        pageBean.setNowPage(nowPage);
        //設定資料量大小
        int num = ProductDao.getCount(nameFind);
        pageBean.setSum(num);
        //設定分頁大小
        if(pageSize == null || pageSize.equals("")) {
            pageSize = "3";//預設大小為3
        }
        int size = Integer.parseInt(pageSize);
        pageBean.setPageSize(size);
        //獲取list
        List<Product> list = ProductDao.getList((nowPage-1)*size,size,nameFind);
        pageBean.setList(list);
        //設定FindBean
        pageBean.getFindBean().setNameFind(nameFind);
        return pageBean;
    }
}

index,顯示頁面和向頁面傳送請求,其中js部分實現了頁數選擇和每頁顯示數量選擇。同時也對當前頁進行了一個判斷,如第一頁的時候無法點選首頁和末頁。每次點選的時候都需要將一些資訊通過超連結帶入到servlet中以保證分頁效果可以持續下去。其中編輯和刪除超連結只做顯示效果,並未實現。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>Insert title here</title>.
</head>
<body>
<table border="1" align="center" width="550" height="250" >
<tr>
<td colspan="5">
請輸入需要查詢的名字
<form action="${pageContext.request.contextPath}/PageServlet?pageSize=${pageBean.pageSize}" method="post" style="margin:0px;display:inline;">
    <input name="nameFind" size="4" value="${pageBean.findBean.nameFind}" />
    <input type="submit" value="提交"/>
</form>
</td>
</tr>
<tr>
<td>名稱</td>
<td>條碼</td>
<td>單價</td>
<td>產地</td>
<td>操作</td>
</tr>
<c:forEach items="${pageBean.list}" var="a_product">
    <tr>
        <td>${a_product.name}</td>
        <td>${a_product.bar_code}</td>
        <td>${a_product.price }</td>
        <td>${a_product.producer }</td>
        <td><a href="">編輯</a>&nbsp;<a href="">刪除</a></td>
    </tr>
</c:forEach>
<tr>
<td colspan="5">第${pageBean.nowPage}頁 /共 ${pageBean.lastPage }頁,&nbsp;

<c:choose>
    <%--如果是第一頁,首頁和上一頁就不可點選 --%>
    <c:when test="${pageBean.nowPage == 1}">
    首頁&nbsp;
    上一頁&nbsp;
    </c:when>
    <c:otherwise>
        <a href="${pageContext.request.contextPath}/PageServlet?nowPage=${pageBean.firstPage}&pageSize=${pageBean.pageSize}&nameFind=${pageBean.findBean.nameFind }">首頁</a>&nbsp;
        <a href="${pageContext.request.contextPath}/PageServlet?nowPage=${pageBean.backPage}&pageSize=${pageBean.pageSize}&nameFind=${pageBean.findBean.nameFind }">上一頁</a>&nbsp;
    </c:otherwise>
</c:choose>
<c:choose>
    <%--如果是最後頁,末頁和下一頁就不可點選 --%>
    <c:when test="${pageBean.nowPage == pageBean.lastPage}">
    下一頁&nbsp;
    末頁&nbsp;
    </c:when>
    <c:otherwise>
        <a href="${pageContext.request.contextPath}/PageServlet?nowPage=${pageBean.nextPage}&pageSize=${pageBean.pageSize}&nameFind=${pageBean.findBean.nameFind }">下一頁</a>&nbsp;
        <a href="${pageContext.request.contextPath}/PageServlet?nowPage=${pageBean.lastPage}&pageSize=${pageBean.pageSize}&nameFind=${pageBean.findBean.nameFind }">末頁</a>
    </c:otherwise>
</c:choose>
    <%--實現頁面跳轉和顯示內容大小 --%>
    跳轉到第<input id="nowPage" size="2" onblur="changeNowPage()" value="${pageBean.nowPage }"/>頁&nbsp;
    顯示<input id="pageSize" size="2" onblur="changePageSize()" value="${pageBean.pageSize }"/></td>
</tr>
</table>
<script type="text/javascript">
    <%--實現pageSize帶參跳轉--%>
    function changePageSize(){
        var pageSize = document.getElementById("pageSize").value;
        var reg = /^[1-9][0-9]?$/;
        if(!reg.test(pageSize)){
            alert("只能輸入1-2位的數字");
            return;
        }
        var url = "${pageContext.request.contextPath}/PageServlet?pageSize="+pageSize+"&nameFind=${pageBean.findBean.nameFind }";
        window.location.href=url;
    }
    <%--實現指定頁面跳轉跳轉--%>
    function changeNowPage(){
        var nowPage = document.getElementById("nowPage").value;
        var reg = /^[1-9][0-9]?$/;
        if(!reg.test(nowPage)){
            alert("只能輸入1-2位的數字");
            return;
        }
        var lastPage = "${pageBean.lastPage}";
        if(nowPage > lastPage){
            alert("跳轉頁面超過了最大頁面");
            return;
        }
        var url = "${pageContext.request.contextPath}/PageServlet?nowPage="+nowPage+"&pageSize=${pageBean.pageSize}"+"&nameFind=${pageBean.findBean.nameFind }";
        window.location.href=url;
    }
</script>
</body>
</html>