1.創建一個web工程 2.導入jar包 3.創建Student表 4.創建實體類 5.配置映射文件 6.配置主配置文件 7.創建一個工具類 8.創建分頁實體類 9.創建Dao類 10.實現Dao介面 11.創建業務層的介面 12.實現業務層介面 13.創建Servlet類 Servlet類里的增刪 ...
1.創建一個web工程
2.導入jar包
3.創建Student表
4.創建實體類
package com.entity;
public class Student {
private Integer sid;
private String sname;
private String password;
private String sex;
private Integer cid;
public Student() {
}
public Student(Integer sid, String sname, String password, String sex,
Integer cid) {
this.sid = sid;
this.sname = sname;
this.password = password;
this.sex = sex;
this.cid = cid;
}
public Student(String sname, String password, String sex,
Integer cid) {
this.sname = sname;
this.password = password;
this.sex = sex;
this.cid = cid;
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getCid() {
return cid;
}
public void setCid(Integer cid) {
this.cid = cid;
}
@Override
public String toString() {
return "Student [cid=" + cid + ", password=" + password + ", sex="
+ sex + ", sid=" + sid + ", sname=" + sname + "]";
}
}
5.配置映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<!--1.實體類的欄位和資料庫的欄位一一映射
name:實體類的全名
table:對應的資料庫表名,預設值為類名
-->
<class name="com.entity.Student" table="STUDENT">
<!--1.1主鍵配置
id:對應表中的主鍵
name:實體類中的屬性名
type:主鍵屬性的數據類型
column:屬性名對應表的欄位名,預設值為屬性名-->
<id name="sid" type="java.lang.Integer" column="SID">
<!--generator:為持久化實例產生一個唯一標識-->
<generator class="sequence">
<!--資料庫的序列名-->
<param name="sequence">SEQ_STUDENT</param>
</generator>
</id>
<!--1.2普通欄位配置-->
<property name="sname" type="java.lang.String" column="SNAME"/>
<property name="password" type="java.lang.String" column="PASSWORD"/>
<property name="sex" type="java.lang.String" column="SEX"/>
<property name="cid" type="java.lang.Integer" column="CID"/>
</class>
</hibernate-mapping>
6.配置主配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" >
<hibernate-configuration>
<!--通常一個session-factory節點代表一個資料庫-->
<session-factory>
<!--1.配置資料庫的驅動-->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<!--2.配置資料庫的url地址-->
<property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
<!--3,配置資料庫的username-->
<property name="connection.username">holly</property>
<!--4.配置資料庫的密碼-->
<property name="connection.password">sys</property>
<!--5.配置資料庫的方言-->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!--6.顯示sql語句-->
<property name="show_sql">true</property>
<!--7.sql語句格式化-->
<property name="format_sql">true</property>
<!--8.載入映射文件-->
<mapping resource="com/entity/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
7.創建一個工具類
package com.util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* Hibernate打開session和關閉session的工具包
* @author Holly
*
*/
public class Hibernate_Util {
private static ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
private static Configuration configuration=null;
private static SessionFactory sessionFactory=null;
static{
try {
configuration=new Configuration().configure("/hibernate.cfg.xml");
sessionFactory=configuration.buildSessionFactory();
} catch (HibernateException e) {
System.out.println("解析xml和創建Session工廠error");
e.printStackTrace();
}
}
public static Session getSession(){
Session session=threadLocal.get();
if(session==null){
session=sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
public static void closeSession(){
Session session=threadLocal.get();
if(session!=null){
threadLocal.set(null);
session.close();
}
}
}
8.創建分頁實體類
package com.page;
public class Page {
private Integer pagesize; //頁面大小
private Integer pageno; //當前頁
private Integer startrow; //起始行
private Integer totalpage; //總頁數
private Integer totalcount; //總條數
public Page() {
}
public Page(Integer pageSize, Integer pageNo, Integer totalCount) {
this.pagesize = pageSize; //頁面大小
this.pageno = pageNo; //當前頁
this.totalcount = totalCount; //計算總條數
this.setStartrow(pageNo, pageSize); //計算起始行
this.setTotalpage(totalCount, pageSize); //計算總頁數
}
public Integer getPagesize() {
return pagesize;
}
public void setPagesize(Integer pageSize) {
this.pagesize = pageSize;
}
public Integer getPageno() {
return pageno;
}
public void setPageno(Integer pageNo) {
this.pageno = pageNo;
}
public Integer getStartrow() {
return startrow;
}
/**
* 計算起始行
* @param pageNo
* @param pageSize
*/
public void setStartrow(Integer pageNo,Integer pageSize) {
this.startrow = (pageNo-1)*pageSize;
}
public Integer getTotalpage() {
return totalpage;
}
/**
* 計算總頁數
* @param totalCount
* @param pageSize
*/
public void setTotalpage(Integer totalCount,Integer pageSize) {
this.totalpage = totalCount%pageSize==0?totalCount/pageSize:totalCount/pageSize+1;
}
public Integer getTotalcount() {
return totalcount;
}
public void setTotalCount(Integer totalCount) {
this.totalcount = totalCount;
}
@Override
public String toString() {
return "[{\"pageno\":" + pageno + ",\"pagesize\":" + pagesize
+ ",\"startrow\":" + startrow + ",\"totalcount\":" + totalcount
+ ",\"totalpage\":" + totalpage + "}]";
}
}
9.創建Dao類
package com.dao;
import java.util.List;
import com.entity.Student;
import com.page.Page;
public interface StudentDao {
/**
* 1.根據用戶名和密碼查詢
* @param sname
* @param password
* @return
*/
Student findByNameAndPwd(String sname,String password);
/**
* 2.延時載入:查詢所有
* @return
*/
List<Student> findAll();
/**
* 3.保存
* @param stu
* @return
*/
int save(Student stu);
/**
* 4.根據主鍵id查詢單條
* @param sid
* @return
*/
Student findById(Integer sid);
/**
* 5.修改
*/
int update(Student stu);
/**
* 6.刪除對象
* @param stu
* @return
*/
int delete(Student stu);
/**
* 7.分頁查詢
*/
List<Student> findPage(Page page);
/**
* 8.查詢總條數
*/
int getTotalCount();
}
10.實現Dao介面
package com.dao.impl;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import com.dao.StudentDao;
import com.entity.Student;
import com.page.Page;
import com.util.Hibernate_Util;
public class StudentDaoImpl implements StudentDao{
/**
* 1.查詢所有:立即載入
*/
public List<Student> findAll() {
//1.獲取session對象
Session session=Hibernate_Util.getSession();
//2.定義hql語句
String hql="from Student";
//3.Session創建Query對象
Query query=session.createQuery(hql);
//4.query對象執行操作
List<Student> it=query.list();
//5.釋放資源
Hibernate_Util.closeSession();
return it;
}
/**
* 2.根據用戶名和密碼查詢
*/
public Student findByNameAndPwd(String sname, String password) {
//1.獲取session對象
Session session=Hibernate_Util.getSession();
//2.定義hql語句(命名參數)
String hql="from Student where sname=:sname and password=:password";
//3.Session創建Query對象
Query query=session.createQuery(hql);
//4.query對象給占位符賦值
/*query.setString("sname", sname);
query.setString("password", password);*/
query.setParameter("sname", sname);
query.setParameter("password", password);
// query.setProperties(user);
//5.執行操作(uniqueResult()查詢的單行數據)
Student stu=(Student) query.uniqueResult();
//6.釋放資源
Hibernate_Util.closeSession();
return stu;
}
/**
* 根據id主鍵查詢單條
*/
public Student findById(Integer sid) {
//1.獲取session對象
Session session=Hibernate_Util.getSession();
//2.利用session根據主鍵查詢
Student stu=(Student) session.get(Student.class, sid);
/*3.
* 因為在修改時要提前查詢單條,和session關聯已經變成持久化對象,
* 而在修改時session執行update方法時,
* 首先會查詢該主鍵id是否存在,
* 如果存在,則根據主鍵id修改該對象,此時對象已經處於持久化對象,
* 而實際session中不能同時存在兩個主鍵id相同的對象,
* 否則會出現如下錯誤:
* org.hibernate.NonUniqueObjectException:
* a different object with the same identifier
* value was already associated with the
* session: [com.entity.Student#1]
*/
Hibernate_Util.closeSession();
// session.clear();
return stu;
}
/**
* 刪除對象
*/
public int delete(Student stu) {
int num=1;
//1.獲取session對象
Session session=Hibernate_Util.getSession();
try {
//session刪除操作
session.delete(stu);
session.beginTransaction().commit();
} catch (HibernateException e) {
num=0;
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//5.釋放資源
Hibernate_Util.closeSession();
}
return num;
}
/**
* 添加
*/
public int save(Student stu) {
int num=1;
//1.獲取session對象
Session session=Hibernate_Util.getSession();
//執行操作
try {
session.save(stu);
session.beginTransaction().commit();
} catch (HibernateException e) {
num=0;
e.printStackTrace();
}finally{
//5.釋放資源
Hibernate_Util.closeSession();
}
return num;
}
/**
* 修改
*/
public int update(Student stu) {
int num=1;
//1.獲取session對象
Session session=Hibernate_Util.getSession();
try {
//執行操作
//該對象的主鍵id必須存在
session.update(stu);
session.beginTransaction().commit();
} catch (HibernateException e) {
num=0;
e.printStackTrace();
}finally{
//5.釋放資源
Hibernate_Util.closeSession();
}
return num;
}
/**
* 7.分頁查詢
*/
public List<Student> findPage(Page page) {
//1.獲取session
Session session=Hibernate_Util.getSession();
//2.定義查詢最大記錄數的hql
String hql="from Student";
//3.定義查詢最大記錄數的Query對象
Query querypage=session.createQuery(hql);
//4.查詢最大記錄數的數據
querypage.setMaxResults(page.getPagesize());
//5.確定查詢起點
querypage.setFirstResult(page.getStartrow());
//6.分頁查詢
List<Student> list=querypage.list();
//7.關閉session
Hibernate_Util.closeSession();
return list;
}
/**
* 8.查詢總條數
*/
public int getTotalCount() {
//1.獲取session
Session session=Hibernate_Util.getSession();
//2.定義查詢總條數hql語句
String hqlcount="select count(*) from Student";
//3.利用Session創建Query對象
Query querycount=session.createQuery(hqlcount);
//4.獲取總條數(返回單行數據uniqueResult())
Integer totalCount=Integer.parseInt(querycount.uniqueResult().toString());
//5.釋放資源
Hibernate_Util.closeSession();
return totalCount;
}
}
11.創建業務層的介面
package com.service;
import java.util.List;
import com.entity.Student;
import com.page.Page;
/**
* 業務介面
* @author pc
*
*/
public interface StudentService {
/**
* 1.登錄的業務
* @param sname
* @param password
* @return
*/
Student login(String sname,String password);
/**
* 2.註冊
* @param stu
* @return
*/
int register(Student stu);
/**
* 3.查詢所有
*/
List<Student> findAll();
/**
* 4.根據主鍵id查詢
* @param sid
* @return
*/
Student findById(Integer sid);
/**
* 5.修改
*/
int update(Student stu);
/**
* 6.刪除
*/
int delete(Student stu);
/**
* 7.分頁查詢
*/
List<Student> findPage(Page page);
/**
* 8.查詢總條數
*/
int getTotalCount();
}
12.實現業務層介面
package com.service.impl;
import java.util.List;
import com.dao.StudentDao;
import com.dao.impl.StudentDaoImpl;
import com.entity.Student;
import com.page.Page;
import com.service.StudentService;
public class StudentServiceImpl implements StudentService {
/**
* 使用多態引用數據訪問層對象
*/
private StudentDao dao = new StudentDaoImpl();
/**
* 登錄
*/
public Student login(String sname, String password) {
return dao.findByNameAndPwd(sname, password);
}
public int delete(Student stu) {
// TODO Auto-generated method stub
return dao.delete(stu);
}
public List<Student> findAll() {
// TODO Auto-generated method stub
return dao.findAll();
}
public Student findById(Integer sid) {
// TODO Auto-generated method stub
return dao.findById(sid);
}
public int register(Student stu) {
// TODO Auto-generated method stub
return dao.save(stu);
}
public int update(Student stu) {
// TODO Auto-generated method stub
return dao.update(stu);
}
public List<Student> findPage(Page page) {
// TODO Auto-generated method stub
return dao.findPage(page);
}
public int getTotalCount() {
// TODO Auto-generated method stub
return dao.getTotalCount();
}
}
13.創建Servlet類
Servlet類里的增刪改查我是分開寫的,所以就不一一粘貼代碼,這裡只粘貼部分
package com.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.entity.Student;
import com.service.StudentService;
import com.service.impl.StudentServiceImpl;
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
// 2.接受參數
String sname = request.getParameter("sname");
String password = request.getParameter("password");
String sex = request.getParameter("sex");
Integer cid = Integer.valueOf(request.getParameter("cid"));
Student stu = new Student(sname, password, sex, cid);
// 3.業務處理
StudentService service = new StudentServiceImpl();
int num = service.register(stu);
if (num > 0) {
System.out.println("register success!");
response.sendRedirect("FindAllServlet");
} else {
System.out.println("register fail!");
}
}
}
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
import com.entity.Student;
import com.page.Page;
import com.service.StudentService;
import com.service.impl.StudentServiceImpl;
/**
* 分頁查詢
*
* @author pc
*
*/
public class FindPageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
/**
* ☆
* 在使用ajax往前臺通過輸出流對象的print方法發送json時
* 該行獲取輸出流對象的代碼必須放在
* response.setContentType("text/html;charset=UTF-8");
* 之後,否則ajax回調時,頁面拿到的中文數據就永遠都是亂碼,
* 原因是:如果將改行代碼寫在處理客戶端亂碼之前,表示編碼格式已經確定,
* 所以,編碼格式的處理應該放在獲取PrintWriter對象之前
*
*/
PrintWriter out=response.getWriter();
// 2.接受參數
String no=request.getParameter("pageNo");
// 3.業務處理
StudentService service = new StudentServiceImpl();
int pageSize=3; //頁面大小
int pageNo=1; //預設的pageNo為1
if(no!=null && no!=""){
pageNo=Integer.valueOf(no);
}
//獲取總條數
int totalCount=service.getTotalCount();
//封裝分頁所需欄位
Page page=new Page(pageSize, pageNo, totalCount);
//分頁查詢
List<Student> list = service.findPage(page);
ObjectMapper om=new ObjectMapper();
String str=om.writeValueAsString(list);
String pagestr=om.writeValueAsString(page);
str="{\"page\":"+pagestr+",\"list\":"+str+"}";
System.out.println(str);
out.print(str);
/*if (list != null) {
System.out.println("find page success");
request.setAttribute("list", list);
request.setAttribute("page", page);
request.getRequestDispatcher("index.jsp").forward(request, response);
} else {
System.out.println("find page fail!");
}*/
}
}
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.entity.Student;
import com.page.Page;
import com.service.StudentService;
import com.service.impl.StudentServiceImpl;
public class FindAllServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
/**
* ☆
* 在使用ajax往前臺通過輸出流對象的print方法發送json時
* 該行獲取輸出流對象的代碼必須放在
* response.setContentType("text/html;charset=UTF-8");
* 之後,否則ajax回調時,頁面拿到的中文數據就永遠都是亂碼,
* 原因是:如果將改行代碼寫在處理客戶端亂碼之前,表示編碼格式已經確定,
* 所以,編碼格式的處理應該放在獲取PrintWriter對象之前
*
*/
// 2.接受參數
String no=request.getParameter("pageNo");
// 3.業務處理
StudentService service = new StudentServiceImpl();
int pageSize=3; //頁面大小
int pageNo=1; //預設的pageNo為1
if(no!=null && no!=""){
pageNo=Integer.valueOf(no);
}
//獲取總條數
int totalCount=service.getTotalCount();
Page page=new Page(pageSize, pageNo, totalCount);
List<Student> list = service.findPage(page);
if(list!=null){
System.out.println("find All page success");
request.setAttribute("list", list);
request.setAttribute("page", page);
request.getRequestDispatcher("index.jsp").forward(request, response);
}else{
System.out.println("find All page fail!");
}
}
}
代碼
package com.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.entity.Student;
import com.service.StudentService;
import com.service.impl.StudentServiceImpl;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//2.接受參數
String sname=request.getParameter("sname");
String password=request.getParameter("password");
//3.業務處理
StudentService service=new StudentServiceImpl();
Student stu=service.login(sname, password);
if(stu!=null){
System.out.println("login success!");
//4.頁面跳轉
request.getSession().setAttribute("sname", sname);
response.sendRedirect("FindAllServlet");
}else{
System.out.println("login fail!");
}
}
}
package com.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ht