1. 程式人生 > >Hibernate+SpringMVC+Spring+分頁實現留言管理專案

Hibernate+SpringMVC+Spring+分頁實現留言管理專案

專案結構:
這裡使用到了Mysql資料庫
這裡寫圖片描述
所用到的包:略。

首先進行springmvc.xml的配置,注意資料庫密碼要改為自己的。

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop
="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "
>
<!-- 元件掃描Handler(Controller) 可以掃描controller,service--> <context:component-scan base-package="com.controller"></context:component-scan> <context:component-scan base-package="com.service"></context:component-scan> <context:component-scan
base-package="com.po">
</context:component-scan> <context:component-scan base-package="com.dao"></context:component-scan> <!-- 配置資料庫連線 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/message?characterEncoding=utf-8"></property> <property name="username" value="root"></property> <property name="password" value="@)!$"></property> </bean> <!-- 配置hibernate相關資訊--> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> <!--以下列表寫入實體類 --> <property name="packagesToScan"> <list> <value>com.po</value> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 使用annotation定義事務 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>

配置spring-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
        <context:annotation-config/>
        <!-- 把標記了@Controller註解 的類轉換為bean -->
        <context:component-scan base-package="com.controller"></context:component-scan>
        <!-- 啟動SpringMvc的註解功能,完成請求和註解POJO的對映 -->
        <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean>
        <!-- 對檢視名稱的解析,即在模型檢視名稱新增前後綴 -->
        <bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 配置jsp路徑的字首 -->
        <property name="prefix" value="/WEB-INF/views/"/>
        <!-- 配置jsp路徑的字尾 -->
        <property name="suffix" value=".jsp"/>
        </bean>

</beans>

在web.xml中配置spring容器和servlet

<?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">
 <display-name>s3h3</display-name>   
  <!-- 配置Spring容器 -->
  <context-param>     
     <param-name>contextConfigLocation</param-name>     
     <param-value>classpath:com/springmvc/springmvc.xml</param-value>  
 </context-param> 
   <!-- 監聽器的配置 -->  
   <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>     
  <!-- 配置Servlet -->
 <servlet>     
     <servlet-name>spring</servlet-name>     
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
     <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:com/spring/spring-servlet.xml</param-value>
     </init-param>    
     <load-on-startup>1</load-on-startup>     
 </servlet>     

 <servlet-mapping>    
     <!-- 這裡在配成spring,下邊也要寫一個名為spring-servlet.xml的檔案,主要用來配置它的controller -->    
     <servlet-name>spring</servlet-name> 
     <url-pattern>*.action</url-pattern>     
 </servlet-mapping>     

<!-- post亂碼過慮器 -->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

  <welcome-file-list>
    <welcome-file>message.action</welcome-file>
  </welcome-file-list>
</web-app>

實體類StudentMessage:這裡實現了Hibernate的類對映到表。需要匯入相應的包。

package com.po;
import java.io.Serializable;
import javax.persistence.Basic; 
import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.GenerationType; 
import javax.persistence.Id; 
import javax.persistence.Table; 
@Entity
@Table(name="studentmessages")
public class StudentMessage implements Serializable {

    private static final long serialVersionUID = 1L;
    private int id;
    private String title;
    private String content;
    private String name;
    private String phone;
    @Id
    @Basic(optional=false)
    @Column(name="Id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    @Column(name="Title")
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
    @Column(name="Content")
    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
    @Column(name="Name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    @Column(name="Phone")
    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

Page類:用於實現分頁查詢


package com.po;
import java.util.List;

public class Page {
    // 結果集
    private List<StudentMessage> list;

    // 查詢記錄總數
    private int totalRecords;

    // 每頁多少條記錄
    private int pageSize;

    // 第幾頁
    private int pageNo;

    /**
     * @return 總頁數
     * */
    public int getTotalPages(){
        return (totalRecords+pageSize-1)/pageSize;
    }

    /**
     * 計算當前頁開始記錄
     * @param pageSize 每頁記錄數
     * @param currentPage 當前第幾頁
     * @return 當前頁開始記錄號
     */
    public int countOffset(int currentPage,int pageSize){
        int offset = pageSize*(currentPage-1);
        return offset;
    }

    /**
     * @return 首頁
     * */
    public int getTopPageNo(){
        return 1;
    }

    /**
     * @return 上一頁
     * */
    public int getPreviousPageNo(){
        if(pageNo<=1){
            return 1;
        }
        return pageNo-1;
    }

    /**
     * @return 下一頁
     * */
    public int getNextPageNo(){
        if(pageNo>=getBottomPageNo()){
            return getBottomPageNo();
        }
        return pageNo+1;
    }

    /**
     * @return 尾頁
     * */
    public int getBottomPageNo(){
        return getTotalPages();
    }


    public List<StudentMessage> getList() {
        return list;
    }

    public void setList(List<StudentMessage> list) {
        this.list = list;
    }

    public int getTotalRecords() {
        return totalRecords;
    }

    public void setTotalRecords(int totalRecords) {
        this.totalRecords = totalRecords;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getPageNo() {
        return pageNo;
    }

    public void setPageNo(int pageNo) {
        this.pageNo = pageNo;
    }

}

DAO層程式碼實現:

package com.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.po.StudentMessage;
//採用註解寫,在配置檔案中不用再寫Dao層的bean
@Repository("studentMessageDao")

public class StudentMessageDao{
 @Autowired
    private SessionFactory sessionFactory;
    /**
  * 分頁查詢
  * @param hql 查詢的條件
  * @param offset 開始記錄
  * @param length 一次查詢幾條記錄
  * @return 返回查詢記錄集合
  */
@SuppressWarnings("unchecked")
     public List<StudentMessage> queryForPage(int offset, int length) {
       //查詢所有的記錄數
       Query query= (Query) sessionFactory.getCurrentSession().createQuery("from StudentMessage");    
        query.setFirstResult(offset);
        query.setMaxResults(length);            
        return query.list(); 
       }

     public void save(StudentMessage st){
     sessionFactory.getCurrentSession().save(st);
       }
     public void update(StudentMessage st) {   
            sessionFactory.getCurrentSession().update(st);
       }
     public void delete(StudentMessage st) {      
            sessionFactory.getCurrentSession().delete(st);
       }
     //查詢記錄總數
     public int getAllRowCount(){
         int count=((Long) sessionFactory.getCurrentSession()
                .createQuery( "select count(*) from StudentMessage").iterate().next()).intValue();
         return count;  
     }
     //根據id查詢記錄
    public  StudentMessage QueryById(int id) {
        StudentMessage st =(StudentMessage) sessionFactory.getCurrentSession().get(StudentMessage.class, id);
       return st;
     }
}

Service層呼叫相應的方法:

 package com.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.dao.StudentMessageDao;
import com.po.Page;
import com.po.StudentMessage;
@Repository("studentMessageService")
@Transactional
public class StudentMessageService {
        @Autowired
        public StudentMessageDao studentMessagedao;
        /**
         * 分頁查詢 
         * @param currentPage 當前頁號:現在顯示的頁數
         * @param pageSize 每頁顯示的記錄條數
         * @return 封閉了分頁資訊(包括記錄集list)的Bean
         * */
        public Page queryForPage(int currentPage,int pageSize) {
            Page page = new Page();       
            //總記錄數
            int allRow = studentMessagedao.getAllRowCount();
            //當前頁開始記錄
            int offset = page.countOffset(currentPage,pageSize);  
            //分頁查詢結果集
            List<StudentMessage> list = studentMessagedao.queryForPage(offset, pageSize); 
            page.setPageNo(currentPage);
            page.setPageSize(pageSize);
            page.setTotalRecords(allRow);
            page.setList(list);    
            return page;
        }
         public void Servicesave(StudentMessage st){
             studentMessagedao.save(st);
         }
        public void Serviceupdate(StudentMessage st){
            studentMessagedao.update(st);
        }
        public void Servicedelete(StudentMessage st){
            studentMessagedao.delete(st);
        }
        public int ServicegetCount(){
            return studentMessagedao.getAllRowCount();
        }
        public  StudentMessage QueryById(int id){
            return studentMessagedao.QueryById(id);
        }

}

Controller層實現:

package com.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.po.Page;
import com.po.StudentMessage;
import com.service.StudentMessageService;
@Controller
@RequestMapping("/message.action")
public class StudentMessageController {

@Autowired
public StudentMessageService studentMessageService;
public StudentMessageController(){}
protected final transient Log log = LogFactory.getLog(StudentMessageController.class);

@RequestMapping
//找到所有的記錄並實現了分頁
public String findAll(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap) {   
        String pageNo = request.getParameter("pageNo");
        if (pageNo == null) {
            pageNo = "1";
        }
        Page page = studentMessageService.queryForPage(Integer.valueOf(pageNo), 5);
        request.setAttribute("page", page);
        List<StudentMessage> list = page.getList();
        modelMap.put("list", list);
    return "message";
}

//新增留言資訊
@RequestMapping(params = "method=add")
public String add(HttpServletRequest request, ModelMap modelMap) throws Exception{
    return "student_add";
}
//儲存留言資訊
@RequestMapping(params = "method=save")
public String save(HttpServletRequest request, ModelMap modelMap){
    StudentMessage st = new StudentMessage();
    String name = request.getParameter("name");
    String title=request.getParameter("title"); 
    String phone=request.getParameter("phone");
    String content=request.getParameter("content");
    st.setName(name);
    st.setPhone(phone);
    st.setTitle(title);
    st.setContent(content);
    try{
        studentMessageService.Servicesave(st);
        modelMap.put("addstate", "新增成功");
    }
    catch(Exception e){
        e.printStackTrace();
        log.error(e.getMessage());
        modelMap.put("addstate", "新增失敗");
    }       
    return "student_add";
}
//刪除留言資訊
@RequestMapping(params = "method=del")
public String del(@RequestParam("id") String id) throws Exception{
    StudentMessage st=new StudentMessage();
    st.setId(Integer.valueOf(id));
    studentMessageService.Servicedelete(st);
    return "success";
}

//修改留言資訊獲得原來的留言資訊並跳轉頁面
@RequestMapping(params = "method=edit")
public ModelAndView edit(@RequestParam("id") String id,HttpServletRequest request) throws Exception{
         ModelAndView modelAndView =  new ModelAndView();
         int idd=Integer.valueOf(id);
         StudentMessage st=studentMessageService.QueryById(idd);
         String name=st.getName();
         String phone=st.getPhone();
         String content=st.getContent();
         String title=st.getTitle();
         request.setAttribute("id", id);
         request.setAttribute("name", name);
         request.setAttribute("phone", phone);
         request.setAttribute("content", content);
         request.setAttribute("title", title);
         modelAndView.setViewName("/edit");
         return modelAndView;
}
//修改留言資訊確認提交
@RequestMapping(params = "method=editsubmit")
public String editsubmit(HttpServletRequest request) throws Exception{
     String name=request.getParameter("name");
     String phone=request.getParameter("phone");
     String title=request.getParameter("title");
     String content=request.getParameter("content");
     String id=request.getParameter("id");
     StudentMessage st=new StudentMessage();
     st.setId(Integer.valueOf(id));
     st.setName(name);
     st.setPhone(phone);
     st.setTitle(title);
     st.setContent(content);
     studentMessageService.Serviceupdate(st);
     return "success";
}
}

JSP頁面實現:
顯示資料頁面:message.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"  
    pageEncoding="UTF-8"%>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>操作</title> 
<style>
table{  border-collapse:collapse;  }   
td{  border:2px solid blue;  }   
</style>  
<script type="text/javascript">
function add(){   
     window.location.href="<%=request.getContextPath() %>/message.action?method=add";   
}   
function del(id){  
     window.location.href="<%=request.getContextPath()%>/message.action?method=del&id=" + id;  
}   
function edit(id){  
     url="<%=request.getContextPath()%>/message.action?method=edit&id=" + id;
     window.location.href=url;
} 
</script> 
</head>  
<body>  
<center>
<h1>留言資訊列表</h1>
<form name="form">
  <table > 
    <tr>  
        <td>Id</td>  
        <td>Name</td>  
        <td>Title</td>  
        <td>phone</td> 
        <td>content</td> 
        <td>do</td>
    </tr>  
    <c:forEach items="${list }" var="studentMessage" varStatus="status">  
    <tr id="<c:out  value="${studentMessage.id}"/>"> 
        <td><input  value="${studentMessage.id}" readonly="readonly"/></td>  
        <td><input  name="list[${status.index}].name"      value="${studentMessage.name}"    readonly="readonly"/></td>  
        <td><input  name="list[${status.index}].title"     value="${studentMessage.title}"   readonly="readonly"/></td>  
        <td><input  name="list[${status.index}].phone"     value="${studentMessage.phone}"   readonly="readonly"/></td>
        <td><input  name="list[${status.index}].content"   value="${studentMessage.content}" readonly="readonly"/></td>
        <td> 
            <input type="button" onclick="edit('<c:out value="${studentMessage.id}"/>')" value="修改"/>        
            <input type="button" onclick="del('<c:out value="${studentMessage.id}"/>')" value="刪除"/>  
        </td>        
    </tr> 
    </c:forEach>  
 </table>
</form>
   <br>
   <table>
       <tr>
            <td colspan="6" align="center" bgcolor="#5BA8DE">共${page.totalRecords}條記錄 共${page.totalPages}頁 當前第${page.pageNo}頁<br>            
                <a href="<%=request.getContextPath()%>/message.action?pageNo=${page.topPageNo}"><input type="button" name="fristPage" value="首頁" /></a>
                <c:choose>
                  <c:when test="${page.pageNo!=1}">             
                      <a href="<%=request.getContextPath()%>/message.action?pageNo=${page.previousPageNo }"><input type="button" name="previousPage" value="上一頁" /></a>                
                  </c:when>
                  <c:otherwise>   
                      <input type="button" disabled="disabled" name="previousPage" value="上一頁" />       
                  </c:otherwise>
                </c:choose>
                <c:choose>
                  <c:when test="${page.pageNo != page.totalPages}">
                    <a href="<%=request.getContextPath()%>/message.action?pageNo=${page.nextPageNo }"><input type="button" name="nextPage" value="下一頁" /></a>
                  </c:when>
                  <c:otherwise>    
                      <input type="button" disabled="disabled" name="nextPage" value="下一頁" />
                  </c:otherwise>
                </c:choose>
                <a href="<%=request.getContextPath()%>/message.action?pageNo=${page.bottomPageNo}"><input type="button" name="lastPage" value="尾頁" /></a>
            </td>
        </tr>
     </table>
        <br>
        新增記錄:<input id="add" type="button" onclick="add()" value="新增"/> 
</center> 
</body>  
</html>  

修改資料頁面:edit.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
<style>
table{  border-collapse:collapse;  }   
td{  border:2px solid blue;  }   

</style>  
  </head>
  <