使用maven搭建Hibernate框架(web项目)
1 create table USERS 2 ( 3 ID NUMBER not null primary key, 4 NAME VARCHAR2(50), 5 PASSWORD VARCHAR2(50), 6 TELEPHONE VARCHAR2(15), 7 USERNAME VARCHAR2(50), 8 ISADMIN VARCHAR2(5) 9 ); 10 create table DISTRICT 11 ( 12 ID NUMBER not null primary key, 13 NAME VARCHAR2(50) not null 14 ); 15 create table HOUSE 16 ( 17 ID NUMBER, 18 USER_ID NUMBER, 19 TYPE_ID NUMBER, 20 TITLE NVARCHAR2(50), 21 DESCRIPTION NVARCHAR2(2000), 22 PRICE NUMBER, 23 PUBDATE DATE, 24 FLOORAGE NUMBER, 25 CONTACT VARCHAR2(100), 26 STREET_ID NUMBER 27 ); 28 29 create table STREET 30 ( 31 ID NUMBER not null primary key, 32 NAME VARCHAR2(50), 33 DISTRICT_ID NUMBER 34 ); 35 create table TYPE 36 ( 37 ID NUMBER not null primary key, 38 NAME VARCHAR2(12) not null 39 ); 40 --主外键关系 41 ALTER TABLE HOUSE ADD CONSTRAINT fk_HOUSE_STREET FOREIGN KEY(STREET_ID) REFERENCES STREET (ID); 42 ALTER TABLE HOUSE ADD CONSTRAINT fk_HOUSE_TYPE FOREIGN KEY(TYPE_ID) REFERENCES TYPE (ID); 43 ALTER TABLE HOUSE ADD CONSTRAINT fk_HOUSE_USERS FOREIGN KEY(USER_ID) REFERENCES USERS (ID) ; 44 ALTER TABLE STREET ADD CONSTRAINT fk_DISTRICT_STREET FOREIGN KEY(DISTRICT_ID) REFERENCES DISTRICT(ID); 45 --DISTRICT 46 insert into DISTRICT (ID, NAME) 47 values (1001, '东城'); 48 insert into DISTRICT (ID, NAME) 49 values (1002, '西城'); 50 insert into DISTRICT (ID, NAME) 51 values (1003, '石景山'); 52 insert into DISTRICT (ID, NAME) 53 values (1006, '朝阳'); 54 insert into DISTRICT (ID, NAME) 55 values (1000, '丰台'); 56 insert into DISTRICT (ID, NAME) 57 values (1004, '海淀'); 58 commit; 59 --STREET 60 insert into STREET (ID, NAME, DISTRICT_ID) 61 values (1000, '知春路', 1004); 62 insert into STREET (ID, NAME, DISTRICT_ID) 63 values (1001, '中关村大街', 1004); 64 insert into STREET (ID, NAME, DISTRICT_ID) 65 values (1002, '学院路', 1004); 66 insert into STREET (ID, NAME, DISTRICT_ID) 67 values (1003, '朝阳路', 1006); 68 commit; 69 --USERS 70 INSERT INTO USERS(ID,NAME,PASSWORD,TELEPHONE,USERNAME,ISADMIN) VALUES(1001,'zhangsan','1234','13267089839','张三','是'); 71 INSERT INTO USERS(ID,NAME,PASSWORD,TELEPHONE,USERNAME,ISADMIN) VALUES(1002,'lisi','1234','13267034439','李四','否'); 72 INSERT INTO USERS(ID,NAME,PASSWORD,TELEPHONE,USERNAME,ISADMIN) VALUES(1003,'wangxin','1234','13848879541','王鑫','是'); 73 INSERT INTO USERS(ID,NAME,PASSWORD,TELEPHONE,USERNAME,ISADMIN) VALUES(1004,'zhangjian','1234','13846972541','张建','否'); 74 INSERT INTO USERS(ID,NAME,PASSWORD,TELEPHONE,USERNAME,ISADMIN) VALUES(1005,'lijian','1234','13247965251','李健','是'); 75 INSERT INTO USERS(ID,NAME,PASSWORD,TELEPHONE,USERNAME,ISADMIN) VALUES(1006,'jiangyiran','1234','13445697214','蒋以然','否'); 76 INSERT INTO USERS(ID,NAME,PASSWORD,TELEPHONE,USERNAME,ISADMIN) VALUES(1007,'wangxiaochao','1234','13598248731','王晓超','否'); 77 INSERT INTO USERS(ID,NAME,PASSWORD,TELEPHONE,USERNAME,ISADMIN) VALUES(1008,'zhangdongxue','1234','13869732519','张冬雪','否'); 78 INSERT INTO USERS(ID,NAME,PASSWORD,TELEPHONE,USERNAME,ISADMIN) VALUES(1009,'sunpeng','1234','13299358331','孙鹏'); 79 INSERT INTO USERS(ID,NAME,PASSWORD,TELEPHONE,USERNAME,ISADMIN) VALUES(1010,'jianglianchang','1234','13846937982','蒋连昌','否'); 80 commit; 81 --TYPE 82 insert into TYPE (ID, NAME) 83 values (1000, '一室一厅'); 84 insert into TYPE (ID, NAME) 85 values (1001, '一室两厅'); 86 insert into TYPE (ID, NAME) 87 values (1002, '两室一厅'); 88 insert into TYPE (ID, NAME) 89 values (1003, '两室两厅'); 90 insert into TYPE (ID, NAME) 91 values (1004, '三室一厅'); 92 insert into TYPE (ID, NAME) 93 values (1005, '三室两厅'); 94 insert into TYPE (ID, NAME) 95 values (1006, '四室一厅'); 96 insert into TYPE (ID, NAME) 97 values (1007, '四室两厅'); 98 insert into TYPE (ID, NAME) 99 values (1008, '四十三厅'); 100 commit; 101 --HOUSE 102 INSERT INTO HOUSE(ID,USER_ID,TYPE_ID,TITLE,DESCRIPTION,PRICE,PUBDATE,FLOORAGE,CONTACT,STREET_ID) 103 VALUES(1,1001,1002,'中关村','中关村一条街',2600,to_date('2014-02-14','yyyy-mm-dd'),100,'张三',1000); 104 INSERT INTO HOUSE(ID,USER_ID,TYPE_ID,TITLE,DESCRIPTION,PRICE,PUBDATE,FLOORAGE,CONTACT,STREET_ID) 105 VALUES(2,1002,1003,'苏州街','苏州街一条街',3600,to_date('2009-1-3','yyyy-mm-dd'),100,'李四',1001); 106 INSERT INTO HOUSE(ID,USER_ID,TYPE_ID,TITLE,DESCRIPTION,PRICE,PUBDATE,FLOORAGE,CONTACT,STREET_ID) 107 VALUES(3,1003,1004,'万泉庄','万泉庄一条街',4600,to_date('2009-1-4','yyyy-mm-dd'),130,'王鑫',1002); 108 INSERT INTO HOUSE(ID,USER_ID,TYPE_ID,TITLE,DESCRIPTION,PRICE,PUBDATE,FLOORAGE,CONTACT,STREET_ID) 109 VALUES(1,1003,1002,'万泉庄附近','万泉庄附近一条街',1500,to_date('2009-7-2','yyyy-mm-dd'),125,'张建',1003); 110 INSERT INTO HOUSE(ID,USER_ID,TYPE_ID,TITLE,DESCRIPTION,PRICE,PUBDATE,FLOORAGE,CONTACT,STREET_ID) 111 VALUES(1,1005,1002,'东单','东单很多美食',2700,to_date('2009-9-2','yyyy-mm-dd'),140,'蒋以然',1001); 112 INSERT INTO HOUSE(ID,USER_ID,TYPE_ID,TITLE,DESCRIPTION,PRICE,PUBDATE,FLOORAGE,CONTACT,STREET_ID) 113 VALUES(3,1001,1002,'中关村','中关村电脑城',2600,to_date('2009-4-1','yyyy-mm-dd'),137,'王晓超',1003); 114 INSERT INTO HOUSE(ID,USER_ID,TYPE_ID,TITLE,DESCRIPTION,PRICE,PUBDATE,FLOORAGE,CONTACT,STREET_ID) 115 VALUES(4,1004,1001,'东四','东四一条街',2000,to_date('2009-4-2','yyyy-mm-dd'),200,'王晓超',1002); 116 INSERT INTO HOUSE(ID,USER_ID,TYPE_ID,TITLE,DESCRIPTION,PRICE,PUBDATE,FLOORAGE,CONTACT,STREET_ID) 117 VALUES(5,1006,1003,'西四','西四一条街',3600,to_date('2009-1-2','yyyy-mm-dd'),210,'张冬雪',1003); 118 INSERT INTO HOUSE(ID,USER_ID,TYPE_ID,TITLE,DESCRIPTION,PRICE,PUBDATE,FLOORAGE,CONTACT,STREET_ID) 119 VALUES(5,1007,1002,'西单','西单购物城',3600,to_date('2009-4-2','yyyy-mm-dd'),240,'孙鹏',1001); 120 INSERT INTO HOUSE(ID,USER_ID,TYPE_ID,TITLE,DESCRIPTION,PRICE,PUBDATE,FLOORAGE,CONTACT,STREET_ID) 121 VALUES(6,1002,1002,'苏州街','苏州街美食',2600,to_date('2009-2-2','yyyy-mm-dd'),260,'蒋连昌',1000); 122 commit;
第一步:打开idea
第二步:创建maven项目
第三步:创建项目名称
第四步:创建完成之后,选中src点击右键选择Directory创建java文件夹
第五步:选中java点击右键,选中 Mark Diectory as 选择Sources Root
第六步:选中main点击右键Directory创建resources文件夹
第七步:选中resources点击右键,选中 Mark Diectory as 选择Sources Root
第八步:点击 File — Project Structure —Facets,点击 "+" 选中hibernate
第九步:IDEA连接Oracle数据
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>com.bdqn</groupId> 8 <artifactId>Hid03</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 <packaging>war</packaging> 11 12 <name>Hid03 Maven Webapp</name> 13 <!-- FIXME change it to the project's website --> 14 <url>http://www.example.com</url> 15 16 <properties> 17 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 18 <maven.compiler.source>1.7</maven.compiler.source> 19 <maven.compiler.target>1.7</maven.compiler.target> 20 </properties> 21 22 <dependencies> 23 <dependency> 24 <groupId>junit</groupId> 25 <artifactId>junit</artifactId> 26 <version>4.11</version> 27 <scope>test</scope> 28 </dependency> 29 30 <dependency> 31 <groupId>org.hibernate</groupId> 32 <artifactId>hibernate-core</artifactId> 33 <version>4.0.0.Final</version> 34 </dependency> 35 36 <dependency> 37 <groupId>com.oracle</groupId> 38 <artifactId>ojdbc6</artifactId> 39 <version>10.2.0.1.0</version> 40 </dependency> 41 <dependency> 42 <groupId>javax.servlet</groupId> 43 <artifactId>jstl</artifactId> 44 <version>1.2</version> 45 </dependency> 46 47 <dependency> 48 <groupId>javax.servlet</groupId> 49 <artifactId>javax.servlet-api</artifactId> 50 <version>3.0.1</version> 51 <scope>provided</scope> 52 </dependency> 53 54 <dependency> 55 <groupId>com.fasterxml.jackson.core</groupId> 56 <artifactId>jackson-databind</artifactId> 57 <version>2.8.3</version> 58 </dependency> 59 <dependency> 60 <groupId>org.apache.taglibs</groupId> 61 <artifactId>taglibs-standard-impl</artifactId> 62 <version>1.2.5</version> 63 </dependency> 64 </dependencies> 65 66 67 </project>
1 <?xml version='1.0' encoding='utf-8'?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configuration DTD//EN" 4 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 5 <hibernate-configuration> 6 <session-factory> 7 <property name="connection.driver_class">oracle.jdbc.OracleDriver</property> <!--Oracle 数据驱动--> 8 <property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property> <!--数据库路径--> 9 <property name="connection.username">OT</property> 10 <property name="connection.password">1234</property> 11 <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property><!--数据库方言--> 12 <property name="show_sql">true</property><!--生成的sql语句--> 13 <property name="format_sql">true</property><!--sql格式化--> 14 <mapping resource="mapping/User.hbm.xml"/> 15 </session-factory> 16 </hibernate-configuration>
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.bdqn.entity.Users" table="Users"> 5 <id name="id" type="java.lang.Integer" column="id"> 6 <generator class="increment"/> 7 </id> 8 <property name="name" type="java.lang.String" column="NAME"/> 9 <property name="password" type="java.lang.String" column="PASSWORD"/> 10 <property name="telephone" type="java.lang.String" column="TELEPHONE"/> 11 <property name="username" type="java.lang.String" column="USERNAME"/> 12 <property name="isadmin" type="java.lang.String" column="ISADMIN"/> 13 14 </class> 15 </hibernate-mapping>
dao层
1 package com.bdqn.dao; 2 3 import com.bdqn.entity.Users; 4 import com.bdqn.page.Page; 5 import java.util.List; 6 7 public interface UserDao { 8 /** 9 * 1.根据用户名和密码查询 10 * 11 * @param sname 12 * @param password 13 * @return 14 */ 15 Users findByNameAndPwd(String sname, String password); 16 17 /** 18 * 2.延时加载:查询所有 19 * 20 * @return 21 */ 22 List<Users> findAll(); 23 24 /** 25 * 3.保存 26 * 27 * @param stu 28 * @return 29 */ 30 int save(Users stu); 31 32 /** 33 * 4.根据主键id查询单条 34 * 35 * @param sid 36 * @return 37 */ 38 Users findById(Integer sid); 39 40 /** 41 * 5.修改 42 */ 43 int update(Users stu); 44 45 /** 46 * 6.删除对象 47 * 48 * @param stu 49 * @return 50 */ 51 int delete(Users stu); 52 53 /** 54 * 7.分页查询 55 */ 56 List<Users> findPage(Page page); 57 58 /** 59 * 8.查询总条数 60 */ 61 int getTotalCount(); 62 }
1 package com.bdqn.dao.impl; 2 3 import com.bdqn.dao.UserDao; 4 import com.bdqn.entity.Users; 5 import com.bdqn.page.Page; 6 import com.bdqn.util.Hibernate_Util; 7 import org.hibernate.HibernateException; 8 import org.hibernate.Query; 9 import org.hibernate.Session; 10 import java.util.List; 11 12 public class UserDaoImpl implements UserDao { 13 /** 14 * 1.查询所有:立即加载 15 */ 16 public List<Users> findAll() { 17 //1.获取session对象 18 Session session = Hibernate_Util.getSession(); 19 //2.定义hql语句 20 String hql = "from Users"; 21 //3.Session创建Query对象 22 Query query = session.createQuery(hql); 23 //4.query对象执行操作 24 List<Users> it = query.list(); 25 //5.释放资源 26 Hibernate_Util.closeSession(); 27 return it; 28 } 29 30 /** 31 * 2.根据用户名和密码查询 32 */ 33 public Users findByNameAndPwd(String sname, String password) { 34 //1.获取session对象 35 Session session = Hibernate_Util.getSession(); 36 //2.定义hql语句(命名参数) 37 String hql = "from Users where name=:name and password=:password"; 38 //3.Session创建Query对象 39 Query query = session.createQuery(hql); 40 //4.query对象给占位符赋值 41 /*query.setString("sname", sname); 42 query.setString("password", password);*/ 43 query.setParameter("name", sname); 44 query.setParameter("password", password); 45 46 //query.setProperties(user); 47 //5.执行操作(uniqueResult()查询的单行数据) 48 Users stu = (Users) query.uniqueResult(); 49 //6.释放资源 50 Hibernate_Util.closeSession(); 51 return stu; 52 53 } 54 55 56 /** 57 * 根据id主键查询单条 58 */ 59 public Users findById(Integer sid) { 60 //1.获取session对象 61 Session session = Hibernate_Util.getSession(); 62 //2.利用session根据主键查询 63 Users stu = (Users) session.get(Users.class, sid); 64 /*3. 65 * 因为在修改时要提前查询单条,和session关联已经变成持久化对象, 66 * 而在修改时session执行update方法时, 67 * 首先会查询该主键id是否存在, 68 * 如果存在,则根据主键id修改该对象,此时对象已经处于持久化对象, 69 * 而实际session中不能同时存在两个主键id相同的对象, 70 * 否则会出现如下错误: 71 * org.hibernate.NonUniqueObjectException: 72 * a different object with the same identifier 73 * value was already associated with the 74 * session: [com.entity.Student#1] 75 */ 76 Hibernate_Util.closeSession(); 77 // session.clear(); 78 return stu; 79 } 80 81 /** 82 * 删除对象 83 */ 84 public int delete(Users 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 */ 108 public int save(Users stu) { 109 int num = 1; 110 //1.获取session对象 111 Session session = Hibernate_Util.getSession(); 112 //执行操作 113 try { 114 session.save(stu); 115 session.beginTransaction().commit(); 116 } catch (HibernateException e) { 117 num = 0; 118 e.printStackTrace(); 119 } finally { 120 //5.释放资源 121 Hibernate_Util.closeSession(); 122 } 123 return num; 124 } 125 126 /** 127 * 修改 128 */ 129 public int update(Users stu) { 130 int num = 1; 131 //1.获取session对象 132 Session session = Hibernate_Util.getSession(); 133 try { 134 //执行操作 135 //该对象的主键id必须存在 136 session.update(stu); 137 session.beginTransaction().commit(); 138 } catch (HibernateException e) { 139 num = 0; 140 e.printStackTrace(); 141 } finally { 142 //5.释放资源 143 Hibernate_Util.closeSession(); 144 } 145 return num; 146 } 147 148 /** 149 * 7.分页查询 150 */ 151 public List<Users> findPage(Page page) { 152 //1.获取session 153 Session session = Hibernate_Util.getSession(); 154 155 //2.定义查询最大记录数的hql 156 String hql = "from Users "; 157 158 //3.定义查询最大记录数的Query对象 159 Query querypage = session.createQuery(hql); 160 161 //4.查询最大记录数的数据 162 querypage.setMaxResults(page.getPagesize()); 163 164 //5.确定查询起点 165 querypage.setFirstResult(page.getStartrow()); 166 167 //6.分页查询 168 List<Users> list = querypage.list(); 169 170 //7.关闭session 171 Hibernate_Util.closeSession(); 172 173 return list; 174 } 175 176 /** 177 * 8.查询总条数 178 */ 179 public int getTotalCount() { 180 //1.获取session 181 Session session = Hibernate_Util.getSession(); 182 183 //2.定义查询总条数hql语句 184 String hqlcount = "select count(*) from Users "; 185 186 //3.利用Session创建Query对象 187 Query querycount = session.createQuery(hqlcount); 188 189 //4.获取总条数(返回单行数据uniqueResult()) 190 Integer totalCount = Integer.parseInt(querycount.uniqueResult().toString()); 191 //5.释放资源 192 Hibernate_Util.closeSession(); 193 return totalCount; 194 } 195 }
page层
1 package com.bdqn.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 14 public Page(Integer pageSize, Integer pageNo, Integer totalCount) { 15 this.pagesize = pageSize; //页面大小 16 this.pageno = pageNo; //当前页 17 this.totalcount = totalCount; //计算总条数 18 this.setStartrow(pageNo, pageSize); //计算起始行 19 this.setTotalpage(totalCount, pageSize); //计算总页数 20 } 21 22 public Integer getPagesize() { 23 return pagesize; 24 } 25 26 public void setPagesize(Integer pageSize) { 27 this.pagesize = pageSize; 28 } 29 30 public Integer getPageno() { 31 return pageno; 32 } 33 34 public void setPageno(Integer pageNo) { 35 this.pageno = pageNo; 36 } 37 38 public Integer getStartrow() { 39 return startrow; 40 } 41 42 /** 43 * 计算起始行 44 * 45 * @param pageNo 46 * @param pageSize 47 */ 48 public void setStartrow(Integer pageNo, Integer pageSize) { 49 this.startrow = (pageNo - 1) * pageSize; 50 } 51 52 public Integer getTotalpage() { 53 return totalpage; 54 } 55 56 /** 57 * 计算总页数 58 * 59 * @param totalCount 60 * @param pageSize 61 */ 62 public void setTotalpage(Integer totalCount, Integer pageSize) { 63 this.totalpage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1; 64 } 65 66 public Integer getTotalcount() { 67 return totalcount; 68 } 69 70 public void setTotalCount(Integer totalCount) { 71 this.totalcount = totalCount; 72 } 73 74 @Override 75 public String toString() { 76 return "[{\"pageno\":" + pageno + ",\"pagesize\":" + pagesize 77 + ",\"startrow\":" + startrow + ",\"totalcount\":" + totalcount 78 + ",\"totalpage\":" + totalpage + "}]"; 79 } 80 }
service层
1 package com.bdqn.service; 2 3 import com.bdqn.entity.Users; 4 import com.bdqn.page.Page; 5 6 import java.util.List; 7 8 public interface UserService { 9 /** 10 * 1.登录的业务 11 * 12 * @param sname 13 * @param password 14 * @return 15 */ 16 Users login(String sname, String password); 17 18 /** 19 * 2.注册 20 * 21 * @param stu 22 * @return 23 */ 24 int register(Users stu); 25 26 /** 27 * 3.查询所有 28 */ 29 List<Users> findAll(); 30 31 /** 32 * 4.根据主键id查询 33 * 34 * @param sid 35 * @return 36 */ 37 Users findById(Integer sid); 38 39 /** 40 * 5.修改 41 */ 42 int update(Users stu); 43 44 /** 45 * 6.删除 46 */ 47 int delete(Users stu); 48 49 /** 50 * 7.分页查询 51 */ 52 List<Users> findPage(Page page); 53 54 /** 55 * 8.查询总条数 56 */ 57 int getTotalCount(); 58 59 }
1 package com.bdqn.service.impl; 2 3 import com.bdqn.dao.UserDao; 4 import com.bdqn.dao.impl.UserDaoImpl; 5 import com.bdqn.entity.Users; 6 import com.bdqn.page.Page; 7 import com.bdqn.service.UserService; 8 9 import java.util.List; 10 11 public class UserServiceImpl implements UserService { 12 /** 13 * 使用多态引用数据访问层对象 14 */ 15 private UserDao dao = new UserDaoImpl(); 16 17 /** 18 * 登录 19 */ 20 public Users login(String sname, String password) { 21 return dao.findByNameAndPwd(sname, password); 22 } 23 24 public int delete(Users stu) { 25 // TODO Auto-generated method stub 26 return dao.delete(stu); 27 } 28 29 public List<Users> findAll() { 30 // TODO Auto-generated method stub 31 return dao.findAll(); 32 } 33 34 public Users findById(Integer sid) { 35 // TODO Auto-generated method stub 36 return dao.findById(sid); 37 } 38 39 public int register(Users stu) { 40 // TODO Auto-generated method stub 41 return dao.save(stu); 42 } 43 44 public int update(Users stu) { 45 // TODO Auto-generated method stub 46 return dao.update(stu); 47 } 48 49 public List<Users> findPage(Page page) { 50 // TODO Auto-generated method stub 51 return dao.findPage(page); 52 } 53 54 public int getTotalCount() { 55 // TODO Auto-generated method stub 56 return dao.getTotalCount(); 57 } 58 59 }
servlet层
实现删除功能
1 package com.bdqn.servlet; 2 3 import com.bdqn.entity.Users; 4 import com.bdqn.service.UserService; 5 import com.bdqn.service.impl.UserServiceImpl; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 import java.io.IOException; 12 13 public class DeleteSerlvet extends HttpServlet { 14 public void doGet(HttpServletRequest request, HttpServletResponse response) 15 throws ServletException, IOException { 16 17 this.doPost(request, response); 18 } 19 20 public void doPost(HttpServletRequest request, HttpServletResponse response) 21 throws ServletException, IOException { 22 request.setCharacterEncoding("UTF-8"); 23 response.setCharacterEncoding("UTF-8"); 24 response.setContentType("text/html;charset=UTF-8"); 25 26 // 2.接受参数 27 Integer sid=Integer.valueOf(request.getParameter("id")); 28 // 3.业务处理 29 UserService service = new UserServiceImpl(); 30 Users stu=service.findById(sid); 31 if (stu != null) { 32 System.out.println("根据id查询成功"); 33 int num=service.delete(stu); 34 if(num>0){ 35 System.out.println("delete success!!"); 36 // 4.页面跳转 37 response.sendRedirect("FindAllServlet"); 38 39 }else{ 40 System.out.println("delete success!!"); 41 42 } 43 } else { 44 System.out.println("根据id查询失败!"); 45 46 } 47 48 } 49 50 }
实现统计总记录数功能
1 package com.bdqn.servlet; 2 3 import com.bdqn.entity.Users; 4 import com.bdqn.page.Page; 5 import com.bdqn.service.UserService; 6 import com.bdqn.service.impl.UserServiceImpl; 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 import java.io.IOException; 13 import java.io.PrintWriter; 14 import java.util.List; 15 16 17 public class FindAllServlet extends HttpServlet { 18 public void doGet(HttpServletRequest request, HttpServletResponse response) 19 throws ServletException, IOException { 20 21 this.doPost(request, response); 22 } 23 24 25 public void doPost(HttpServletRequest request, HttpServletResponse response) 26 throws ServletException, IOException { 27 request.setCharacterEncoding("UTF-8"); 28 response.setCharacterEncoding("UTF-8"); 29 response.setContentType("text/html;charset=UTF-8"); 30 31 /** 32 * ☆ 33 * 在使用ajax往前台通过输出流对象的print方法发送json时 34 * 该行获取输出流对象的代码必须放在 35 * response.setContentType("text/html;charset=UTF-8"); 36 * 之后,否则ajax回调时,页面拿到的中文数据就永远都是乱码, 37 * 原因是:如果将改行代码写在处理客户端乱码之前,表示编码格式已经确定, 38 * 所以,编码格式的处理应该放在获取PrintWriter对象之前 39 * 40 */ 41 PrintWriter out = response.getWriter(); 42 43 44 // 2.接受参数 45 String no = request.getParameter("pageNo"); 46 47 48 // 3.业务处理 49 UserService service = new UserServiceImpl(); 50 51 int pageSize = 3; //页面大小 52 int pageNo = 1; //默认的pageNo为1 53 if (no != null && no != "") { 54 pageNo = Integer.valueOf(no); 55 } 56 //获取总条数 57 int totalCount = service.getTotalCount(); 58 Page page = new Page(pageSize, pageNo, totalCount); 59 60 List<Users> list = service.findPage(page); 61 if (list != null) { 62 System.out.println("find All page success"); 63 request.setAttribute("list", list); 64 request.setAttribute("page", page); 65 request.getRequestDispatcher("index.jsp").forward(request, response); 66 } else { 67 System.out.println("find All page fail!"); 68 69 70 } 71 72 } 73 }
实现根据条件查询功能
1 package com.bdqn.servlet; 2 3 import com.bdqn.entity.Users; 4 import com.bdqn.service.UserService; 5 import com.bdqn.service.impl.UserServiceImpl; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 import java.io.IOException; 12 13 14 public class FindByIdSerlvet extends HttpServlet { 15 public void doGet(HttpServletRequest request, HttpServletResponse response) 16 throws ServletException, IOException { 17 18 this.doPost(request, response); 19 } 20 21 public void doPost(HttpServletRequest request, HttpServletResponse response) 22 throws ServletException, IOException { 23 request.setCharacterEncoding("UTF-8"); 24 response.setCharacterEncoding("UTF-8"); 25 response.setContentType("text/html;charset=UTF-8"); 26 27 // 2.接受参数 28 Integer sid=Integer.valueOf(request.getParameter("id")); 29 30 // 3.业务处理 31 UserService service = new UserServiceImpl(); 32 33 Users stu=service.findById(sid); 34 System.out.println("stu:"+stu); 35 if(stu!=null){ 36 System.out.println("根据id查询到对象"); 37 request.setAttribute("stu", stu); 38 request.getRequestDispatcher("update.jsp").forward(request, response); 39 }else{ 40 System.out.println("没有根据id查询到对象"); 41 } 42 43 } 44 }
实现分页功能
1 package com.bdqn.servlet; 2 3 import com.bdqn.entity.Users; 4 import com.bdqn.page.Page; 5 import com.bdqn.service.UserService; 6 import com.bdqn.service.impl.UserServiceImpl; 7 import com.fasterxml.jackson.databind.ObjectMapper; 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 import java.io.IOException; 14 import java.io.PrintWriter; 15 import java.util.List; 16 17 18 public class FindPageServlet extends HttpServlet { 19 20 public void doGet(HttpServletRequest request, HttpServletResponse response) 21 throws ServletException, IOException { 22 23 this.doPost(request, response); 24 } 25 26 public void doPost(HttpServletRequest request, HttpServletResponse response) 27 throws ServletException, IOException { 28 response.setContentType("text/html;charset=UTF-8"); 29 request.setCharacterEncoding("UTF-8"); 30 response.setCharacterEncoding("UTF-8"); 31 /** 32 * ☆ 33 * 在使用ajax往前台通过输出流对象的print方法发送json时 34 * 该行获取输出流对象的代码必须放在 35 * response.setContentType("text/html;charset=UTF-8"); 36 * 之后,否则ajax回调时,页面拿到的中文数据就永远都是乱码, 37 * 原因是:如果将改行代码写在处理客户端乱码之前,表示编码格式已经确定, 38 * 所以,编码格式的处理应该放在获取PrintWriter对象之前 39 * 40 */ 41 PrintWriter out=response.getWriter(); 42 43 44 // 2.接受参数 45 String no=request.getParameter("pageNo"); 46 47 48 // 3.业务处理 49 UserService service = new UserServiceImpl(); 50 51 int pageSize=3; //页面大小 52 int pageNo=1; //默认的pageNo为1 53 if(no!=null && no!=""){ 54 pageNo=Integer.valueOf(no); 55 } 56 //获取总条数 57 int totalCount=service.getTotalCount(); 58 //封装分页所需字段 59 Page page=new Page(pageSize, pageNo, totalCount); 60 //分页查询 61 List<Users> list = service.findPage(page); 62 63 ObjectMapper om=new ObjectMapper(); 64 String str=om.writeValueAsString(list); 65 String pagestr=om.writeValueAsString(page); 66 str="{\"page\":"+pagestr+",\"list\":"+str+"}"; 67 System.out.println(str); 68 69 out.print(str); 70 71 72 } 73 }
实现登录功能
1 package com.bdqn.servlet; 2 3 import com.bdqn.entity.Users; 4 import com.bdqn.service.UserService; 5 import com.bdqn.service.impl.UserServiceImpl; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 import java.io.IOException; 12 13 public class LoginServlet extends HttpServlet { 14 public void doGet(HttpServletRequest request, HttpServletResponse response) 15 throws ServletException, IOException { 16 17 this.doPost(request, response); 18 } 19 20 21 public void doPost(HttpServletRequest request, HttpServletResponse response) 22 throws ServletException, IOException { 23 request.setCharacterEncoding("UTF-8"); 24 response.setCharacterEncoding("UTF-8"); 25 response.setContentType("text/html;charset=UTF-8"); 26 27 //2.接受参数 28 String name = request.getParameter("name"); 29 String password = request.getParameter("password"); 30 //3.业务处理 31 UserService service = new UserServiceImpl(); 32 Users stu = service.login(name, password); 33 if (stu != null) { 34 System.out.println("login success!"); 35 //4.页面跳转 36 request.getSession().setAttribute("name", name); 37 response.sendRedirect("FindAllServlet"); 38 } else { 39 System.out.println("login fail!"); 40 41 } 42 43 } 44 }
实现添加功能
1 package com.bdqn.servlet; 2 3 import com.bdqn.entity.Users; 4 import com.bdqn.service.UserService; 5 import com.bdqn.service.impl.UserServiceImpl; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 import java.io.IOException; 12 13 14 public class RegisterServlet extends HttpServlet { 15 public void doGet(HttpServletRequest request, HttpServletResponse response) 16 throws ServletException, IOException { 17 18 this.doPost(request, response); 19 } 20 21 public void doPost(HttpServletRequest request, HttpServletResponse response) 22 throws ServletException, IOException { 23 request.setCharacterEncoding("UTF-8"); 24 response.setCharacterEncoding("UTF-8"); 25 response.setContentType("text/html;charset=UTF-8"); 26 27 // 2.接受参数 28 29 String name = request.getParameter("name"); 30 String password = request.getParameter("password"); 31 String telephone = request.getParameter("telephone"); 32 String username = request.getParameter("username"); 33 String isadmin = request.getParameter("isadmin"); 34 35 Users stu = new Users(name, password, telephone, username,isadmin); 36 37 // 3.业务处理 38 UserService service = new UserServiceImpl(); 39 int num = service.register(stu); 40 if (num > 0) { 41 System.out.println("register success!"); 42 response.sendRedirect("FindAllServlet"); 43 } else { 44 System.out.println("register fail!"); 45 46 } 47 48 } 49 }
实现修改功能
1 package com.bdqn.servlet; 2 3 import com.bdqn.entity.Users; 4 import com.bdqn.service.UserService; 5 import com.bdqn.service.impl.UserServiceImpl; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 import java.io.IOException; 12 13 14 public class UpdateServlet extends HttpServlet { 15 public void doGet(HttpServletRequest request, HttpServletResponse response) 16 throws ServletException, IOException { 17 18 this.doPost(request, response); 19 } 20 21 public void doPost(HttpServletRequest request, HttpServletResponse response) 22 throws ServletException, IOException { 23 request.setCharacterEncoding("UTF-8"); 24 response.setCharacterEncoding("UTF-8"); 25 response.setContentType("text/html;charset=UTF-8"); 26 27 // 2.接受参数 28 Integer id = Integer.valueOf(request.getParameter("id")); 29 String name = request.getParameter("name"); 30 String password = request.getParameter("password"); 31 String telephone = request.getParameter("telephone"); 32 String username = request.getParameter("username"); 33 String isadmin = request.getParameter("isadmin"); 34 Users stu = new Users(id,name, password, telephone, username,isadmin); 35 36 // 3.业务处理 37 UserService service = new UserServiceImpl(); 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 }
Util层
Hibernate封装类
1 package com.bdqn.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 public class Hibernate_Util { 9 private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); 10 private static Configuration configuration = null; 11 private static SessionFactory sessionFactory = null; 12 13 static { 14 15 try { 16 configuration = new Configuration().configure("/hibernate.cfg.xml"); 17 sessionFactory = configuration.buildSessionFactory(); 18 } catch (HibernateException e) { 19 System.out.println("解析xml和创建Session工厂error"); 20 e.printStackTrace(); 21 } 22 23 } 24 25 public static Session getSession() { 26 Session session = threadLocal.get(); 27 if (session == null) { 28 session = sessionFactory.openSession(); 29 threadLocal.set(session); 30 } 31 return session; 32 } 33 34 public static void closeSession() { 35 Session session = threadLocal.get(); 36 if (session != null) { 37 threadLocal.set(null); 38 session.close(); 39 } 40 } 41 }
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>页 34 <a href="javascript:void(0);" class="apage">首页</a> 35 <a href="javascript:void(0);" class="apage">上一页</a> 36 <a href="javascript:void(0);" class="apage">下一页</a> 37 <a href="javascript:void(0);" class="apage">末页</a> 38 共<span id="totalCount"></span>条 39 </div> 40 41 </CENTER> 42 43 </body> 44 </html> 45 46 ajaxindex.jsp
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %> 2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 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 border="1px" width="60%"> 29 <tr> 30 <td colspan="6"> 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 <td> 48 姓名 49 </td> 50 <td> 51 操作 52 </td> 53 </tr> 54 55 <c:forEach var="i" items="${list}"> 56 <tr> 57 <td> 58 ${i.id } 59 </td> 60 <td> 61 ${i.name } 62 </td> 63 <td> 64 ${i.password } 65 </td> 66 <td> 67 ${i.telephone } 68 </td> 69 70 <td> 71 ${i.username } 72 </td> 73 <td> 74 <a href="FindByIdSerlvet?id=${i.id}">修改</a> 75 76 <a href="DeleteSerlvet?id=${i.id}">删除</a> 77 78 </td> 79 </tr> 80 </c:forEach> 81 82 </table> 83 <div> 84 85 86 第${page.pageno}/${page.totalpage}页 87 <a href="FindAllServlet?pageNo=1">首页</a> 88 <c:choose> 89 <c:when test="${page.pageno gt 1}"> 90 <a href="FindAllServlet?pageNo=${page.pageno-1 }">上一页</a> 91 </c:when> 92 <c:otherwise> 93 <a href="javascript:alert('已经是第一页了,没有上一页!');">上一页</a> 94 </c:otherwise> 95 </c:choose> 96 <c:choose> 97 <c:when test="${page.pageno lt page.totalpage}"> 98 <a href="FindAllServlet?pageNo=${page.pageno+1 }">下一页</a> 99 </c:when> 100 <c:otherwise> 101 <a href="javascript:alert('已经是最有一页了,没有下一页!');">下一页</a> 102 </c:otherwise> 103 </c:choose> 104 105 <a href="FindAllServlet?pageNo=${page.totalpage}">末页</a> 106 107 共${page.totalcount}条 108 109 </div> 110 111 </CENTER> 112 113 </body> 114 </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <center> <fieldset style="width: 300px;"> <legend> 登录 </legend> <form action="LoginServlet" method="post"> <table> <tr> <td> 用户名: </td> <td> <input type="text" name="name" /> </td> </tr> <tr> <td> 密码: </td> <td> <input type="password" name="password" /> </td> </tr> <tr> <td> <input type="submit" value="提交" /> </td> <td> <input type="reset" value="重置" /> </td> </tr> </table> </form> </fieldset> </center> </body> </html>
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="name"/> 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="text" name="telephone"/> 56 </td> 57 </tr> 58 <tr> 59 <td> 60 姓名: 61 </td> 62 <td> 63 <input type="text" name="username"/> 64 </td> 65 </tr> 66 <tr> 67 <td> 68 <input type="submit" value="修改"/> 69 </td> 70 <td> 71 <input type="reset" value="重置"/> 72 </td> 73 </tr> 74 </table> 75 </form> 76 </fieldset> 77 </center> 78 </body> 79 </html>
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?id=${stu.id}" method="post"> 32 <table border="1px" width="60%"> 33 <tr> 34 <td> 35 用户名: 36 </td> 37 <td> 38 <input type="text" name="name" value="${stu.name}"/> 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 <input type="text" name="telephone" value="${stu.telephone}"/> 55 </td> 56 </tr> 57 <tr> 58 <td> 59 姓名: 60 </td> 61 <td> 62 <input type="text" name="username" value="${stu.username}"/> 63 </td> 64 </tr> 65 66 <tr> 67 <td> 68 <input type="submit" value="修改" /> 69 </td> 70 <td> 71 <input type="reset" value="重置" /> 72 </td> 73 </tr> 74 </table> 75 </form> 76 </fieldset> 77 </center> 78 </body> 79 </html>