Hibernate+SpringMVC+Spring+分页实现留言管理项目

项目结构:
这里使用到了Mysql数据库
Hibernate+SpringMVC+Spring+分页实现留言管理项目_第1张图片
所用到的包:略。

首先进行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 ">

        
        <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>

        
       <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.MySQLDialectprop>  
                <prop key="hibernate.show_sql">trueprop>  
            props>  
        property> 
        
        <property name="packagesToScan">
        <list>
        <value>com.povalue>
        list>
        property> 
        bean> 

         <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
        <property name="sessionFactory" ref="sessionFactory"/>  
        bean>  
          
         <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/>
        
        <context:component-scan base-package="com.controller">context:component-scan>
        
        <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">bean>
        
        <bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        
        <property name="prefix" value="/WEB-INF/views/"/>
        
        <property name="suffix" value=".jsp"/>
        bean>

beans>

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


<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>s3h3display-name>   
  
  <context-param>     
     <param-name>contextConfigLocationparam-name>     
     <param-value>classpath:com/springmvc/springmvc.xmlparam-value>  
 context-param> 
     
   <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>     
  
 <servlet>     
     <servlet-name>springservlet-name>     
     <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class> 
     <init-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:com/spring/spring-servlet.xmlparam-value>
     init-param>    
     <load-on-startup>1load-on-startup>     
 servlet>     

 <servlet-mapping>    
         
     <servlet-name>springservlet-name> 
     <url-pattern>*.actionurl-pattern>     
 servlet-mapping>     


    <filter>
        <filter-name>CharacterEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>utf-8param-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

  <welcome-file-list>
    <welcome-file>message.actionwelcome-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 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 getList() {
        return list;
    }

    public void setList(List 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 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 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 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" %>  
  
<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>Idtd>  
        <td>Nametd>  
        <td>Titletd>  
        <td>phonetd> 
        <td>contenttd> 
        <td>dotd>
    tr>  
    <c:forEach items="${list }" var="studentMessage" varStatus="status">  
    <tr id="${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('${studentMessage.id}"/>')" value="修改"/>        
            <input type="button" onclick="del('${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"%> 



<html>
  <head>
<style>
table{  border-collapse:collapse;  }   
td{  border:2px solid blue;  }   

style>  
  head>
  <body>
  <center>
  <form action="<%=request.getContextPath() %>/message.action?method=editsubmit" method="post">
  <h1>留言修改h1>
  <table>
    <tr>  
        <td>Idtd>  
        <td>Nametd>  
        <td>Titletd>  
        <td>phonetd> 
        <td>contenttd> 

    tr> 
    <tr> 
        <td><input  name="id"        value="<% out.print(request.getAttribute("id"));%>" readonly="readonly"/>td>  
        <td><input  name="name"      value="<% out.print(request.getAttribute("name"));%>"/>td>  
        <td><input  name="title"     value="<% out.print(request.getAttribute("title"));%>"/>td>  
        <td><input  name="phone"     value="<% out.print(request.getAttribute("phone"));%>"/>td>
        <td><input  name="content"   value="<% out.print(request.getAttribute("content"));%>"/>td>

    tr> 
    table>
    <br>
     <input type="submit"  value="提交">
    form>
    center>
  body>
html>

添加留言信息:student_add.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title heretitle>
<script type="text/javascript"> 
function turnback(){   
    window.location.href="<%=request.getContextPath() %>/message.action";   
}   
script> 
head>
<body>
<center>
<h1>添加留言h1>
<form method="post" action="<%=request.getContextPath()%>/message.action?method=save">  
        <div><c:out value="${addstate}">c:out>div>  
        <table>  
            <tr><td>姓名:td><td><input id="name" name="name" type="text" />td>tr> 
            <tr><td>电话:td><td><input id="phone" name="phone"  type="text" />td>tr>
            <tr><td>标题:td><td><input id="title" name="title" type="text" />td>tr>
            <tr><td>内容:td><td><input id="content" name="content"  type="text" />td>tr> 
            <tr><td colSpan="2" align="center"><input type="submit" value="提交"/>
            <input type="button" onclick="turnback()" value="返回" /> td>tr>  
        table>  
form>
center>  
body>
html>

success.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>成功提示title>
head>
<body>
<center>

<h1>操作成功!h1>
<a href="<%=request.getContextPath() %>/message.action">返回留言列表a>
center>
body>
html>

效果展示:
Hibernate+SpringMVC+Spring+分页实现留言管理项目_第2张图片

你可能感兴趣的:(javaweb知识)