Struts2边学边练(3)-Struts2集成Hibernate完成CRUD操作

Struts2边学边练(3)-Struts2集成Hibernate完成CRUD操作
在这个项目中,准备用Struts2集成hibernate来完成数据库的简单CRUD操作,暂时不涉及集成spring。项目需要的lib文件:
antlr-2.7.6.jar
cglib-nodep-2.1_3.jar
commons-collections-3.1.jar
commons-logging-1.0.4.jar
dom4j-1.6.1.jar
ehcache-1.2.3.jar
freemarker-2.3.8.jar
hibernate3.jar
javassist-3.4.GA.jar
jta-1.1.jar
log4j-1.2.15.jar
mysql-connector-java-5.1.7-bin.jar
ognl-2.6.11.jar
servlet-api.jar
slf4j-api-1.5.6.jar
slf4j-log4j12-1.5.6.jar
struts2-core-2.0.14.jar
xwork-2.0.7.jar

在这个系统中将完成User对象的增、删、改、查功能。Uer对象的属性有id,name和password。

将分为如下几个步骤来完成:

1.编写Hibernate工具类
2.编写Hibernate拦截器控制事务
3.编写DAO类
4.编写User对象和hibernate映射文件
5.编写UserAction类
6.编写所需的listUser.jsp和editUser.jsp页面
7.编写struts配置文件
8.配置web.xml文件
9.发布测试

首先新建一个web project项目Struts2Hibernate,将上面所需的jar全部复制到WEB-INF下的lib文件夹中。

1.编写Hibernate工具类:

首先编写hibernate.cfg.xml文件,文件放在src目录下。此文件主要配置hibernate的数据库连接和事务管理。
<? 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 >

        
< property  name ="hibernate.connection.driver_class" > com.mysql.jdbc.Driver </ property >
        
        
< property  name ="hibernate.connection.url" > jdbc:mysql://localhost:3306/test </ property >
        
        
< property  name ="hibernate.connection.username" > root </ property >
        
        
< property  name ="hibernate.connection.password" ></ property >
        
        
< property  name ="dialect" > org.hibernate.dialect.MySQLDialect </ property >
        
        
< property  name ="hibernate.current_session_context_class" > thread </ property >
        
        
< property  name ="hibernate.transaction.JDBCTransactionFactory" >
            org.hibernate.transaction.JDBCTransactionFactory
        
</ property >

        
<!--  Echo all executed SQL to stdout  -->
        
< property  name ="show_sql" > true </ property >

        
<!--  Drop and re-create the database schema on startup  -->
        
< property  name ="hbm2ddl.auto" > create </ property >

        
< mapping  resource ="com/hibernate/domain/User.hbm.xml" />

    
</ session-factory >

</ hibernate-configuration >


接着编写HibernateUtil类,用于获取SessionFactory实例。此类可以在hibernate-distribution-3.3.1.GA包的\project\tutorials下找到。
package  com.hibernate.util;

import  org.hibernate.SessionFactory;
import  org.hibernate.cfg.Configuration;

public   class  HibernateUtil  {
    
    
private static final SessionFactory sessionFactory;

    
static {
        
try {
            
// Create the SessionFactory from hibernate.cfg.xml
            sessionFactory = new Configuration().configure().buildSessionFactory();
        }
 catch (Throwable ex) {
            
// Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            
throw new ExceptionInInitializerError(ex);
        }

    }


    
public static SessionFactory getSessionFactory() {
        
return sessionFactory;
    }

}


接着编写一个ExportDB类,方便用户直接将写好的hibernate映射表结构创建到数据库中。此类可以单独直接运行。
package  com.hibernate.util;

import  org.hibernate.cfg.Configuration;
import  org.hibernate.tool.hbm2ddl.SchemaExport;

public   class  ExportDB  {

    
public static void main(String[] args) {
        
          Configuration cf 
=   new Configuration().configure();
          
          SchemaExport se 
=   new SchemaExport(cf);
          se.create(
falsetrue);
        }

}


2.编写Hibernate拦截器控制事务
编写一个SessionInterceptor类来解决hibernate的lazyInitializationException。主要是采用过滤器的方式,在请求到达目标资源之前开始事务,在目标资源响应之后结束事务,来支持请求/响应模式所需的长事务。为了能执行此filter,需要在web.xml中增加filter。
package  com.hibernate.web;

import  java.io.IOException;

import  javax.servlet.Filter;
import  javax.servlet.FilterChain;
import  javax.servlet.FilterConfig;
import  javax.servlet.ServletException;
import  javax.servlet.ServletRequest;
import  javax.servlet.ServletResponse;

import  org.hibernate.SessionFactory;
import  org.hibernate.StaleObjectStateException;


import  com.hibernate.util.HibernateUtil;

public   class  SessionInterceptor  implements  Filter   {

    
private SessionFactory sf = null;

    
public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) 
throws IOException, ServletException {
        
        
try{
            
if (sf.getCurrentSession()==null){
                sf.openSession();
            }
else{
                sf.getCurrentSession().beginTransaction();        
            }

            chain.doFilter(request, response);
            sf.getCurrentSession().getTransaction().commit();
        }
catch(StaleObjectStateException ex){
            
throw ex;
        }
catch(Throwable tx){
            tx.printStackTrace();
            
try{
                
if(sf.getCurrentSession().getTransaction().isActive()){
                    sf.getCurrentSession().getTransaction().rollback();
                }

            }
catch(Throwable rbEx){
                System.err.println(rbEx.toString());
            }

        }

    }


    
public void init(FilterConfig arg0) throws ServletException {    
        sf 
= HibernateUtil.getSessionFactory();
    }

    
    
public void destroy() {
        
    }


}


3.编写DAO类

编写一个DAOFactorty类用于屏蔽具体的DAO实现。
package  com.hibernate.dao;

public   abstract   class  DaoFactory  {

    
private static final DaoFactory daoFactory = new HibernateDaoFactory();
    
    
public static DaoFactory getInstance(){
        
        
return daoFactory;
    }

    
    
public abstract UserDao getUserDao();
}


编写HibernateDaoFactory工厂类,获得具体的DAO实现类。
package  com.hibernate.dao;

import  org.hibernate.Session;

import  com.hibernate.dao.impl.UserDaoImpl;
import  com.hibernate.util.HibernateUtil;

public   class  HibernateDaoFactory  extends  DaoFactory  {

    
public UserDao getUserDao(){
        UserDao userdao 
= new UserDaoImpl(getCurrentSession());
        
return userdao;
    }

    
    
private Session getCurrentSession(){
        
return HibernateUtil.getSessionFactory().getCurrentSession();
    }

}


编写UserDAO接口,便于不让上层依赖具体的DAO实现类。
package  com.hibernate.dao;

import  java.util.List;
import  com.hibernate.domain.User;

public   interface  UserDao  {
  
    
public User findById(Integer id);
    
public List<User> findAll();
    
public void makePersistent(User user);
    
public void delete(Integer id);
}


编写具体的实现类UserDaoImpl类
package  com.hibernate.dao.impl;

import  java.util.List;

import  org.hibernate.Session;

import  com.hibernate.dao.UserDao;
import  com.hibernate.domain.User;

public   class  UserDaoImpl  implements  UserDao  {

    
private Session session ;
    
    
public UserDaoImpl(Session session) {
        
this.session = session;
    }

    
    
public Session getSession() {
        
return session;
    }


    
public void delete(Integer id) {
        session.delete(getSession().get(User.
class, id));
    }


    
public List<User> findAll() {
        
return session.createCriteria(User.class).list();
    }


    
public User findById(Integer id) {
        
return (User)session.get(User.class, id);
    }


    
public void makePersistent(User user) {
        session.saveOrUpdate(user);
    }


}


4.编写User对象和hibernate映射文件

编写领域对象User。
package  com.hibernate.domain;

public   class  User  {
 
    
private int id;
    
    
private String name;
    
    
private String password;

    
public int getId() {
        
return id;
    }


    
public void setId(int id) {
        
this.id = id;
    }


    
public String getName() {
        
return name;
    }


    
public void setName(String name) {
        
this.name = name;
    }


    
public String getPassword() {
        
return password;
    }


    
public void setPassword(String password) {
        
this.password = password;
    }

    
}


对上述领域对象编写hibernate映射文件User.hbm.xml
<? xml version="1.0" ?>
<! DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
>

< hibernate-mapping  package ="com.hibernate.domain" >

    
< class  name ="User"  table ="user" >
        
< id  name ="id"  column ="id" >
            
< generator  class ="native" />
        
</ id >
        
< property  name ="name" />
        
< property  name ="password" />
    
</ class >

</ hibernate-mapping >

5.编写UserAction类

在UserAction中完成User对象的CRUD相关函数的开发。同时需要创建3个属性,users,user,id
package  com.struts2.action;

import  java.util.List;

import  com.hibernate.dao.DaoFactory;
import  com.hibernate.domain.User;
import  com.opensymphony.xwork2.ActionSupport;
import  com.opensymphony.xwork2.Preparable;


public   class  UserAction  extends  ActionSupport  implements  Preparable  {

    
private static final long serialVersionUID = -1057922687577124881L;
    
    
private List<User> users;
    
private User user;
    
private Integer id;
    
    
public List<User> getUsers() {
        
return users;
    }


    
public void setUsers(List<User> users) {
        
this.users = users;
    }


    
public User getUser() {
        
return user;
    }


    
public void setUser(User user) {
        
this.user = user;
    }


    
public Integer getId() {
        
return id;
    }


    
public void setId(Integer id) {
        
this.id = id;
    }


    
public String list() throws Exception{
        users 
= DaoFactory.getInstance().getUserDao().findAll();
        
return SUCCESS;
    }

    
    
public String delete() throws Exception{
        
if(id!=null){
          DaoFactory.getInstance().getUserDao().delete(id);
        }

        
return SUCCESS;
    }

    
    
public String save() throws Exception{
        DaoFactory.getInstance().getUserDao().makePersistent(user);
        
return SUCCESS;
    }

    
    
public void prepare() throws Exception{
        
if(id!=null){
         user 
= DaoFactory.getInstance().getUserDao().findById(id);
        }

    }


}


6.编写所需的listUser.jsp和editUser.jsp页面
index.jsp如下:
<% @ page language = " java "  contentType = " text/html; charset=ISO-8859-1 "  pageEncoding = " ISO-8859-1 " %>
<% @ taglib prefix = " s "  uri = " /struts-tags " %>
<! DOCTYPE html PUBLIC  " -//W3C//DTD HTML 4.01 Transitional//EN "   " http://www.w3.org/TR/html4/loose.dtd " >

< html >
< head >
< title > Struts2Hibernate </ title >
</ head >
< body >
  Welcome to Struts2Hibernate Project
  
< p >
  
< a href = " listUser.jsp " > View all users </ a >
</ body >
</ html >

listUser.jsp如下
<% @ page language = " java "  contentType = " text/html; charset=ISO-8859-1 "
    pageEncoding
= " ISO-8859-1 " %>
<% @ taglib prefix = " s "  uri = " /struts-tags " %>

<! DOCTYPE html PUBLIC  " -//W3C//DTD HTML 4.01 Transitional//EN "   " http://www.w3.org/TR/html4/loose.dtd " >

< html >
< head >
< title > Struts2Hibernate </ title >
</ head >
< body >
< table >
   
< tr >
     
< th > id </ th >
     
< th > name </ th >
     
< th > password </ th >
   
</ tr >
    
< s:iterator value = " users " >
        
< tr >
            
< td >< a href = " <s:url action= " edit -% {id} " /> " >< s:property value = " id " /></ a ></ td >
            
< td >< s:property value = " name "   /></ td >
            
< td >< s:property value = " password "   /></ td >
            
< td >< a href = " <s:url action= " delete -% {id} " /> " > delete </ a ></ td >
        
</ tr >
    
</ s:iterator >
</ table >
< p >
< a href = " <s:url action= " edit - "  includeParams= " none " /> " > create  new  user </ a >
</ body >
</ html >

editUser.jsp如下:
<% @ page language = " java "  contentType = " text/html; charset=ISO-8859-1 "  pageEncoding = " ISO-8859-1 " %>
<% @ taglib prefix = " s "  uri = " /struts-tags "   %>

<! 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=ISO-8859-1 " >
< title > Struts2Hibernate </ title >
</ head >
< body >
  
< s: if  test = " user!=null " >
    
< s:text id = " title "  name = " edit user " />
  
</ s: if >
  
< s: else >
    
< s:text id = " title "  name = " create user " />
  
</ s: else >
  
  
< s:property value = " #title " />
  
  
< s:form action = " save "  method = " post " >
     
< s:hidden name = " user.id "  name = " user.id "  value = " %{user.id} " ></ s:hidden >
     
< s:textfield label = " name "  name = " user.name "  value = " %{user.name} " ></ s:textfield >
     
< s:password label = " password "  name = " user.password "  value = " %{user.password} " ></ s:password >
     
< s:submit value = " save " ></ s:submit >
  
</ s:form >
</ body >
</ html >


7.编写struts配置文件struts.xml
<? xml version="1.0" encoding="UTF-8"  ?>
<! DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd"
>

< struts >
    
< constant  name ="struts.i18n.encoding"  value ="GBK"   />
    
    
< package  name ="default"  extends ="struts-default" >
        
< action  name ="list"  class ="com.struts2.action.UserAction"  method ="list" >
            
< result  name ="success" > /listUser.jsp </ result >
            
< interceptor-ref  name ="basicStack"   />
        
</ action >
 
        
< action  name ="edit-*"  class ="com.struts2.action.UserAction" >
            
< param  name ="id" > {1} </ param >
            
< result > /editUser.jsp </ result >
            
< interceptor-ref  name ="static-params"   />
            
< interceptor-ref  name ="basicStack"   />
        
</ action >
        
        
< action  name ="save"  class ="com.struts2.action.UserAction"  method ="save" >
            
< result  name ="input" > /editUser.jsp </ result >
            
< result  type ="redirect" > list.action </ result >
        
</ action >
        
        
< action  name ="delete-*"  class ="com.struts2.action.UserAction"  method ="delete" >
            
< param  name ="id" > {1} </ param >
            
< result  type ="redirect" > list.action </ result >
            
< interceptor-ref  name ="static-params"   />
        
</ action >
        
    
</ package >

</ struts >

8.配置web.xml文件
注意:SessionInterceptor的filter要放在第一个filer的位置。
<? xml version="1.0" encoding="UTF-8" ?>
< web-app  id ="WebApp_ID"  version ="2.4"  xmlns ="http://java.sun.com/xml/ns/j2ee"  xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation ="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >
    
    
< display-name > Struts2Hibernate </ display-name >
    
    
< welcome-file-list >
        
< welcome-file > index.jsp </ welcome-file >
    
</ welcome-file-list >
    
    
< filter >
        
< filter-name > SessionInterceptor </ filter-name >
        
< filter-class > com.hibernate.web.SessionInterceptor </ filter-class >
    
</ filter >
    
< filter-mapping >
        
< filter-name > SessionInterceptor </ filter-name >
        
< url-pattern > /* </ url-pattern >
    
</ filter-mapping >
    
    
< filter >
        
< filter-name > struts2 </ filter-name >
        
< filter-class > org.apache.struts2.dispatcher.FilterDispatcher </ filter-class >
    
</ filter >
    
< filter-mapping >
        
< filter-name > struts2 </ filter-name >
        
< url-pattern > /* </ url-pattern >
    
</ filter-mapping >
    
</ web-app >

9.发布测试




你可能感兴趣的:(Struts2边学边练(3)-Struts2集成Hibernate完成CRUD操作)