程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> Hibernate全套增刪改查+分頁,hibernate全套

Hibernate全套增刪改查+分頁,hibernate全套

編輯:JAVA綜合教程

Hibernate全套增刪改查+分頁,hibernate全套


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.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;
import com.util.Hibernate_Util;

public class FindByIdSerlvet 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.接受參數
        Integer sid=Integer.valueOf(request.getParameter("sid"));
        
        // 3.業務處理
        StudentService service = new StudentServiceImpl();
         
         Student stu=service.findById(sid);
         System.out.println("stu:"+stu);
         if(stu!=null){
             System.out.println("根據id查詢到對象");
             request.setAttribute("stu", stu);
             request.getRequestDispatcher("update.jsp").forward(request, response);
         }else{
             System.out.println("沒有根據id查詢到對象");
         }
    }
}
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 UpdateServlet 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.接受參數
        Integer sid=Integer.valueOf(request.getParameter("sid"));
        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(sid,sname, password, sex, cid);
        
        // 3.業務處理
        StudentService service = new StudentServiceImpl();
        int num=service.update(stu);
        if(num>0){
            System.out.println("update success!");
            response.sendRedirect("FindAllServlet");
        }else{
            System.out.println("update 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 DeleteSerlvet 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.接受參數
        Integer sid=Integer.valueOf(request.getParameter("sid"));
        // 3.業務處理
        StudentService service = new StudentServiceImpl();
        Student stu=service.findById(sid);
        if (stu != null) {
            System.out.println("根據id查詢成功");
             int num=service.delete(stu);
             if(num>0){
                 System.out.println("delete success!!");
                 // 4.頁面跳轉
                 response.sendRedirect("FindAllServlet");
                 
             }else{
                 System.out.println("delete success!!");
                 
             }
        } else {
            System.out.println("根據id查詢失敗!");
        }
    }
}

14.配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>FindAllServlet</servlet-name>
    <servlet-class>com.servlet.FindAllServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>FindByIdSerlvet</servlet-name>
    <servlet-class>com.servlet.FindByIdSerlvet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>UpdateServlet</servlet-name>
    <servlet-class>com.servlet.UpdateServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>DeleteSerlvet</servlet-name>
    <servlet-class>com.servlet.DeleteSerlvet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>RegisterServlet</servlet-name>
    <servlet-class>com.servlet.RegisterServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>FindPageServlet</servlet-name>
    <servlet-class>com.servlet.FindPageServlet</servlet-class>
  </servlet>



  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>FindAllServlet</servlet-name>
    <url-pattern>/FindAllServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>FindByIdSerlvet</servlet-name>
    <url-pattern>/FindByIdSerlvet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>UpdateServlet</servlet-name>
    <url-pattern>/UpdateServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>DeleteSerlvet</servlet-name>
    <url-pattern>/DeleteSerlvet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>RegisterServlet</servlet-name>
    <url-pattern>/RegisterServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>FindPageServlet</servlet-name>
    <url-pattern>/FindPageServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
</web-app>

15.首頁

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
    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>
        <h3>學生信息表</h3>
        <table border="2">
            <tr>
                <td>
                    序號
                </td>
                <td>
                    姓名
                </td>
                <td>
                    性別
                </td>
                <td align="center">
                    操作
                </td>
            </tr>
            
            <c:forEach var="i" items="${list}"  varStatus="f">
                <tr <c:if test="${f.index%2==0}"></c:if>>
                    <td>
                        ${i.sid }
                    </td>
                    <td>
                        ${i.sname }
                    </td>
                    <td>
                        ${i.sex }
                    </td>
                    <td>
                        <a href="register.jsp">添加</a>
                        &nbsp;&nbsp;
                        <a href="FindByIdSerlvet?sid=${i.sid}">修改</a>
                        &nbsp;&nbsp;
                        <a href="DeleteSerlvet?sid=${i.sid}">刪除</a>
                        
                    </td>
                </tr>
            </c:forEach>
            
        </table>
        <div>
        
        
        第${page.pageno}/${page.totalpage}頁 &nbsp;&nbsp;
        <a href="FindAllServlet?pageNo=1">首頁</a>
        <c:choose>
          <c:when test="${page.pageno gt 1}">
            <a href="FindAllServlet?pageNo=${page.pageno-1 }">上一頁</a>
          </c:when>
          <c:otherwise>
            <a href="javascript:alert('已經是第一頁了,沒有上一頁!');">上一頁</a>
          </c:otherwise>
        </c:choose>
        <c:choose>
          <c:when test="${page.pageno lt page.totalpage}">
            <a href="FindAllServlet?pageNo=${page.pageno+1 }">下一頁</a>
          </c:when>
          <c:otherwise>
            <a href="javascript:alert('已經是最有一頁了,沒有下一頁!');">下一頁</a>
          </c:otherwise>
        </c:choose>
        
        <a href="FindAllServlet?pageNo=${page.totalpage}">末頁</a>
        &nbsp;&nbsp;
        共${page.totalcount}條
        
        </div>
        
    </CENTER>
        
    </body>
</html>

16.登錄頁面

<%@ 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>
                    登錄
                </legend>
                <form action="LoginServlet" method="post">
                    <table>
                        <tr>
                            <td>
                                用戶名:
                            </td>
                            <td>
                                <input type="text" name="sname" />
                            </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>

17.注冊頁面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
    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> 
                    注冊 
                </legend>
                <form action="RegisterServlet" method="post">
                    <table>
                        <tr>
                            <td>
                                用戶名:
                            </td>
                            <td>
                                <input type="text" name="sname"/>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                密碼:
                            </td>
                            <td>
                                <input type="password" name="password"/>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                性別:
                            </td>
                            <td>
                                    <input type="radio" name="sex" value="男" checked="checked"/>男
                                    <input type="radio" name="sex" value="女"/>女
                            </td>
                        </tr>
                        <tr>
                            <td>
                                班級編號:
                            </td>
                            <td>
                                <select name="cid">
                                  <option value="1">TB07</option>
                                  <option value="2">TB13</option>
                                  <option value="3">TB24</option>
                                  <option value="4">TB31</option>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input type="submit" value="注冊" />
                            </td>
                            <td>
                                <input type="reset" value="重置" />
                            </td>
                        </tr>
                    </table>
                </form>
            </fieldset>
        </center>
    </body>
</html>

18.修改

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
    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>修改  
                </legend>
                <form action="UpdateServlet?sid=${stu.sid}" method="post">
                    <table>
                        <tr>
                            <td>
                                用戶名:
                            </td>
                            <td>
                                <input type="text" name="sname" value="${stu.sname}"/>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                密碼:
                            </td>
                            <td>
                                <input type="password" name="password" value="${stu.password}"/>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                性別:
                            </td>
                            <td>
                                <c:choose>
                                  <c:when test="${stu.sex eq '男'}">
                                    <input type="radio" name="sex" value="男" checked="checked"/>男
                                    <input type="radio" name="sex" value="女"/>女
                                  </c:when>
                                  <c:otherwise>
                                     <input type="radio" name="sex" value="男"/>男
                                    <input type="radio" name="sex" value="女" checked="checked"/>女
                                  </c:otherwise>
                                </c:choose>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                班級編號:
                            </td>
                            <td>
                                <select name="cid">
                                  <option value="1">TB07</option>
                                  <option value="2">TB13</option>
                                  <option value="3">TB24</option>
                                  <option value="4">TB31</option>
                                </select>
                            </td>
                        </tr>
                        
                        <tr>
                            <td>
                                <input type="submit" value="修改" />
                            </td>
                            <td>
                                <input type="reset" value="重置" />
                            </td>
                        </tr>
                    </table>
                </form>
            </fieldset>
        </center>
    </body>
</html>

部分截圖       2016-09-2415:21:19

注:希望各路大神多多指點!!!

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved