码迷,mamicode.com
首页 > Web开发 > 详细

JSP + Servlet 图书管理系统

时间:2017-09-05 21:55:25      阅读:1592      评论:0      收藏:0      [点我收藏+]

标签:actor   contex   jdb   throws   eem   dao   exe   dmi   种子   

所用技术:

  JS+Servlet、bootstrap前端框架、JQuery Validate 验证框架、MySQL数据库;

  DAO 设计模式;

  基于Servlet + JSP + JavaBean 的MVC设计模式。

  小技术点:MD5加密操作,分页小脚本。

功能:

  1、后台登录

    超级管理员登录能看到超级管理员菜单(全局flag)

    普通管理员登录

  2、用户管理

    用户录入

  3、图书类别管理

    添加分类

    类别列表

  4、图书管理

    增加图书

    图书列表

  5、借书登记

    借书信息录入

    借书信息列表

数据库设计:

技术分享

 

数据库脚本:

技术分享
  1 --删除数据库
  2 drop database booksystem;
  3 
  4 --创建数据库
  5 create database booksystem;
  6 
  7 --使用数据库
  8 use booksystem;
  9 
 10 --删除数据表
 11 drop table if exists admin;
 12 
 13 drop table if exists item;
 14 
 15 drop table if exists books;
 16 
 17 drop table if exists member;
 18 
 19 drop table if exists lenbooks;
 20 
 21 --创建数据表
 22 /*==============================================================*/
 23 /* Table: admin 管理员表                                            */
 24 /*==============================================================*/
 25 create table admin
 26 (
 27    aid                  varchar(50) not null, 
 28    password             varchar(32),
 29    lastdate             datetime,
 30    flag                 int,    --1 超级管理员
 31    status               int,    --1 表示激活
 32    primary key (aid)
 33 );
 34 
 35 /*==============================================================*/
 36 /* Table: item   图书类别表                                               */
 37 /*==============================================================*/
 38 create table item
 39 (
 40    iid                   int not null auto_increment,
 41    name                 varchar(100),
 42    note                 text,    --备注、简介
 43    primary key (iid)
 44 );
 45 
 46 /*==============================================================*/
 47 /* Table: books  图书详情表                                               */
 48 /*==============================================================*/
 49 create table books
 50 (
 51    bid                  int not null auto_increment,
 52    iid                   int,            --图书类别id
 53    aid                  varchar(50),    --管理员id
 54    name                 varchar(100),    --书名儿
 55    credate              datetime,        --上架日期
 56    status               int,            --1 上架
 57    note                 text,            --简介
 58    primary key (bid)
 59 );
 60 
 61 alter table books add constraint FK_Reference_1 foreign key (iid)
 62       references item (iid) on delete cascade;
 63 
 64 alter table books add constraint FK_Reference_3 foreign key (aid)
 65       references admin (aid) on delete cascade;
 66       
 67 /*==============================================================*/
 68 /* Table: member  用户表                                              */
 69 /*==============================================================*/
 70 create table member
 71 (
 72    mid                  varchar(50) not null,
 73    name                 varchar(50),
 74    age                  int,
 75    sex                  int,
 76    phone                varchar(32),
 77    primary key (mid)
 78 );
 79 
 80 /*==============================================================*/
 81 /* Table: lenbook  借书详情表                                            */
 82 /*==============================================================*/
 83 create table lenbook
 84 (
 85    leid                 int not null auto_increment,
 86    mid                  varchar(50),                --用户id(借书人id)
 87    bid                  int,                        --图书id
 88    credate              datetime,                    --借出时间
 89    retdate              datetime,                    --归还时间
 90    primary key (leid)
 91 );
 92 
 93 alter table lenbook add constraint FK_Reference_2 foreign key (mid)
 94       references member (mid) on delete cascade;
 95 
 96 alter table lenbook add constraint FK_Reference_4 foreign key (bid)
 97       references books (bid) on delete cascade;
 98 
 99 --增加测试数据
100 --管理员ID:admin,管理员密码:admin123 
101 --F5866C4A4D6014ECCED47960C2E3D07F 是进行MD5加密后的字符串
102 insert into admin(aid,password,flag,status) values(admin,F5866C4A4D6014ECCED47960C2E3D07F,1,1);
103 insert into admin(aid,password,flag,status) values(root,F5866C4A4D6014ECCED47960C2E3D07F,1,1);
104 
105 --图书表
106 INSERT INTO books(iid,aid,name,credate,status,note) VALUES (1, root, Java WEB 开发, 2017-09-04 20:42:21, 1, Java WEB 从入门到精通有木有呀。);
107 INSERT INTO books(iid,aid,name,credate,status,note) VALUES (2, admin, 二胡鉴赏, 2017-09-04 20:45:51, 1, 二胡从入门到精通呀。);
108 INSERT INTO books(iid,aid,name,credate,status,note) VALUES (1, admin, C语言原理, 2017-09-04 21:09:04, 1, C语言基础和原理篇(计算机系必修)。);
109 INSERT INTO books(iid,aid,name,credate,status,note) VALUES (2, root, 古典音乐鉴赏, 2017-09-04 21:09:47, 1, 古典音乐通俗化鉴赏(必修));
110 INSERT INTO books(iid,aid,name,credate,status,note) VALUES (1, admin, C++ 面向对象编程和设计, 2017-09-04 21:10:58, 1, 体会面向过程编程和面向对象编程的区别和好处。);
111 INSERT INTO books(iid,aid,name,credate,status,note) VALUES (2, root, 竹笛基础教程, 2017-09-04 21:11:33, 1, 竹笛基础教程(选修之一),多动手。);
112 INSERT INTO books(iid,aid,name,credate,status,note) VALUES (1, admin, 数据结构(C语言版), 2017-09-04 21:12:02, 1, 体会数据结构的无穷魅力。);
113 
114 --图书分类表
115 INSERT INTO item VALUES (1, 计算机科学&技术, 计算机相关专业书籍。);
116 INSERT INTO item VALUES (2, 文化艺术, 文艺专业相关书籍。);
117 
118 --提交
119 commit;
View Code

基本开发流程:

  可行性分析;

  概要设计(概要设计说明书、ER图);

  详细设计(数据库详细设计,系统设计UI设计、后台框架技术使用等)。

几个关键的流程:

  DAO层:

    1、先创建DatabaseConnection类,用于数据库连接;

 1 package com.shawn.book.dbc;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.SQLException;
 6 
 7 public class DatabaseConnection {
 8     
 9     public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
10     
11     public static final String DBURL = "jdbc:mysql://localhost:3306/booksystem";
12     
13     public static final String DBUSER = "root";
14     
15     public static final String DBPASSWORD = "root";
16     
17     private Connection conn = null;
18     
19     public DatabaseConnection(){
20         try {
21             //加载驱动
22             Class.forName(DBDRIVER);
23             //创建数据库连接
24             this.conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD);
25         } catch (SQLException e) {
26             e.printStackTrace();
27         } catch (ClassNotFoundException e) {
28             e.printStackTrace();
29         }
30     }
31 
32     /**
33      * 获取数据库连接
34      * @return
35      */
36     public Connection getConn() {
37         return this.conn;
38     }
39     
40     /**
41      * 关闭数据库连接
42      */
43     public void close(){
44         if(this.conn != null){
45             try {
46                 this.conn.close();
47             } catch (SQLException e) {
48                 e.printStackTrace();
49             }
50         }
51     }
52     
53 }

 

    2、建AbstractDAOImpl 类,只有两个属性 pstmt(PreparedStatement类型)、conn(Connection 类型),一个构造方法;

 1 package com.shawn.book.dao;
 2 
 3 import java.sql.Connection;
 4 import java.sql.PreparedStatement;
 5 
 6 public abstract class AbstractDAOImpl {
 7     
 8     protected Connection conn;
 9     
10     protected PreparedStatement pstmt;
11     
12     public AbstractDAOImpl(Connection conn){
13         this.conn = conn;
14     }
15     
16 }

    2、建DAO层接口接口(举例):

        IDAO 公共的方法

           ---> IAdminDAO 继承IDAO,如果有需要可以添加自己特定的方法

            ---> IAdminDAOImpl(实现IAdminDAO接口,继承AbstractDAOImpl类)

              ---> DAOFactory进行注册 静态获取各个实现类

IDAO

 1 package com.shawn.book.dao;
 2 
 3 import java.sql.SQLException;
 4 import java.util.List;
 5 import java.util.Set;
 6 
 7 /**
 8  * 这个接口表示一个公共的DAO接口
 9  * @author Shawn
10  *
11  * @param <K> 表示主键
12  * @param <V> 表示要操作的对象
13  */
14 public interface IDAO<K,V> {
15     
16     /**
17      * 实现数据增加操作
18      * @param vo 表示要执行操作的对象
19      * @return 成功返回 true,失败返回 false
20      * @throws SQLException
21      */
22     boolean doCreate(V vo) throws SQLException;
23     
24     /**
25      * 实现数据更新操作
26      * @param vo 表示要执行更新的对象
27      * @return 成功返回 true,失败返回 false
28      * @throws SQLException
29      */
30     boolean doUpdate(V vo) throws SQLException;
31     
32     /**
33      * 实现数据批量删除
34      * @param ids 表示要执行删除的数据集合
35      * @return 成功返回 true,失败返回 false
36      * @throws SQLException
37      */
38     boolean doRemove(Set<?> ids) throws SQLException;
39     
40     /**
41      * 根据用户提供的id执行查询
42      * @param id 表示要查询的id
43      * @return 查询成功返回该数据行的记录,失败返回null
44      * @throws SQLException
45      */
46     V findById(K id) throws SQLException;
47     
48     /**
49      * 实现数据全部查询
50      * @return 成功返回全部数据,失败返回null
51      * @throws SQLException
52      */
53     List<V> findAll() throws SQLException;
54     
55     /**
56      * 实现数据分页操作
57      * @param column 表示要执行查询的列
58      * @param keyWord 表示查询关键字
59      * @param currentPage 表示当前页
60      * @param lineSize 表示每页显示记录数
61      * @return 查询成功返回满足条件的数据,失败返回null
62      * @throws SQLException
63      */
64     List<V> findBySplit(
65             String column,
66             String keyWord,
67             Integer currentPage,
68             Integer lineSize
69         ) throws SQLException;
70     
71     /**
72      * 实现数据量统计操作
73      * @param column 表示要查询的列
74      * @param keyWord 表示查询关键字
75      * @return 成功返回数据量,失败返回0
76      * @throws SQLException
77      */
78     Integer getAllCount(
79             String column,
80             String keyWord
81         ) throws SQLException;
82 }

IAdminDAO

 1 package com.shawn.book.dao;
 2 
 3 import com.shawn.book.vo.Admin;
 4 
 5 public interface IAdminDAO extends IDAO<String, Admin> {
 6     
 7     /**
 8      * 实现用户登录检查操作
 9      * @param vo 表示要执行检查的对象(aid,password,flag)
10      * @return 成功返回 ture,失败返回 false
11      * @throws Exception
12      */
13     public boolean findLogin(Admin vo) throws Exception;
14     
15     /**
16      * 实现用数据更新操作
17      * @param aid 要更新的主键
18      * @return
19      * @throws Exception
20      */
21     public boolean doUpdateByLastDate(String aid) throws Exception;
22 }

AdminDAOImpl

  1 package com.shawn.book.dao.impl;
  2 
  3 import java.sql.Connection;
  4 import java.sql.ResultSet;
  5 import java.sql.SQLException;
  6 import java.sql.Timestamp;
  7 import java.util.ArrayList;
  8 import java.util.Date;
  9 import java.util.List;
 10 import java.util.Set;
 11 
 12 import com.shawn.book.dao.AbstractDAOImpl;
 13 import com.shawn.book.dao.IAdminDAO;
 14 import com.shawn.book.vo.Admin;
 15 
 16 public class AdminDAOImpl extends AbstractDAOImpl implements IAdminDAO{
 17 
 18     public AdminDAOImpl(Connection conn) {//conn从外部传入
 19         super(conn);
 20     }
 21 
 22     @Override
 23     public boolean doCreate(Admin vo) throws SQLException {
 24         String sql = "insert into admin(aid,password,status) values(?,?,?)";
 25         super.pstmt = super.conn.prepareStatement(sql);
 26         super.pstmt.setString(1, vo.getAid());
 27         super.pstmt.setString(2, vo.getPassword());
 28 //        super.pstmt.setTimestamp(3, new java.sql.Timestamp(vo.getLastDate().getTime()));
 29         super.pstmt.setInt(3, vo.getStatus());
 30         int rel = super.pstmt.executeUpdate();
 31         return rel > 0;
 32     }
 33 
 34     @Override
 35     public boolean doUpdate(Admin vo) throws SQLException {
 36         return false;
 37     }
 38 
 39     @Override
 40     public boolean doRemove(Set<?> ids) throws SQLException {
 41         return false;
 42     }
 43 
 44     @Override
 45     public Admin findById(String id) throws SQLException {
 46         Admin vo = null;
 47         String sql = "select aid,password,lastdate,flag,status from admin where aid = ?";
 48         super.pstmt = super.conn.prepareStatement(sql);
 49         super.pstmt.setString(1, id);
 50         ResultSet rs = super.pstmt.executeQuery();
 51         if(rs.next()){
 52             vo = new Admin();
 53             vo.setAid(rs.getString("aid"));
 54             vo.setFlag(rs.getInt("flag"));
 55             vo.setStatus(rs.getInt("status"));
 56             vo.setPassword(rs.getString("password"));
 57             vo.setLastDate(rs.getTimestamp("lastdate"));
 58         }
 59         return vo;
 60     }
 61 
 62     @Override
 63     public List<Admin> findAll() throws SQLException {
 64         List<Admin> all = new ArrayList<Admin>();
 65         String sql = "select aid,password,lastdate,flag,status from admin";
 66         super.pstmt = super.conn.prepareStatement(sql);
 67         ResultSet rs = super.pstmt.executeQuery();
 68         while(rs.next()){
 69             Admin vo = new Admin();
 70             vo.setAid(rs.getString("aid"));
 71             vo.setPassword(rs.getString("password"));
 72             vo.setLastDate(rs.getTimestamp("lastdate"));
 73             vo.setFlag(rs.getInt("flag"));
 74             vo.setStatus(rs.getInt("status"));
 75             all.add(vo);
 76         }
 77         return all;
 78     }
 79 
 80     @Override
 81     public List<Admin> findBySplit(String column, String keyWord,
 82             Integer currentPage, Integer lineSize) throws SQLException {
 83         return null;
 84     }
 85 
 86     @Override
 87     public Integer getAllCount(String column, String keyWord)
 88             throws SQLException {
 89         return null;
 90     }
 91 
 92     @Override
 93     public boolean findLogin(Admin vo) throws Exception {
 94         boolean flag = false;
 95         String sql = "select lastdate,flag from admin where aid=? and password=? and status=1";
 96         super.pstmt = super.conn.prepareStatement(sql);
 97         super.pstmt.setString(1, vo.getAid());
 98         super.pstmt.setString(2, vo.getPassword());
 99         ResultSet rs = super.pstmt.executeQuery();
100         if(rs.next()){
101             flag = true;
102             vo.setLastDate(rs.getTimestamp("lastdate"));//设置lastdate
103             vo.setFlag(rs.getInt("flag"));
104         }
105         return flag;
106     }
107 
108     @Override
109     public boolean doUpdateByLastDate(String aid)
110             throws Exception {
111         boolean flag = false;
112         String sql = "update admin set lastdate = ? where aid = ?";
113         super.pstmt = super.conn.prepareStatement(sql);
114         //登陆成功后,使用当前日期为最后一次登陆日期
115         super.pstmt.setTimestamp(1, new Timestamp(new Date().getTime()));
116         super.pstmt.setString(2, aid);
117         int rel = super.pstmt.executeUpdate();
118         if(rel > 0){
119             flag = true;
120         }
121         return flag;
122     }
123 
124 }

  Service层:

    IAdminService(以某个模块为例)

      ----> ServiceImpl

        ---> 创建并注册 ServiceFactory

IAdminService

 1 package com.shawn.book.service;
 2 
 3 import com.shawn.book.vo.Admin;
 4 
 5 public interface IAdminService {
 6     
 7     /**
 8      * 实现管理员登录检查操作,调用IAdminDAO接口中的findLogin方法
 9      * @param vo 表示要操作的对象(aid,password)
10      * @return 成功返回true并且将最后一次登陆日期传递到页面,失败返回false
11      * @throws Exception
12      */
13     boolean login(Admin vo) throws Exception;
14     
15     /**
16      * 实现增加操作
17      * @param vo
18      * @return
19      * @throws Exception
20      */
21     boolean insert(Admin vo) throws Exception;
22     
23 }

AdminServiceImpl

 1 package com.shawn.book.service.impl;
 2 
 3 import com.shawn.book.dbc.DatabaseConnection;
 4 import com.shawn.book.factory.DAOFactory;
 5 import com.shawn.book.service.IAdminService;
 6 import com.shawn.book.vo.Admin;
 7 
 8 public class AdminServiceImpl implements IAdminService {
 9 
10     private DatabaseConnection dbc = new DatabaseConnection();
11     
12     @Override
13     public boolean login(Admin vo) throws Exception {
14         try{
15             if(DAOFactory.getIAdminDAOInstance(this.dbc.getConn()).findLogin(vo)){
16                 return DAOFactory.getIAdminDAOInstance(this.dbc.getConn()).doUpdateByLastDate(vo.getAid());
17             }
18             return false;
19         } catch(Exception e){
20             throw e;
21         } finally{
22             dbc.close();//最后一定要关闭数据库连接
23         }
24     }
25 
26     @Override
27     public boolean insert(Admin vo) throws Exception {
28         try{
29             if(DAOFactory.getIAdminDAOInstance(this.dbc.getConn()).findById(vo.getAid()) == null){
30                 DAOFactory.getIAdminDAOInstance(this.dbc.getConn()).doCreate(vo);
31                 return true;
32             }
33         } catch(Exception e){
34             throw e;
35         } finally{
36             this.dbc.close();
37         }
38         return false;
39     }
40 
41 }

    控制层:一个模块一个Servlet

AdminServlet

技术分享
  1 package com.shawn.book.servlet;
  2 
  3 import java.io.IOException;
  4 
  5 import javax.servlet.ServletException;
  6 import javax.servlet.http.HttpServlet;
  7 import javax.servlet.http.HttpServletRequest;
  8 import javax.servlet.http.HttpServletResponse;
  9 
 10 import com.shawn.book.factory.ServiceFactory;
 11 import com.shawn.book.util.MD5Code;
 12 import com.shawn.book.util.ValidateUtils;
 13 import com.shawn.book.vo.Admin;
 14 
 15 public class AdminServlet extends HttpServlet{
 16     
 17     private static final long serialVersionUID = -9132124124978042276L;
 18 
 19     @Override
 20     public void doGet(HttpServletRequest request, HttpServletResponse response)
 21             throws ServletException, IOException {
 22         
 23         String path = "/pages/errors.jsp";    //定义错误页面
 24         
 25         ///pages/back/AdminServlet/login 截取login这个字段
 26         String status = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/")+1);
 27         
 28         if(status != null){
 29             if("login".equals(status)){
 30                 path = this.login(request);
 31             } else if("logout".equals(status)){
 32                 path = this.logout(request);
 33             } else if("reg".equals(status)){
 34                 path = this.reg(request);
 35             }
 36         }
 37         
 38         request.getRequestDispatcher(path).forward(request, response);
 39     }
 40 
 41     public String reg(HttpServletRequest request) {
 42         String msg = "";
 43         String url = "";
 44         
 45         String aid = request.getParameter("aid");
 46         String password = request.getParameter("password");
 47         if(ValidateUtils.validateEmpty(aid) && 
 48                 ValidateUtils.validateEmpty(password)){
 49             Admin vo = new Admin();
 50             vo.setAid(aid);
 51             vo.setFlag(0);
 52             vo.setPassword(new MD5Code().getMD5ofStr(vo.getPassword()+vo.getAid()));
 53             vo.setStatus(1);//默认激活
 54             try {
 55                 if(ServiceFactory.getIAdminServiceInstance().insert(vo)){
 56                     msg = "添加管理员成功!";
 57                     url = "pages/back/admin/admin_insert.jsp";
 58                 } else {
 59                     msg = "添加管理员失败,请重新添加!";
 60                     url = "pages/back/admin/admin_insert.jsp";
 61                 }
 62             } catch (Exception e) {
 63                 msg = "添加管理员出现异常,请重新添加!";
 64                 url = "pages/back/admin/admin_insert.jsp";
 65                 e.printStackTrace();
 66             }
 67         } else {
 68             msg = "数据不能为空!";
 69             url = "pages/back/admin/admin_insert.jsp";
 70         }
 71         
 72         request.setAttribute("msg", msg);
 73         request.setAttribute("url", url);
 74         return "/pages/forward.jsp";
 75     }
 76 
 77     @Override
 78     public void doPost(HttpServletRequest request, HttpServletResponse response)
 79             throws ServletException, IOException {
 80         this.doGet(request, response);
 81     }
 82     
 83     /**
 84      * 实现登录
 85      * @param request
 86      * @return
 87      */
 88     public String login(HttpServletRequest request){
 89         String msg = ""; //表示提示信息
 90         String url = ""; //表示跳转路径
 91         
 92         //去的页面中传递过来的数据
 93         String aid = request.getParameter("aid");
 94         String password = request.getParameter("password");
 95         
 96         //判断数据是否为空
 97         if(ValidateUtils.validateEmpty(aid) && ValidateUtils.validateEmpty(password)){//表示数据存在
 98             Admin vo = new Admin();
 99             vo.setAid(aid);    //取得参数
100             vo.setPassword(new MD5Code().getMD5ofStr(password+aid)); //需要加盐处理
101             try {
102                 if(ServiceFactory.getIAdminServiceInstance().login(vo)){
103                     request.getSession().setAttribute("aid", aid);    //保存aid
104                     request.getSession().setAttribute("lastdate", vo.getLastDate());
105                     request.getSession().setAttribute("flag", vo.getFlag());
106                     msg = "登陆成功!";
107                     url = "pages/back/index.jsp";
108                 } else {
109                     msg = "登录失败,错误的ID或密码!";
110                     url = "login.jsp";
111                 }
112             } catch (Exception e) {
113                 e.printStackTrace();
114             }
115         } else {
116             msg = "数据不能为空";
117             url = "login.jsp";
118         }
119         request.setAttribute("msg",msg);
120         request.setAttribute("url",url);
121         return "/pages/forward.jsp";
122     }
123     
124     public String logout(HttpServletRequest request) {
125         String msg = "";
126         String url = "";
127         
128         request.getSession().invalidate();//表示session失效
129         msg = "已经成功退出系统,请重新登录!";
130         url = "login.jsp";
131         
132         request.setAttribute("msg", msg);
133         request.setAttribute("url", url);
134         return "/pages/forward.jsp";
135     }
136     
137 }
View Code

添加功能:先写dao方法 ---> service 方法 ---> 控制层逻辑;可以先把页面写好,有利于理清思路。

后台大致就是这种开发流程,因人而异。

有用的MD5加密类:

MD5Code

技术分享
1 MD5Code
View Code

用法:

package com.shawn.util;

import com.shawn.book.util.MD5Code;

public class MD5CodeTest {
    
    public static void main(String[] args) {
        System.out.println(new MD5Code().getMD5ofStr("admin123admin"));
    }
    
}

页面分页小脚本:

split_bar.jsp

技术分享
  1 <%@ page pageEncoding="UTF-8"%>
  2 <link rel="stylesheet" type="text/css" href="mldn.css">
  3 <%--
  4 <div id="splitBarDiv" style="float:right">
  5     <jsp:include page="/pages/split_page_plugin_bars.jsp"/>
  6 </div>
  7 --%>
  8 <%
  9 String path = request.getContextPath();
 10 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 11 %>
 12 <%
 13     String url = null ;
 14     int currentPage = 1 ;
 15     int lineSize = 5 ;
 16     String column = null ;
 17     String keyWord = null ;
 18     int allRecorders = 0 ;
 19     int pageSize = 0 ;
 20     int lsData [] = new int [] {1,5,10,15,20,30,50,100} ;
 21     int seed = 3 ;    // 种子数
 22     String paramName = request.getParameter("paramName") ;
 23     String paramValue = request.getParameter("paramValue") ;
 24 %>
 25 
 26 <%    // 接收传递的参数
 27     try {
 28         currentPage = (Integer) request.getAttribute("currentPage") ;
 29     } catch (Exception e) {}
 30     try {
 31         allRecorders = (Integer)request.getAttribute("allRecorders") ;
 32     } catch (Exception e) {}
 33     try {
 34         lineSize = (Integer) request.getAttribute("lineSize") ;
 35     } catch (Exception e) {}
 36     column = (String) request.getAttribute("column") ;
 37     keyWord = (String) request.getAttribute("keyWord") ;
 38     url = basePath + request.getAttribute("url") ;
 39 %>
 40 <%
 41     if (allRecorders > 0) {
 42         pageSize = (allRecorders + lineSize - 1) / lineSize ;
 43     } else {    // 没有记录
 44         pageSize = 1 ;
 45     }
 46 %>
 47 
 48 <script type="text/javascript">
 49     function goSplit(vcp) {    // 根据外部传递的cp内容进行操作
 50         try {
 51             var eleKw = document.getElementById("kw").value ;
 52             var eleCol = document.getElementById("colSel").value ;
 53             window.location = "<%=url%>?cp=" + vcp + "&ls=" + <%=lineSize%> + "&kw=" + eleKw + "&col=" + eleCol + "&<%=paramName%>=<%=paramValue%>" ;
 54         } catch (Exception) {
 55             window.location = "<%=url%>?cp=" + vcp + "&ls=" + <%=lineSize%> + "&<%=paramName%>=<%=paramValue%>" ;
 56         }
 57     }
 58 </script>
 59 <ul class="pagination"> 
 60 <%
 61 if (pageSize > seed * 3) {
 62 %>
 63     <li class="<%=currentPage == 1?"active":""%>"><a onclick="goSplit(1)">1</a></li>
 64     
 65 <%
 66     if (currentPage > seed * 2) {
 67 %>
 68         <li class="disabled"><span>...</span></li>
 69 <%
 70         int startPage = currentPage - seed ;
 71         int endPage = currentPage + seed ;
 72         for (int x = startPage ; x <= endPage ; x ++) {
 73             if(x < pageSize) {
 74 %>
 75                 <li class="<%=currentPage == x?"active":""%>"><a onclick="goSplit(<%=x%>)"><%=x%></a></li>
 76 <%
 77             }
 78         }
 79         if ((currentPage + seed * 2) <= pageSize) {
 80 %>
 81             <li class="disabled"><span>...</span></li>
 82 <%        
 83         }
 84     } else {    // 还在6页以前
 85         for (int x = 2 ; x <= currentPage + seed ; x ++) {
 86 %>
 87             <li class="<%=currentPage == x?"active":""%>"><a onclick="goSplit(<%=x%>)"><%=x%></a></li>
 88 <%
 89         }
 90                 if ((currentPage + seed * 2) <= pageSize) {
 91 %>
 92             <li class="disabled"><span>...</span></li>
 93 <%        
 94         }
 95     }
 96 %>
 97     <li class="<%=currentPage == pageSize?"active":""%>"><a onclick="goSplit(<%=pageSize%>)"><%=pageSize%></a></li>
 98 <%
 99 } else {
100     for (int x = 1 ; x <= pageSize ; x ++) {
101 %>
102         <li class="<%=currentPage == x?"active":""%>"><a onclick="goSplit(<%=x%>)"><%=x%></a></li>
103 <%
104     }
105 }
106 %>
107 </ul>
View Code

用法举例:

  servlet层:

技术分享
 1         Integer currentPage = 1;    //当前页
 2         Integer lineSize = 5;        //每页显示行数
 3         try{
 4             currentPage = Integer.parseInt(request.getParameter("cp") == null ? "1" : request.getParameter("cp"));    //当前页参数
 5             lineSize = Integer.parseInt(request.getParameter("ls") == null ? "5" : request.getParameter("ls"));        //每页显示行数
 6         } catch(Exception e){
 7             e.printStackTrace();
 8         }
 9         String keyWord = request.getParameter("kw");    //查询关键字
10         String column = request.getParameter("col");    //查询字段
11         if(keyWord == null){
12             keyWord = "";
13         }
14         if(column == null){
15             column = "name";
16         }
17         
18         try {
19             Map<String,Object> map = 
20                     ServiceFactory.getIBookServiceInstance().listBySplit(column, keyWord, currentPage, lineSize);
21             request.setAttribute("allBook", map.get("allBook"));
22             request.setAttribute("allRecorders", map.get("allRecord"));
23         } catch (Exception e) {
24             e.printStackTrace();
25         }
26         
27         request.setAttribute("url", "pages/back/book/BookServlet/listSplit");
28         request.setAttribute("currentPage", currentPage);
29         request.setAttribute("lineSize", lineSize);
30         request.setAttribute("currentPage", currentPage);
31         request.setAttribute("keyWord", keyWord);
32         
33         return "/pages/back/book/book_list.jsp";
34     
View Code

  service 层:

技术分享
 1     @Override
 2     public Map<String, Object> listBySplit(String column, String keyWord,
 3             int currentPage, int lineSize) throws Exception {
 4         Map<String, Object> map = null;
 5         try{
 6             map = new HashMap<String, Object>();
 7             map.put("allBook", DAOFactory.getIBookDAOInstance(this.dbc.getConn()).findBySplit(column, keyWord, currentPage, lineSize));
 8             map.put("allRecord", DAOFactory.getIBookDAOInstance(this.dbc.getConn()).getAllCount(column, keyWord));
 9         } catch(Exception e){
10             throw e;
11         } finally{
12             this.dbc.close();
13         }
14         return map;
15     }
View Code

  dao 层:

技术分享
 1 @Override
 2     public List<Book> findBySplit(String column, String keyWord,
 3             Integer currentPage, Integer lineSize) throws SQLException {
 4         List<Book> all = new ArrayList<Book>();
 5         String sql = "select * from "
 6                 + "(select b.bid,b.name,i.name iname,b.aid,b.credate,b.status,b.note "
 7                     + "from books b,admin a,item i where b.iid = i.iid and b.aid = a.aid and b."+column+" like ?) t"
 8                     + " order by t.bid limit ?,?";
 9         super.pstmt = super.conn.prepareStatement(sql);
10         super.pstmt.setString(1, "%" + keyWord + "%");
11         super.pstmt.setInt(2, (currentPage - 1)*lineSize);
12         super.pstmt.setInt(3, lineSize);
13         ResultSet rs = super.pstmt.executeQuery();
14         while(rs.next()){
15             Book vo = new Book();
16             vo.setBid(rs.getInt("bid"));
17             vo.setCredate(rs.getTimestamp("credate"));
18             vo.setName(rs.getString("name"));
19             vo.setNote(rs.getString("note"));
20             vo.setStatus(rs.getInt("status"));
21             Item item = new Item();
22             item.setName(rs.getString("iname"));
23             vo.setItem(item);
24             Admin admin = new Admin();
25             admin.setAid(rs.getString("aid"));
26             vo.setAdmin(admin);
27             all.add(vo);
28         }
29         return all;
30     }
31 
32     @Override
33     public Integer getAllCount(String column, String keyWord)
34             throws SQLException {
35         String sql = "select count(name) num from books where " + column + " like ?";
36         super.pstmt = super.conn.prepareStatement(sql);
37         super.pstmt.setString(1, "%" + keyWord + "%");
38         ResultSet rs = super.pstmt.executeQuery();
39         if(rs.next()){
40             int rel = rs.getInt("num");
41             return rel;
42         }
43         return 0;
44     }
View Code

 项目最终效果:

登录页面:

技术分享

首页大体效果:

技术分享

代码链接: https://pan.baidu.com/s/1eRWhAb4 密码: u5m9

JSP + Servlet 图书管理系统

标签:actor   contex   jdb   throws   eem   dao   exe   dmi   种子   

原文地址:http://www.cnblogs.com/ShawnYang/p/7481979.html

(3)
(1)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!