5.Hibernate实现全套增删改查和ajax异步分页

1.1 创建如下oracle数据库脚本

 1 drop sequence seq_stu;
 2 
 3 create sequence SEQ_STU
 4 minvalue 1
 5 maxvalue 999999999999999999999999999
 6 start with 1
 7 increment by 1
 8 cache 20;
 9 
10 drop table student;
11 
12 create table STUDENT
13 (
14   sid      NUMBER not null,
15   sname    VARCHAR2(20) not null,
16   password VARCHAR2(20) default '123',
17   sex     VARCHAR2(10) default '',
18   cid      NUMBER not null
19 );
20 alter table STUDENT
21   add constraint pk_SID primary key (SID);
22   
23 alter table STUDENT
24   add constraint CK_STUDENT_CID
25   check (cid between 1 and 50);
26 
27 insert into STUDENT (sid, sname, password, sex, cid)
28 values (SEQ_STU.NEXTVAL, '潜逃', '123', '', 1);
29 insert into STUDENT (sid, sname, password, sex, cid)
30 values (SEQ_STU.NEXTVAL, '周强', '123', '', 1);
31 insert into STUDENT (sid, sname, password, sex, cid)
32 values (SEQ_STU.NEXTVAL, '薛东', '123', '', 1);
33 insert into STUDENT (sid, sname, password, sex, cid)
34 values (SEQ_STU.NEXTVAL, '帅天威', '123', '', 2);
35 insert into STUDENT (sid, sname, password, sex, cid)
36 values (SEQ_STU.NEXTVAL, '汤帅', '123', '', 2);
37 insert into STUDENT (sid, sname, password, sex, cid)
38 values (SEQ_STU.NEXTVAL, '刘亮', '123', '', 2);
39 insert into STUDENT (sid, sname, password, sex, cid)
40 values (SEQ_STU.NEXTVAL, '李杰', '123', '', 3);
41 insert into STUDENT (sid, sname, password, sex, cid)
42 values (SEQ_STU.NEXTVAL, '唐龙', '123', '', 3);
43 insert into STUDENT (sid, sname, password, sex, cid)
44 values (SEQ_STU.NEXTVAL, '胡强', '123', '', 3);
45 insert into STUDENT (sid, sname, password, sex, cid)
46 values (SEQ_STU.NEXTVAL, '李文宝', '123', '', 4);
47 insert into STUDENT (sid, sname, password, sex, cid)
48 values (SEQ_STU.NEXTVAL, '程秀秀', '123', '', 4);
49 insert into STUDENT (sid, sname, password, sex, cid)
50 values (SEQ_STU.NEXTVAL, '陆羽', '123', '', 4);
51 insert into STUDENT (sid, sname, password, sex, cid)
52 values (SEQ_STU.NEXTVAL, 'holly', '123', '', 4);
53 commit;
54 
55 --只修改列表 列名重命名
56 alter table student rename column ssex to sex;
57 
58 select * from student;
59 
60 commit;
student.sql

1.2 创建如下项目结构

1.3 在项目的src根目录下创建hibernate.cfg.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" >
 3 <hibernate-configuration>
 4   <session-factory>
 5     <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
 6     <property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
 7     <property name="connection.username">holly</property>
 8     <property name="connection.password">sys</property>
 9     <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
10     <property name="show_sql">true</property>
11     <property name="format_sql">true</property>
12     <mapping resource="com/entity/Student.hbm.xml"/>
13   </session-factory>
14 </hibernate-configuration>
hibernate.cfg.xml

1.4 在项目的src下的com.entity包下创建Student.java

 1 package com.entity;
 2 
 3 public class Student {
 4     private Integer sid;
 5     private String sname;
 6     private String password;
 7     private String sex;
 8     private Integer cid;
 9     
10     public Student() {
11     }
12     public Student(Integer sid, String sname, String password, String sex,
13             Integer cid) {
14         this.sid = sid;
15         this.sname = sname;
16         this.password = password;
17         this.sex = sex;
18         this.cid = cid;
19     }
20     public Student(String sname, String password, String sex,
21             Integer cid) {
22         this.sname = sname;
23         this.password = password;
24         this.sex = sex;
25         this.cid = cid;
26     }
27     public Integer getSid() {
28         return sid;
29     }
30     public void setSid(Integer sid) {
31         this.sid = sid;
32     }
33     public String getSname() {
34         return sname;
35     }
36     public void setSname(String sname) {
37         this.sname = sname;
38     }
39     public String getPassword() {
40         return password;
41     }
42     public void setPassword(String password) {
43         this.password = password;
44     }
45     public String getSex() {
46         return sex;
47     }
48     public void setSex(String sex) {
49         this.sex = sex;
50     }
51     public Integer getCid() {
52         return cid;
53     }
54     public void setCid(Integer cid) {
55         this.cid = cid;
56     }
57     @Override
58     public String toString() {
59         return "Student [cid=" + cid + ", password=" + password + ", sex="
60                 + sex + ", sid=" + sid + ", sname=" + sname + "]";
61     }
62     
63     
64 
65 }
Student.java

1.5 在项目的src下的com.entity包下创建Student.hbm.xml映射文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
 3 <hibernate-mapping>
 4    <class name="com.entity.Student" table="STUDENT">
 5        <id name="sid" type="java.lang.Integer" column="SID">
 6           <generator class="sequence">
 7             <param name="sequence">SEQ_STU</param>
 8           </generator>
 9        </id>
10        <property name="sname" type="java.lang.String" column="SNAME"/>
11        <property name="password" type="java.lang.String" column="PASSWORD"/>
12        <property name="sex" type="java.lang.String" column="SEX"/>
13        <property name="cid" type="java.lang.Integer" column="CID"/>
14    </class>
15 </hibernate-mapping>
Student.hbm.xml

1.6 在项目的src下的com.page包下创建Page.java

 1 package com.page;
 2 
 3 public class Page {
 4     private Integer pagesize; //页面大小
 5     private Integer pageno; //当前页
 6     private Integer startrow; //起始行
 7     private Integer totalpage; //总页数
 8     private Integer totalcount; //总条数
 9     
10     
11     public Page() {
12     }
13     public Page(Integer pageSize, Integer pageNo, Integer totalCount) {
14         this.pagesize = pageSize; //页面大小 
15         this.pageno = pageNo;  //当前页
16         this.totalcount = totalCount; //计算总条数
17         this.setStartrow(pageNo, pageSize); //计算起始行
18         this.setTotalpage(totalCount, pageSize); //计算总页数
19     }
20     public Integer getPagesize() {
21         return pagesize;
22     }
23     public void setPagesize(Integer pageSize) {
24         this.pagesize = pageSize;
25     }
26     public Integer getPageno() {
27         return pageno;
28     }
29     public void setPageno(Integer pageNo) {
30         this.pageno = pageNo;
31     }
32     public Integer getStartrow() {
33         return startrow;
34     }
35     /**
36      * 计算起始行
37      * @param pageNo
38      * @param pageSize
39      */
40     public void setStartrow(Integer pageNo,Integer pageSize) {
41         this.startrow = (pageNo-1)*pageSize;
42     }
43     public Integer getTotalpage() {
44         return totalpage;
45     }
46     /**
47      * 计算总页数
48      * @param totalCount
49      * @param pageSize
50      */
51     public void setTotalpage(Integer totalCount,Integer pageSize) {
52         this.totalpage = totalCount%pageSize==0?totalCount/pageSize:totalCount/pageSize+1;
53     }
54     public Integer getTotalcount() {
55         return totalcount;
56     }
57     public void setTotalCount(Integer totalCount) {
58         this.totalcount = totalCount;
59     }
60     @Override
61     public String toString() {
62         return "[{\"pageno\":" + pageno + ",\"pagesize\":" + pagesize
63                 + ",\"startrow\":" + startrow + ",\"totalcount\":" + totalcount
64                 + ",\"totalpage\":" + totalpage + "}]";
65     }
66 
67 }
Page.java

1.7 在项目的src下的com.util包下创建Hibernate_Util.java

 1 package com.util;
 2 
 3 import org.hibernate.HibernateException;
 4 import org.hibernate.Session;
 5 import org.hibernate.SessionFactory;
 6 import org.hibernate.cfg.Configuration;
 7 
 8 /**
 9  * Hibernate打开session和关闭session
10  * @author Holly
11  *
12  */
13 public class Hibernate_Util {
14     private static ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
15     private static Configuration configuration=null;
16     private static SessionFactory sessionFactory=null;
17     static{
18         
19      try {
20         configuration=new Configuration().configure("/hibernate.cfg.xml");
21         sessionFactory=configuration.buildSessionFactory();
22      } catch (HibernateException e) {
23          System.out.println("解析xml和创建Session工厂error");
24         e.printStackTrace();
25     }
26       
27     }
28    
29     public static Session getSession(){
30         Session session=threadLocal.get();
31         if(session==null){
32             session=sessionFactory.openSession();
33             threadLocal.set(session);
34         }
35         return session;
36     }
37     public static void closeSession(){
38         Session session=threadLocal.get();
39         if(session!=null){
40               threadLocal.set(null);
41               session.close();
42         }
43     }
44     
45 }
Hibernate_Util.java

1.8 在项目的src下的com.dao包下创建StudentDao.java

 1 package com.dao;
 2 
 3 import java.util.Iterator;
 4 import java.util.List;
 5 
 6 import org.hibernate.Hibernate;
 7 import org.hibernate.Session;
 8 
 9 import com.entity.Student;
10 import com.page.Page;
11 import com.util.Hibernate_Util;
12 
13 import sun.print.resources.serviceui;
14 
15 public interface StudentDao {
16     /**
17      * 1.根据用户名和密码查询
18      * @param sname
19      * @param password
20      * @return
21      */
22     Student findByNameAndPwd(String sname,String password);
23     /**
24      * 2.延时加载:查询所有
25      * @return
26      */
27     List<Student> findAll();
28     /**
29      * 3.保存
30      * @param stu
31      * @return
32      */
33     int save(Student stu);
34     /**
35      * 4.根据主键id查询单条
36      * @param sid
37      * @return
38      */
39     Student findById(Integer sid);
40     /**
41      * 5.修改
42      */
43     int update(Student stu);
44     /**
45      * 6.删除对象
46      * @param stu
47      * @return
48      */
49     int delete(Student stu);
50     /**
51      * 7.分页查询
52      */
53     List<Student> findPage(Page page);
54     /**
55      * 8.查询总条数
56      */
57     int getTotalCount();
58     
59 }
StudentDao.java

1.9 在项目的src下的com.dao.impl包下创建StudentDaoImpl.java

  1 package com.dao.impl;
  2 
  3 import java.util.List;
  4 
  5 import org.hibernate.HibernateException;
  6 import org.hibernate.Query;
  7 import org.hibernate.Session;
  8 
  9 import com.dao.StudentDao;
 10 import com.entity.Student;
 11 import com.page.Page;
 12 import com.util.Hibernate_Util;
 13 
 14 public class StudentDaoImpl implements StudentDao{
 15     /**
 16      * 1.查询所有:立即加载
 17      */
 18     public List<Student> findAll() {
 19         //1.获取session对象
 20         Session session=Hibernate_Util.getSession();
 21         //2.定义hql语句
 22         String hql="from Student";
 23         //3.Session创建Query对象
 24         Query query=session.createQuery(hql);
 25         //4.query对象执行操作
 26         List<Student> it=query.list();
 27         //5.释放资源
 28         Hibernate_Util.closeSession();
 29         return it;
 30     }
 31     /**
 32      * 2.根据用户名和密码查询
 33      */
 34     public Student findByNameAndPwd(String sname, String password) {
 35         //1.获取session对象
 36         Session session=Hibernate_Util.getSession();
 37         //2.定义hql语句(命名参数)
 38         String hql="from Student where sname=:sname and password=:password";
 39         //3.Session创建Query对象
 40         Query query=session.createQuery(hql);
 41         //4.query对象给占位符赋值
 42         /*query.setString("sname", sname);
 43         query.setString("password", password);*/
 44         query.setParameter("sname", sname);
 45         query.setParameter("password", password);
 46     
 47 //        query.setProperties(user);
 48         //5.执行操作(uniqueResult()查询的单行数据)
 49         Student stu=(Student) query.uniqueResult();
 50         //6.释放资源
 51         Hibernate_Util.closeSession();
 52         return stu;
 53         
 54     }
 55     
 56 
 57    /**
 58     * 根据id主键查询单条
 59     */
 60     public Student findById(Integer sid) {
 61         //1.获取session对象
 62         Session session=Hibernate_Util.getSession();
 63         //2.利用session根据主键查询
 64         Student stu=(Student) session.get(Student.class, sid);
 65         /*3.
 66          * 因为在修改时要提前查询单条,和session关联已经变成持久化对象,
 67          * 而在修改时session执行update方法时,
 68          * 首先会查询该主键id是否存在,
 69          * 如果存在,则根据主键id修改该对象,此时对象已经处于持久化对象,
 70          * 而实际session中不能同时存在两个主键id相同的对象,
 71          * 否则会出现如下错误:
 72          * org.hibernate.NonUniqueObjectException: 
 73          * a different object with the same identifier 
 74          * value was already associated with the 
 75          * session: [com.entity.Student#1]
 76          */
 77           Hibernate_Util.closeSession();
 78          // session.clear();
 79         return stu;
 80     }
 81     /**
 82      * 删除对象
 83      */
 84     public int delete(Student stu) {
 85         int num=1;
 86         //1.获取session对象
 87         Session session=Hibernate_Util.getSession();
 88         
 89         try {
 90             //session删除操作
 91             session.delete(stu);
 92             session.beginTransaction().commit();
 93         } catch (HibernateException e) {
 94              num=0;
 95             // TODO Auto-generated catch block
 96             e.printStackTrace();
 97         }finally{
 98             //5.释放资源
 99             Hibernate_Util.closeSession();
100         }
101         
102         return num;
103     }
104     /**
105      * 添加
106      */
107     public int save(Student stu) {
108         int num=1;
109         //1.获取session对象
110         Session session=Hibernate_Util.getSession();
111         //执行操作
112         try {
113             session.save(stu);
114             session.beginTransaction().commit();
115         } catch (HibernateException e) {
116             num=0;
117             e.printStackTrace();
118         }finally{
119             //5.释放资源
120             Hibernate_Util.closeSession();
121         }
122         return num;
123     }
124    /**
125     * 修改
126     */
127     public int update(Student stu) {
128         int num=1;
129         //1.获取session对象
130         Session session=Hibernate_Util.getSession();
131         try {
132             //执行操作
133             //该对象的主键id必须存在
134             session.update(stu);
135             session.beginTransaction().commit();
136         } catch (HibernateException e) {
137             num=0;
138             e.printStackTrace();
139         }finally{
140             //5.释放资源
141             Hibernate_Util.closeSession();
142         }
143         return num;
144     }
145     /**
146      * 7.分页查询
147      */
148 public List<Student> findPage(Page page) {
149     //1.获取session
150     Session session=Hibernate_Util.getSession();
151     
152     //2.定义查询最大记录数的hql
153     String hql="from Student";
154     
155     //3.定义查询最大记录数的Query对象
156     Query querypage=session.createQuery(hql);
157     
158     //4.查询最大记录数的数据
159     querypage.setMaxResults(page.getPagesize());
160     
161     //5.确定查询起点
162     querypage.setFirstResult(page.getStartrow());
163     
164     //6.分页查询
165     List<Student> list=querypage.list();
166     
167     //7.关闭session
168     Hibernate_Util.closeSession();
169     
170     return list;
171 }
172 /**
173  * 8.查询总条数
174  */
175 public int getTotalCount() {
176     //1.获取session
177     Session session=Hibernate_Util.getSession();
178     
179     //2.定义查询总条数hql语句
180     String hqlcount="select count(*) from Student";
181     
182     //3.利用Session创建Query对象
183     Query querycount=session.createQuery(hqlcount);
184     
185     //4.获取总条数(返回单行数据uniqueResult())
186     Integer totalCount=Integer.parseInt(querycount.uniqueResult().toString());
187     //5.释放资源
188     Hibernate_Util.closeSession();
189     return totalCount;
190 }
191     
192 
193 }
StudentDaoImpl.java

1.10 在项目的src下的com.service包下创建StudentService.java

 1 package com.service;
 2 
 3 import java.util.List;
 4 
 5 import com.entity.Student;
 6 import com.page.Page;
 7 
 8 /**
 9  * 业务接口
10  * @author pc
11  *
12  */
13 public interface StudentService {
14     /**
15      * 1.登录的业务
16      * @param sname
17      * @param password
18      * @return
19      */
20     Student login(String sname,String password);
21     /**
22      * 2.注册
23      * @param stu
24      * @return
25      */
26     int register(Student stu);
27     
28     /**
29      * 3.查询所有
30      */
31     List<Student> findAll();
32     /**
33      * 4.根据主键id查询
34      * @param sid
35      * @return
36      */
37     Student findById(Integer sid);
38     /**
39      * 5.修改
40      */
41     int update(Student stu);
42     /**
43      * 6.删除
44      */
45     int delete(Student stu);
46     
47     /**
48      * 7.分页查询
49      */
50     List<Student> findPage(Page page);
51     /**
52      * 8.查询总条数
53      */
54     int getTotalCount();
55     
56 
57 }
StudentService.java

1.11 在项目的src下的com.service.impl包下创建StudentServiceImpl.java

 1 package com.service.impl;
 2 
 3 import java.util.Iterator;
 4 import java.util.List;
 5 
 6 import com.dao.StudentDao;
 7 import com.dao.impl.StudentDaoImpl;
 8 import com.entity.Student;
 9 import com.page.Page;
10 import com.service.StudentService;
11 
12 public class StudentServiceImpl implements StudentService {
13     /**
14      * 使用多态引用数据访问层对象
15      */
16     private StudentDao dao = new StudentDaoImpl();
17 
18     /**
19      * 登录
20      */
21     public Student login(String sname, String password) {
22         return dao.findByNameAndPwd(sname, password);
23     }
24 
25     public int delete(Student stu) {
26         // TODO Auto-generated method stub
27         return dao.delete(stu);
28     }
29 
30     public List<Student> findAll() {
31         // TODO Auto-generated method stub
32         return dao.findAll();
33     }
34 
35     public Student findById(Integer sid) {
36         // TODO Auto-generated method stub
37         return dao.findById(sid);
38     }
39 
40     public int register(Student stu) {
41         // TODO Auto-generated method stub
42         return dao.save(stu);
43     }
44 
45     public int update(Student stu) {
46         // TODO Auto-generated method stub
47         return dao.update(stu);
48     }
49 
50     public List<Student> findPage(Page page) {
51         // TODO Auto-generated method stub
52         return dao.findPage(page);
53     }
54 
55     public int getTotalCount() {
56         // TODO Auto-generated method stub
57         return dao.getTotalCount();
58     }
59 
60 }
StudentServiceImpl.java

 1.12 在项目的WebRoot下创建login.jsp页面

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%
 3     String path = request.getContextPath();
 4     String basePath = request.getScheme() + "://"
 5             + request.getServerName() + ":" + request.getServerPort()
 6             + path + "/";
 7 %>
 8 
 9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
10 <html>
11     <head>
12         <base href="<%=basePath%>">
13 
14         <title>My JSP 'index.jsp' starting page</title>
15         <meta http-equiv="pragma" content="no-cache">
16         <meta http-equiv="cache-control" content="no-cache">
17         <meta http-equiv="expires" content="0">
18         <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
19         <meta http-equiv="description" content="This is my page">
20         <!--
21     <link rel="stylesheet" type="text/css" href="styles.css">
22     -->
23     </head>
24 
25     <body>
26         <center>
27             <fieldset style="width: 300px;">
28                 <legend>
29                     登录
30                 </legend>
31                 <form action="LoginServlet" method="post">
32                     <table>
33                         <tr>
34                             <td>
35                                 用户名:
36                             </td>
37                             <td>
38                                 <input type="text" name="sname" />
39                             </td>
40                         </tr>
41                         <tr>
42                             <td>
43                                 密码:
44                             </td>
45                             <td>
46                                 <input type="password" name="password" />
47                             </td>
48                         </tr>
49                         <tr>
50                             <td>
51                                 <input type="submit" value="提交" />
52                             </td>
53                             <td>
54                                 <input type="reset" value="重置" />
55                             </td>
56                         </tr>
57                     </table>
58                 </form>
59             </fieldset>
60         </center>
61     </body>
62 </html>
login.jsp

1. 13 在项目的src下的com.servlet包下创建LoginServlet.java

 1 package com.servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 import com.entity.Student;
12 import com.service.StudentService;
13 import com.service.impl.StudentServiceImpl;
14 
15 public class LoginServlet extends HttpServlet {
16 
17     public void doGet(HttpServletRequest request, HttpServletResponse response)
18             throws ServletException, IOException {
19 
20        this.doPost(request, response);
21     }
22 
23     
24     public void doPost(HttpServletRequest request, HttpServletResponse response)
25             throws ServletException, IOException {
26         request.setCharacterEncoding("UTF-8");
27         response.setCharacterEncoding("UTF-8");
28         response.setContentType("text/html;charset=UTF-8");
29         
30         //2.接受参数
31         String sname=request.getParameter("sname");
32         String password=request.getParameter("password");
33         //3.业务处理
34         StudentService service=new StudentServiceImpl();
35         Student stu=service.login(sname, password);
36         if(stu!=null){
37             System.out.println("login success!");
38             //4.页面跳转
39             request.getSession().setAttribute("sname", sname);
40             response.sendRedirect("FindAllServlet");
41         }else{
42             System.out.println("login fail!");
43             
44         }
45         
46     }
47 
48 }
LoginServlet.java

1.14 在项目WebRoot下的WEB-INF下的web.xml中配置servlet

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.5" 
 3     xmlns="http://java.sun.com/xml/ns/javaee" 
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 6     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 7   <servlet>
 8     <servlet-name>LoginServlet</servlet-name>
 9     <servlet-class>com.servlet.LoginServlet</servlet-class>
10   </servlet>
11   <servlet-mapping>
12     <servlet-name>LoginServlet</servlet-name>
13     <url-pattern>/LoginServlet</url-pattern>
14   </servlet-mapping>
15   <welcome-file-list>
16     <welcome-file>login.jsp</welcome-file>
17   </welcome-file-list>
18 </web-app>
web.xml

1.15 在项目的src下的com.servlet包下创建FindAllServlet.java

 1 package com.servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 import java.util.Iterator;
 6 import java.util.List;
 7 
 8 import javax.servlet.ServletException;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 
13 import com.entity.Student;
14 import com.page.Page;
15 import com.service.StudentService;
16 import com.service.impl.StudentServiceImpl;
17 
18 public class FindAllServlet extends HttpServlet {
19 
20 
21     public void doGet(HttpServletRequest request, HttpServletResponse response)
22             throws ServletException, IOException {
23 
24        this.doPost(request, response);
25     }
26 
27     
28     public void doPost(HttpServletRequest request, HttpServletResponse response)
29             throws ServletException, IOException {
30         request.setCharacterEncoding("UTF-8");
31         response.setCharacterEncoding("UTF-8");
32         response.setContentType("text/html;charset=UTF-8");
33         
34         /**
35          * ☆
36          * 在使用ajax往前台通过输出流对象的print方法发送json时
37          * 该行获取输出流对象的代码必须放在
38          * response.setContentType("text/html;charset=UTF-8");
39          * 之后,否则ajax回调时,页面拿到的中文数据就永远都是乱码,
40          * 原因是:如果将改行代码写在处理客户端乱码之前,表示编码格式已经确定,
41          * 所以,编码格式的处理应该放在获取PrintWriter对象之前
42          * 
43          */
44         PrintWriter out=response.getWriter();
45         
46 
47         // 2.接受参数
48         String no=request.getParameter("pageNo");
49         
50 
51         // 3.业务处理
52         StudentService service = new StudentServiceImpl();
53         
54         int pageSize=3; //页面大小
55         int pageNo=1; //默认的pageNo为1
56         if(no!=null && no!=""){
57             pageNo=Integer.valueOf(no);
58         }
59         //获取总条数
60         int totalCount=service.getTotalCount();
61         Page page=new Page(pageSize, pageNo, totalCount);
62         
63         List<Student> list = service.findPage(page);
64         if(list!=null){
65              System.out.println("find All page success");
66               request.setAttribute("list", list);
67               request.setAttribute("page", page);
68               request.getRequestDispatcher("index.jsp").forward(request, response);
69         }else{
70             System.out.println("find All page fail!");
71             
72         
73         }
74         
75     }    
76         
77     }
FindAllServlet.java

1.16. 在项目的WebRoot下创建index.jsp页面

  1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  2 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  3 <%
  4     String path = request.getContextPath();
  5     String basePath = request.getScheme() + "://"
  6             + request.getServerName() + ":" + request.getServerPort()
  7             + path + "/";
  8 %>
  9 
 10 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 11 <html>
 12     <head>
 13         <base href="<%=basePath%>">
 14 
 15         <title>My JSP 'index.jsp' starting page</title>
 16         <meta http-equiv="pragma" content="no-cache">
 17         <meta http-equiv="cache-control" content="no-cache">
 18         <meta http-equiv="expires" content="0">
 19         <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 20         <meta http-equiv="description" content="This is my page">
 21         <!--
 22     <link rel="stylesheet" type="text/css" href="styles.css">
 23     -->
 24     </head>
 25 
 26     <body>
 27     <CENTER>
 28         <table>
 29             <tr>
 30                 <td colspan="4">
 31                     <a href="register.jsp">注册</a>
 32                 </td>
 33             </tr>
 34             <tr>
 35                 <td>
 36                     序号
 37                 </td>
 38                 <td>
 39                     姓名
 40                 </td>
 41                 <td>
 42                     性别
 43                 </td>
 44                 <td>
 45                     操作
 46                 </td>
 47             </tr>
 48             
 49             <c:forEach var="i" items="${list}">
 50                 <tr>
 51                     <td>
 52                         ${i.sid }
 53                     </td>
 54                     <td>
 55                         ${i.sname }
 56                     </td>
 57                     <td>
 58                         ${i.sex }
 59                     </td>
 60                     <td>
 61                         <a href="FindByIdSerlvet?sid=${i.sid}">修改</a>
 62                         &nbsp;&nbsp;
 63                         <a href="DeleteSerlvet?sid=${i.sid}">删除</a>
 64                         
 65                     </td>
 66                 </tr>
 67             </c:forEach>
 68             
 69         </table>
 70         <div>
 71         
 72         
 73         第${page.pageno}/${page.totalpage}页 &nbsp;&nbsp;
 74         <a href="FindAllServlet?pageNo=1">首页</a>
 75         <c:choose>
 76           <c:when test="${page.pageno gt 1}">
 77             <a href="FindAllServlet?pageNo=${page.pageno-1 }">上一页</a>
 78           </c:when>
 79           <c:otherwise>
 80             <a href="javascript:alert('已经是第一页了,没有上一页!');">上一页</a>
 81           </c:otherwise>
 82         </c:choose>
 83         <c:choose>
 84           <c:when test="${page.pageno lt page.totalpage}">
 85             <a href="FindAllServlet?pageNo=${page.pageno+1 }">下一页</a>
 86           </c:when>
 87           <c:otherwise>
 88             <a href="javascript:alert('已经是最有一页了,没有下一页!');">下一页</a>
 89           </c:otherwise>
 90         </c:choose>
 91         
 92         <a href="FindAllServlet?pageNo=${page.totalpage}">末页</a>
 93         &nbsp;&nbsp;
 94         共${page.totalcount}条
 95         
 96         </div>
 97         
 98     </CENTER>
 99         
100     </body>
101 </html>
index.jsp

1.17 运行登录和查询的效果

 

1.18 在项目的WebRoot下创建register.jsp页面

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 3 <%
 4     String path = request.getContextPath();
 5     String basePath = request.getScheme() + "://"
 6             + request.getServerName() + ":" + request.getServerPort()
 7             + path + "/";
 8 %>
 9 
10 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
11 <html>
12     <head>
13         <base href="<%=basePath%>">
14 
15         <title>My JSP 'index.jsp' starting page</title>
16         <meta http-equiv="pragma" content="no-cache">
17         <meta http-equiv="cache-control" content="no-cache">
18         <meta http-equiv="expires" content="0">
19         <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
20         <meta http-equiv="description" content="This is my page">
21         <!--
22     <link rel="stylesheet" type="text/css" href="styles.css">
23     -->
24     </head>
25 
26     <body> 
27         <center>
28             <fieldset style="width: 300px;">
29                 <legend> 
30                     注册 
31                 </legend>
32                 <form action="RegisterServlet" method="post">
33                     <table>
34                         <tr>
35                             <td>
36                                 用户名:
37                             </td>
38                             <td>
39                                 <input type="text" name="sname"/>
40                             </td>
41                         </tr>
42                         <tr>
43                             <td>
44                                 密码:
45                             </td>
46                             <td>
47                                 <input type="password" name="password"/>
48                             </td>
49                         </tr>
50                         <tr>
51                             <td>
52                                 性别:
53                             </td>
54                             <td>
55                                     <input type="radio" name="sex" value="男" checked="checked"/>56                                     <input type="radio" name="sex" value="女"/>57                             </td>
58                         </tr>
59                         <tr>
60                             <td>
61                                 班级编号:
62                             </td>
63                             <td>
64                                 <select name="cid">
65                                   <option value="1">TB07</option>
66                                   <option value="2">TB13</option>
67                                   <option value="3">TB24</option>
68                                   <option value="4">TB31</option>
69                                 </select>
70                             </td>
71                         </tr>
72                         <tr>
73                             <td>
74                                 <input type="submit" value="修改" />
75                             </td>
76                             <td>
77                                 <input type="reset" value="重置" />
78                             </td>
79                         </tr>
80                     </table>
81                 </form>
82             </fieldset>
83         </center>
84     </body>
85 </html>
register.jsp

1.19.在项目的src下的com.servlet包下创建RegisterServlet.java

 1 package com.servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 import com.entity.Student;
12 import com.service.StudentService;
13 import com.service.impl.StudentServiceImpl;
14 
15 public class RegisterServlet extends HttpServlet {
16     public void doGet(HttpServletRequest request, HttpServletResponse response)
17             throws ServletException, IOException {
18 
19         this.doPost(request, response);
20     }
21 
22     public void doPost(HttpServletRequest request, HttpServletResponse response)
23             throws ServletException, IOException {
24         request.setCharacterEncoding("UTF-8");
25         response.setCharacterEncoding("UTF-8");
26         response.setContentType("text/html;charset=UTF-8");
27 
28         // 2.接受参数
29         String sname = request.getParameter("sname");
30         String password = request.getParameter("password");
31         String sex = request.getParameter("sex");
32         Integer cid = Integer.valueOf(request.getParameter("cid"));
33         Student stu = new Student(sname, password, sex, cid);
34 
35         // 3.业务处理
36         StudentService service = new StudentServiceImpl();
37         int num = service.register(stu);
38         if (num > 0) {
39             System.out.println("register success!");
40             response.sendRedirect("FindAllServlet");
41         } else {
42             System.out.println("register fail!");
43 
44         }
45 
46     }
47 
48 }
RegisterServlet.java

1.20 在上面点击注册超链接出现如下页面

1.21  在项目的WebRoot下创建update.jsp页面

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 3 <%
 4     String path = request.getContextPath();
 5     String basePath = request.getScheme() + "://"
 6             + request.getServerName() + ":" + request.getServerPort()
 7             + path + "/";
 8 %>
 9 
10 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
11 <html>
12     <head>
13         <base href="<%=basePath%>">
14         <title>My JSP 'index.jsp' starting page</title>
15         <meta http-equiv="pragma" content="no-cache">
16         <meta http-equiv="cache-control" content="no-cache">
17         <meta http-equiv="expires" content="0">
18         <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
19         <meta http-equiv="description" content="This is my page">
20         <!--
21     <link rel="stylesheet" type="text/css" href="styles.css">
22     -->
23     </head>
24 
25     <body> 
26         <center>
27             <fieldset style="width: 300px;">
28                 <legend>  
29                     <br>修改  
30                 </legend>
31                 <form action="UpdateServlet?sid=${stu.sid}" method="post">
32                     <table>
33                         <tr>
34                             <td>
35                                 用户名:
36                             </td>
37                             <td>
38                                 <input type="text" name="sname" value="${stu.sname}"/>
39                             </td>
40                         </tr>
41                         <tr>
42                             <td>
43                                 密码:
44                             </td>
45                             <td>
46                                 <input type="password" name="password" value="${stu.password}"/>
47                             </td>
48                         </tr>
49                         <tr>
50                             <td>
51                                 性别:
52                             </td>
53                             <td>
54                                 <c:choose>
55                                   <c:when test="${stu.sex eq '男'}">
56                                     <input type="radio" name="sex" value="男" checked="checked"/>57                                     <input type="radio" name="sex" value="女"/>58                                   </c:when>
59                                   <c:otherwise>
60                                      <input type="radio" name="sex" value="男"/>61                                     <input type="radio" name="sex" value="女" checked="checked"/>62                                   </c:otherwise>
63                                 </c:choose>
64                             </td>
65                         </tr>
66                         <tr>
67                             <td>
68                                 班级编号:
69                             </td>
70                             <td>
71                                 <select name="cid">
72                                   <option value="1">TB07</option>
73                                   <option value="2">TB13</option>
74                                   <option value="3">TB24</option>
75                                   <option value="4">TB31</option>
76                                 </select>
77                             </td>
78                         </tr>
79                         
80                         <tr>
81                             <td>
82                                 <input type="submit" value="修改" />
83                             </td>
84                             <td>
85                                 <input type="reset" value="重置" />
86                             </td>
87                         </tr>
88                     </table>
89                 </form>
90             </fieldset>
91         </center>
92     </body>
93 </html>
update.jsp

1.22  在项目的src下的com.servlet包下创建FindByIdSerlvet.java

 1 package com.servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 import com.entity.Student;
12 import com.service.StudentService;
13 import com.service.impl.StudentServiceImpl;
14 import com.util.Hibernate_Util;
15 
16 public class FindByIdSerlvet extends HttpServlet {
17     public void doGet(HttpServletRequest request, HttpServletResponse response)
18             throws ServletException, IOException {
19 
20         this.doPost(request, response);
21     }
22 
23     public void doPost(HttpServletRequest request, HttpServletResponse response)
24             throws ServletException, IOException {
25         request.setCharacterEncoding("UTF-8");
26         response.setCharacterEncoding("UTF-8");
27         response.setContentType("text/html;charset=UTF-8");
28 
29         // 2.接受参数
30         Integer sid=Integer.valueOf(request.getParameter("sid"));
31         
32         // 3.业务处理
33         StudentService service = new StudentServiceImpl();
34          
35          Student stu=service.findById(sid);
36          System.out.println("stu:"+stu);
37          if(stu!=null){
38              System.out.println("根据id查询到对象");
39              request.setAttribute("stu", stu);
40              request.getRequestDispatcher("update.jsp").forward(request, response);
41          }else{
42              System.out.println("没有根据id查询到对象");
43          }
44 
45     }
46 
47 }
48 
49 FindByIdSerlvet.java
FindByIdServlet.java

1.23  在项目的src下的com.servlet包下创建UpdateServlet.java

 1 package com.servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 import com.entity.Student;
12 import com.service.StudentService;
13 import com.service.impl.StudentServiceImpl;
14 
15 public class UpdateServlet extends HttpServlet {
16     public void doGet(HttpServletRequest request, HttpServletResponse response)
17             throws ServletException, IOException {
18 
19         this.doPost(request, response);
20     }
21 
22     public void doPost(HttpServletRequest request, HttpServletResponse response)
23             throws ServletException, IOException {
24         request.setCharacterEncoding("UTF-8");
25         response.setCharacterEncoding("UTF-8");
26         response.setContentType("text/html;charset=UTF-8");
27 
28         // 2.接受参数
29         Integer sid=Integer.valueOf(request.getParameter("sid"));
30         String sname = request.getParameter("sname");
31         String password = request.getParameter("password");
32         String sex = request.getParameter("sex");
33         Integer cid=Integer.valueOf(request.getParameter("cid"));
34         Student stu=new Student(sid,sname, password, sex, cid);
35         
36         // 3.业务处理
37         StudentService service = new StudentServiceImpl();
38         int num=service.update(stu);
39         if(num>0){
40             System.out.println("update success!");
41             response.sendRedirect("FindAllServlet");
42         }else{
43             System.out.println("update fail!");
44             
45         }
46 
47     }
48 
49 }
UpdateServlet.java

1.24  点击修改超链接,进行修改会出现如下页面

1. 25 在项目的src下的com.servlet包下创建DeleteSerlvet.java

 1 package com.servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 import com.entity.Student;
12 import com.service.StudentService;
13 import com.service.impl.StudentServiceImpl;
14 
15 public class DeleteSerlvet extends HttpServlet {
16     public void doGet(HttpServletRequest request, HttpServletResponse response)
17             throws ServletException, IOException {
18 
19         this.doPost(request, response);
20     }
21 
22     public void doPost(HttpServletRequest request, HttpServletResponse response)
23             throws ServletException, IOException {
24         request.setCharacterEncoding("UTF-8");
25         response.setCharacterEncoding("UTF-8");
26         response.setContentType("text/html;charset=UTF-8");
27 
28         // 2.接受参数
29         Integer sid=Integer.valueOf(request.getParameter("sid"));
30         // 3.业务处理
31         StudentService service = new StudentServiceImpl();
32         Student stu=service.findById(sid);
33         if (stu != null) {
34             System.out.println("根据id查询成功");
35              int num=service.delete(stu);
36              if(num>0){
37                  System.out.println("delete success!!");
38                  // 4.页面跳转
39                  response.sendRedirect("FindAllServlet");
40                  
41              }else{
42                  System.out.println("delete success!!");
43                  
44              }
45         } else {
46             System.out.println("根据id查询失败!");
47 
48         }
49 
50     }
51 
52 }
DeleteSerlvet.java

1.26 点击第一条删除

1.26 在项目的src下的com.servlet包下创建FindPageServlet.java

 1 package com.servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 import java.util.ArrayList;
 6 import java.util.Hashtable;
 7 import java.util.List;
 8 
 9 import javax.servlet.ServletException;
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 
14 import org.codehaus.jackson.map.ObjectMapper;
15 
16 import com.entity.Student;
17 import com.page.Page;
18 import com.service.StudentService;
19 import com.service.impl.StudentServiceImpl;
20 
21 /**
22  * 分页查询
23  * 
24  * @author pc
25  * 
26  */
27 public class FindPageServlet extends HttpServlet {
28 
29     public void doGet(HttpServletRequest request, HttpServletResponse response)
30             throws ServletException, IOException {
31 
32         this.doPost(request, response);
33     }
34 
35     public void doPost(HttpServletRequest request, HttpServletResponse response)
36             throws ServletException, IOException {
37         response.setContentType("text/html;charset=UTF-8");
38         request.setCharacterEncoding("UTF-8");
39         response.setCharacterEncoding("UTF-8");
40         /**
41          * ☆
42          * 在使用ajax往前台通过输出流对象的print方法发送json时
43          * 该行获取输出流对象的代码必须放在
44          * response.setContentType("text/html;charset=UTF-8");
45          * 之后,否则ajax回调时,页面拿到的中文数据就永远都是乱码,
46          * 原因是:如果将改行代码写在处理客户端乱码之前,表示编码格式已经确定,
47          * 所以,编码格式的处理应该放在获取PrintWriter对象之前
48          * 
49          */
50         PrintWriter out=response.getWriter();
51         
52 
53         // 2.接受参数
54         String no=request.getParameter("pageNo");
55         
56 
57         // 3.业务处理
58         StudentService service = new StudentServiceImpl();
59         
60         int pageSize=3; //页面大小
61         int pageNo=1; //默认的pageNo为1
62         if(no!=null && no!=""){
63             pageNo=Integer.valueOf(no);
64         }
65         //获取总条数
66         int totalCount=service.getTotalCount();
67         //封装分页所需字段
68         Page page=new Page(pageSize, pageNo, totalCount);
69         //分页查询
70         List<Student> list = service.findPage(page);
71         
72         ObjectMapper om=new ObjectMapper();
73         String str=om.writeValueAsString(list);
74         String pagestr=om.writeValueAsString(page);
75         str="{\"page\":"+pagestr+",\"list\":"+str+"}";
76         System.out.println(str);
77         
78         out.print(str);
79         /*if (list != null) {
80             System.out.println("find page success");
81             request.setAttribute("list", list);
82             request.setAttribute("page", page);
83             request.getRequestDispatcher("index.jsp").forward(request, response);
84         } else {
85             System.out.println("find page fail!");
86 
87         }*/
88 
89     }
90 
91 }
FindPageServlet.java

1. 27 在项目WebRoot下创建ajaxindex.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 3 <%
 4     String path = request.getContextPath();
 5     String basePath = request.getScheme() + "://"
 6             + request.getServerName() + ":" + request.getServerPort()
 7             + path + "/";
 8 %>
 9 
10 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
11 <html>
12     <head>
13         <base href="<%=basePath%>">
14 
15         <title>My JSP 'index.jsp' starting page</title>
16         <meta http-equiv="pragma" content="no-cache">
17         <meta http-equiv="cache-control" content="no-cache">
18         <meta http-equiv="expires" content="0">
19         <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
20         <meta http-equiv="description" content="This is my page">
21         <!--
22     <link rel="stylesheet" type="text/css" href="styles.css">
23     -->
24     <script type="text/javascript" src="js/jquery-1.8.3.js"></script>
25     <script type="text/javascript" src="js/ajaxindex.js"></script>
26     </head>
27 
28     <body>
29     <CENTER>
30        
31         <table></table>
32         <div> 
33<span id="pageNo"></span>/<span id="totalPage"></span>&nbsp;&nbsp;
34             <a href="javascript:void(0);" class="apage">首页</a>  &nbsp;&nbsp;
35             <a href="javascript:void(0);" class="apage">上一页</a> &nbsp;&nbsp;
36             <a href="javascript:void(0);" class="apage">下一页</a> &nbsp;&nbsp;
37             <a href="javascript:void(0);" class="apage">末页</a>&nbsp;&nbsp;
38<span id="totalCount"></span>39         </div>
40         
41     </CENTER>
42         
43     </body>
44 </html>
ajaxindex.jsp

1.28 在项目WebRoot下的WEB-INF下的web.xml中配置servlet

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.5" 
 3     xmlns="http://java.sun.com/xml/ns/javaee" 
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 6     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 7   <servlet>
 8     <servlet-name>LoginServlet</servlet-name>
 9     <servlet-class>com.servlet.LoginServlet</servlet-class>
10   </servlet>
11   <servlet-mapping>
12     <servlet-name>LoginServlet</servlet-name>
13     <url-pattern>/LoginServlet</url-pattern>
14   </servlet-mapping>
15   <servlet>
16     <servlet-name>FindAllServlet</servlet-name>
17     <servlet-class>com.servlet.FindAllServlet</servlet-class>
18   </servlet>
19  <servlet-mapping>
20     <servlet-name>FindAllServlet</servlet-name>
21     <url-pattern>/FindAllServlet</url-pattern>
22   </servlet-mapping>
23     <servlet>
24     <servlet-name>RegisterServlet</servlet-name>
25     <servlet-class>com.servlet.RegisterServlet</servlet-class>
26   </servlet>
27   <servlet-mapping>
28     <servlet-name>RegisterServlet</servlet-name>
29     <url-pattern>/RegisterServlet</url-pattern>
30   </servlet-mapping>
31  
32  
33   <servlet>
34     <servlet-name>FindByIdSerlvet</servlet-name>
35     <servlet-class>com.servlet.FindByIdSerlvet</servlet-class>
36   </servlet>
37      <servlet-mapping>
38     <servlet-name>FindByIdSerlvet</servlet-name>
39     <url-pattern>/FindByIdSerlvet</url-pattern>
40   </servlet-mapping>
41   
42   <servlet>
43     <servlet-name>UpdateServlet</servlet-name>
44     <servlet-class>com.servlet.UpdateServlet</servlet-class>
45   </servlet>
46  <servlet-mapping>
47     <servlet-name>UpdateServlet</servlet-name>
48     <url-pattern>/UpdateServlet</url-pattern>
49   </servlet-mapping>
50    <servlet>
51     <servlet-name>DeleteSerlvet</servlet-name>
52     <servlet-class>com.servlet.DeleteSerlvet</servlet-class>
53   </servlet>
54   
55   <servlet-mapping>
56     <servlet-name>DeleteSerlvet</servlet-name>
57     <url-pattern>/DeleteSerlvet</url-pattern>
58   </servlet-mapping>
59    <servlet>
60     <servlet-name>FindPageServlet</servlet-name>
61     <servlet-class>com.servlet.FindPageServlet</servlet-class>
62   </servlet>
63   <servlet-mapping>
64     <servlet-name>FindPageServlet</servlet-name>
65     <url-pattern>/FindPageServlet</url-pattern>
66   </servlet-mapping> 
67   
68   <welcome-file-list>
69     <welcome-file>login.jsp</welcome-file>
70   </welcome-file-list>
71 </web-app>
web.xml

1.29 在项目WebRoot下的js文件中创建ajaxindex.js

  1 $(function() {
  2     /*1.获取页面上span标签中显示的pageNo的值
  3      * 因为第一次span标签里没有,所以为空,
  4      * 此时后台因为前台接到的是空,后台就会默认给1,
  5      * 然后再返回前台页面,
  6      * 所以第一次使用ajax回调时pageNo传过去为null,
  7      * 第二次是页面点击分页超链接重新赋值pageNo
  8      * 所以这里ajax第一次访问和点击分页查询可以提取成一个方法
  9      */
 10     var pageNo = $("#pageNo").text();
 11 
 12     /*
 13      * 2.ajax第一次通过页面去后台服务器回调数据
 14      * 调用ajax公共函数实现回调(第一次访问参数是null,
 15      * 等第一次访问从后代服务器回来时,将会带一个pageNo的值回来,
 16      * 然后将该值放入分页的span标签id为pageNo中,
 17      * 所以第二次访问的pageNo就有值了,该值是上一次访问从后台带回来的值
 18      */
 19     getAjaxPage(pageNo);
 20 
 21     /*
 22      * 3.超链接分页查询
 23      * ajax非第一次去后台获取数据
 24      */
 25     $(".apage").click(function() {
 26         /*
 27          * 3.1获取pageNo的值
 28          * 获取的是上一次回调过后放在id为pageNo的span标签的值
 29          */
 30         var pageNo = parseInt($("#pageNo").text());
 31         /*
 32          * 3.2 获取totalPage的值
 33          * 获取的是上一次回调过后放在id为totalPage的span标签的值
 34          */
 35         var totalPage = parseInt($("#totalPage").text());
 36 
 37         /*
 38          * 3.3获取分页超链接的文本
 39          * 因为要判断是首页?上一页?下一页?末页?
 40          * 从而重新给pageNo设值
 41          */
 42         var pagetext = $(this).html();
 43         //去 alert(pagetext);
 44 
 45             /*
 46              * 4.判断是首页?上一页?下一页?末页?
 47              * 从而重新给pageNo设值
 48              * */
 49             if (pagetext == "首页") {
 50                 pageNo = 1;
 51             } else if (pagetext == "上一页") {
 52                 if (pageNo > 1) {
 53                     pageNo = pageNo - 1;
 54                 } else {
 55                     alert("已经是第一页了!");
 56                     //如果已经是第一页了,则不容许接下来的操作再进行所以return
 57                     return;
 58                 }
 59             } else if (pagetext == "下一页") {
 60                 if (pageNo < totalPage) {
 61                     pageNo = pageNo + 1;
 62                 } else {
 63                     alert("已经是最后一页了!");
 64                     //如果已经是最后一页了,则不容许接下来的操作再进行所以return
 65                     return;
 66                 }
 67             } else if (pagetext == "末页") {
 68                 pageNo = totalPage;
 69             }
 70 
 71             //去 alert("pageNo:"+pageNo);
 72             /*
 73              * 5.调用ajax公共函数实现回调
 74              * 注意:此时调用时非第一次调用,而且pageNo是肯定有值的
 75              */
 76             getAjaxPage(pageNo);
 77 
 78         });
 79 
 80 });
 81 
 82 /*二. ajax异步分页公共函数*/
 83 function getAjaxPage(pageNo) {
 84     /**
 85      * url:要回调的地址
 86      * type:是请求的方式,post或get
 87      * dataType:是回调函数得到的数据类型
 88      * data:表示的发到后台的的参数,
 89      * 后台回去的时候是通过request.getParameter("key")获取
 90      * 参数名建议用双引号引起来
 91      * contenttype:设置页面发送到后台服务器的文字进行乱码处理
 92      * async:ajax异步属性,默认值为true表示异步,为false表示同步
 93      * success:表示数据成功回调后处理的函数,obj是承载后台数据的参数默认是Object类型
 94      * error:表示数据回调失败的处理的函数, 
 95      * 
 96      */
 97     $.ajax( {
 98         url:'FindPageServlet',
 99         type:'post',
100         dataType:'json',
101         data:{"pageNo":pageNo},
102         async:true,
103         contenttype:"application/x-www-form-urlencoded;charset=UTF-8",
104         success:function(obj) {
105             /*
106              * 2.1 由于每一次回调的数据不一样,但却是放在同一个table标签中
107              * 所以在每次添加新数据之前,要将上一次内容清空,再添加新的
108              */
109             $("table").html(" ");
110             
111             /*
112              * 2.2 获取后台回来的pageNo的值,
113              * 并添加到页面id为pageNo的span标签中,
114              * 以备下一次点击分页超链接时使用*/
115             //var pageNo = obj.page[0].pageno;
116             var pageNo = obj.page.pageno;
117             $("#pageNo").text(pageNo);
118             
119             /*
120              * 2.3 获取后台回来的totalPage的值,
121              * 并添加到页面id为totalPage的span标签中,
122              * 以备下一次点击分页超链接时使用*/
123             //var totalPage = obj.page[0].totalpage;
124             var totalPage = obj.page.totalpage;
125             $("#totalPage").text(totalPage);
126             
127             /*
128              * 2.4 获取后台回来的totalCount的值,
129              * 并添加到页面id为totalCount的span标签中,
130              * 以备下一次点击分页超链接时使用*/
131             //var totalCount = obj.page[0].totalcount;
132             var totalCount = obj.page.totalcount;
133             $("#totalCount").text(totalCount);
134             
135             /*
136              * 2.5 拼接table行数据*/
137             str = "<tr><td><a href='register.jsp'>注册</a><td></tr>";
138             str += "<tr><td>序号</td><td>姓名</td><td>性别</td><td>操作</td></tr>";
139             
140             /*2.6
141              * 循环后台回调的list对象数组中的数据,
142              * 并将数据取出拼接成tr行进行显示
143              * */
144             $.each(obj.list, function(i) {
145                 str += "<tr><td>" + obj.list[i].sid + "</td><td>"
146                         + obj.list[i].sname + "</td><td>" + obj.list[i].sex
147                         + "</td><td><a href='FindByIdSerlvet?sid="+obj.list[i].sid+"'>修改</a>&nbsp;&nbsp;<a href=''>删除</a></td></tr>";
148             });
149             
150             /*2.7 将拼接好的数据行放入table中*/
151             $("table").append(str);
152         },
153         error : function() {
154             alert("error");
155         }
156     });
157 }
ajaxindex.js

1.30 运行页面

 

转载于:https://www.cnblogs.com/holly8/p/5756284.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值