• Struts2+Spring2.5+Hibernate3整合


    今天主要集成Struts2 + Spring2.5 + Hibernate3的开发。首先我们先整合 Spring2.5 + Hibernate3,然后在此基础上整合Struts2.

    第一步:首先罗列出Spring2.5 + Hibernate3 + 数据库驱动的必要Jar文件并加入到lib目录里:

    Hibernate3 所需的Jar文件:

    Spring2.5 所需的Jar文件:


    SqlServer驱动所需的Jar文件:

    第二步:在src下创建spring配置文件applicationContext.xml。

    <?xml version="1.0" encoding="UTF-8"?>  
    
    <beans xmlns="http://www.springframework.org/schema/beans"  
    
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    
           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-2.5.xsd   
    
               http://www.springframework.org/schema/context   
    
               http://www.springframework.org/schema/context/spring-context-2.5.xsd   
    
               http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd   
    
               http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">  
    
                  
    
        <context:annotation-config/>    
    
           
    
        <context:component-scan base-package="com.zhaoxuan.projectdemo"/>  
    
           
    
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">  
    
            <property name="driverClass" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>  
    
            <property name="jdbcUrl" value="jdbc:sqlserver://localhost:1032;DatabaseName=SSH2ProjectDemoDB"/>  
    
            <property name="user" value="sa"/>  
    
            <property name="password" value="sql2005"/>  
    
            <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->  
    
            <property name="initialPoolSize" value="1"/>  
    
            <!--连接池中保留的最小连接数。-->  
    
            <property name="minPoolSize" value="1"/>     
    
            <!--连接池中保留的最大连接数。Default: 15 -->  
    
            <property name="maxPoolSize" value="300"/>  
    
            <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->  
    
            <property name="maxIdleTime" value="60"/>    
    
            <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->  
    
            <property name="acquireIncrement" value="5"/>    
    
            <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->  
    
            <property name="idleConnectionTestPeriod" value="60"/>  
    
        </bean>  
    
           
    
        <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
    
            <property name="dataSource" ref="dataSource"/>  
    
             <property name="mappingResources">  
    
                    <list>  
    
                      <value>com/zhaoxuan/projectdemo/pojo/Users.hbm.xml</value>  
    
                    </list>  
    
            </property>  
    
             <property name="hibernateProperties">  
    
                 <value>  
    
                      hibernate.dialect=org.hibernate.dialect.SQLServerDialect   
    
                      hibernate.hbm2ddl.auto=update  
    
                      hibernate.show_sql=false  
    
                      hibernate.format_sql=false  
    
                  </value>  
    
             </property>  
    
        </bean>  
    
           
    
        <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
    
            <property name="sessionFactory" ref="sessionFactory"/>  
    
        </bean>  
    
        <!--使用基于注解方式配置事务 -->  
    
        <tx:annotation-driven transaction-manager="txManager"/>  
    
      
    
    </beans>  

     第三步:在src下创建包com.zhaoxuan.projectdemo.pojo,并创建实体类Users和一个Gender(Gender为枚举,指性别,它是Users的一个属性)以及Users的映射文件Users.hbm.xml。

    Users 类:

    package com.zhaoxuan.projectdemo.pojo;   
    
    public class Users {   
    
        private int id;   
    
        private String name;   
    
        private String pwd;   
    
        private Gender gender = Gender.男;   
    
     
    
        public Users(){}   
    
     
    
        public Users(String name, String pwd, Gender gender) {   
    
            this.name = name;   
    
            this.pwd = pwd;   
    
            this.gender = gender;   
    
        }   
    
        //------------------------get/set-----------------------------//   
    
        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 getPwd() {   
    
            return pwd;   
    
        }   
    
        public void setPwd(String pwd) {   
    
            this.pwd = pwd;   
    
        }   
    
        public Gender getGender() {   
    
            return gender;   
    
        }   
    
        public void setGender(Gender gender) {   
    
            this.gender = gender;   
    
        }   
    
    }  

    Gender 类:

    package com.zhaoxuan.projectdemo.pojo;    
    
    public enum Gender {   
    
        男,女;   
    
    }  

    Users.hbm.xml 映射文件:

    <?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 package="com.zhaoxuan.projectdemo.pojo">  
    
        <class name="Users" table="Users">  
    
            <id name="id" column="id">  
    
                <generator class="native"/>  
    
            </id>  
    
            <property name="name" length="20" not-null="true" column="name"/>  
    
            <property name="pwd" length="20" not-null="true" column="pwd"/>  
    
            <property name="gender" length="5">  
    
                <type name="org.hibernate.type.EnumType">  
    
                    <param name="enumClass">com.zhaoxuan.projectdemo.pojo.Gender</param>  
    
                    <!--12为java.sql.Types.VARCHAR常量值,即保存枚举的字面值到数据库。如果不指定type参数,保存枚举的索引值(从0开始)到数据库-->  
    
                    <param name="type">12</param>  
    
                </type>  
    
            </property>  
    
        </class>  
    
    </hibernate-mapping> 

    第四步:编写dao层代码,在src下创建包com.zhaoxuan.projectdemo.dao,在该包下创建接口UsersDao并创建的实现类UsersDaoImpl。

    UsersDao 类:

    package com.zhaoxuan.projectdemo.dao;   
    
    import java.util.List;   
    
    import com.zhaoxuan.projectdemo.pojo.Users; 
    
      
    
    public interface UsersDao {   
    
          
    
        public void save(Users users);   
    
        public void update(Users users);   
    
        public Users find(int id);   
    
        public void delete(int... ids);   
    
        public List<Users> list();   
    
        
    
    }  
    
     UsersDaoImpl 类:
    
    package com.zhaoxuan.projectdemo.dao.impl;   
    
    import java.util.List;   
    
    import javax.annotation.Resource;   
    
    import org.hibernate.SessionFactory;   
    
    import org.springframework.stereotype.Repository;   
    
    import org.springframework.transaction.annotation.Propagation;   
    
    import org.springframework.transaction.annotation.Transactional;   
    
    import com.zhaoxuan.projectdemo.dao.UsersDao;   
    
    import com.zhaoxuan.projectdemo.pojo.Users;   
    
      
    
    @Repository  
    
    @Transactional  
    
    public class UsersDaoImpl implements UsersDao {   
    
      
    
        @Resource private SessionFactory sessionFactory ;   
    
      
    
        public void delete(int... ids) {   
    
            for(int id : ids){   
    
                sessionFactory.getCurrentSession().delete(sessionFactory.getCurrentSession().load(Users.class, id));   
    
            }   
    
        }   
    
        @Transactional(propagation=Propagation.NOT_SUPPORTED)   
    
        public Users find(int id) {   
    
            // TODO Auto-generated method stub   
    
            return (Users)sessionFactory.getCurrentSession().get(Users.class, id);   
    
        }   
    
        @SuppressWarnings("unchecked")   
    
        @Transactional(propagation=Propagation.NOT_SUPPORTED)   
    
        public List<Users> list() {   
    
            return sessionFactory.getCurrentSession().createQuery("from Users").list();   
    
        }   
    
        public void save(Users users) {   
    
            sessionFactory.getCurrentSession().persist(users);   
    
      
    
        }   
    
        public void update(Users users) {   
    
            sessionFactory.getCurrentSession().merge(users);   
    
      
    
        }      
    
    }  

    第五步:编写service层代码,在src下创建包com.zhaoxuan.projectdemo.service,在该包下创建接口UsersService并创建的实现类UsersServiceImpl。

    UsersService 类:

    package com.zhaoxuan.projectdemo.service;   
    
      
    
    import java.util.List;   
    
    import com.zhaoxuan.projectdemo.pojo.Users;   
    
      
    
    public interface UsersService {   
    
           
    
        public void save(Users users);     
    
        public void update(Users users);     
    
        public Users find(int id);    
    
        public void delete(int... ids);   
    
        public List<Users> list();   
    
      
    
    } 
    
    UsersServiceImpl 类:
    
    package com.zhaoxuan.projectdemo.service.impl;   
    
      
    
    import java.util.List;   
    
    import javax.annotation.Resource;   
    
    import org.springframework.stereotype.Service;   
    
    import org.springframework.transaction.annotation.Propagation;   
    
    import org.springframework.transaction.annotation.Transactional;   
    
    import com.zhaoxuan.projectdemo.dao.UsersDao;   
    
    import com.zhaoxuan.projectdemo.pojo.Users;   
    
    import com.zhaoxuan.projectdemo.service.UsersService;   
    
      
    
    @Service  
    
    public class UsersServiceIpml implements UsersService {   
    
           
    
        @Resource private UsersDao usersDao;   
    
      
    
        public void delete(int... ids) {   
    
            usersDao.delete(ids);   
    
        }   
    
        @Transactional(propagation=Propagation.NOT_SUPPORTED)   
    
        public Users find(int id) {   
    
            return usersDao.find(id);   
    
        }   
    
        @Transactional(propagation=Propagation.NOT_SUPPORTED)   
    
        public List<Users> list() {   
    
            return usersDao.list();   
    
        }   
    
        public void save(Users users) {   
    
            usersDao.save(users);   
    
        }   
    
        public void update(Users users) {   
    
            usersDao.update(users);   
    
        }   
    
    }  

    第六步:通过以上五步,其实我们已经将Spring2.5和Hibernate3整合完毕了,但是为了验证,我们还得测试。在src下创建包com.zhaoxuan.projectdemo.junit,在该包下创建测试类UsersTest(注意加上Junit4支持)。

    UsersTest 类:

    package com.zhaoxuan.projectdemo.junit;   
    
      
    
    import java.util.List;   
    
    import javax.annotation.Resource;   
    
    import org.junit.BeforeClass;   
    
    import org.junit.Test;   
    
    import org.springframework.context.ApplicationContext;   
    
    import org.springframework.context.support.ClassPathXmlApplicationContext;   
    
    import com.zhaoxuan.projectdemo.dao.UsersDao;   
    
    import com.zhaoxuan.projectdemo.pojo.Gender;   
    
    import com.zhaoxuan.projectdemo.pojo.Users;   
    
    import com.zhaoxuan.projectdemo.service.UsersService;   
    
      
    
    public class UsersTest {   
    
           
    
        @Resource private static UsersService usersService;   
    
      
    
    //       
    
    //  @BeforeClass   
    
    //  public static void setUpBeforeClass() throws Exception {   
    
    //         
    
    //  }   
    
    //   
    
    //  @Test   
    
    //  public void createDBTest(){   
    
    //      new ClassPathXmlApplicationContext("applicationContext.xml");   
    
    //  }      
    
        @BeforeClass  
    
        public static void setUpBeforeClass() throws Exception {   
    
            try {   
    
                ApplicationContext act = new ClassPathXmlApplicationContext("applicationContext.xml");   
    
                usersService = (UsersService)act.getBean("usersServiceIpml");   
    
            } catch (RuntimeException e) {   
    
                // TODO Auto-generated catch block   
    
                e.printStackTrace();   
    
            }   
    
        }     
    
        @Test  
    
        public void save(){   
    
            usersService.save(new Users("zhaoxuan", "zhaoxuan123",Gender.男));   
    
            usersService.save(new Users("123", "123",Gender.女));   
    
            usersService.save(new Users("aaa", "aaa",Gender.女));   
    
        }      
    
        @Test  
    
        public void find(){   
    
            Users users = usersService.find(1);   
    
            System.out.println("帐号:" + users.getName() + " 密码 :" + users.getPwd() + " 性别:" +users.getGender() );   
    
        }     
    
        @Test  
    
        public void list(){   
    
            List<Users> list = usersService.list();   
    
            for(Users users : list){   
    
                System.out.println("帐号:" + users.getName() + " 密码 :" + users.getPwd() + " 性别:" +users.getGender() );   
    
            }   
    
        }     
    
        @Test  
    
        public void update(){   
    
            Users users = usersService.find(6);   
    
            users.setGender(Gender.男);   
    
            usersService.update(users);   
    
        }     
    
        @Test  
    
        public void delete(){   
    
            usersService.delete(3);   
    
        }      
    
    } 

    测试效果


    嘿嘿。。。好啦,效果出来了,CRUD能够正常操作,通过以上六步,我们已经完全将Spring2.5和Hibernate3整合完毕了,接下来就是在此基础上整合Struts2了

    第一步:罗列出Struts2的必要Jar文件并加入到lib目录里:

    Struts2 所需的Jar文件:


    在这里我们顺便加入JSTL/EL表达式的Jar文件到lib里,因为我们页面上可能会用到...

    JSTL/EL 所需的Jar文件:

    第二步:修改编写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">  
    
        <!--  指定spring的配置文件,默认从web根目录寻找配置文件,我们可以通过spring提供的classpath:前缀指定从类路径下寻找  -->  
    
        <context-param>  
    
            <param-name>contextConfigLocation</param-name>  
    
            <param-value>classpath:applicationContext.xml</param-value>  
    
        </context-param>  
    
        <!-- 对Spring容器进行实例化 -->  
    
        <listener>  
    
            <listenerclass>
    
               org.springframework.web.context.ContextLoaderListener
    
            </listener-class>  
    
        </listener>  
    
      
    
        <filter>  
    
            <filter-name>struts2</filter-name>  
    
            <filterclass>
    
               org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    
            </filter-class>  
    
        </filter>  
    
        <filter-mapping>  
    
            <filter-name>struts2</filter-name>  
    
            <url-pattern>/*</url-pattern>  
    
        </filter-mapping>  
    
         
    
      <welcome-file-list>  
    
        <welcome-file>index.jsp</welcome-file>  
    
      </welcome-file-list>  
    
     
    
    </web-app>  

    第三步:在src下创建struts2的配置文件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>  
    
        <!-- 与Spring集成,指定由Spring负责Action对象的创建 -->  
    
       <constant name="struts.objectFactory" value="spring"></constant>  
    
        <!-- 默认的视图主题 -->    
    
       <constant name="struts.ui.theme" value="simple"></constant>    
    
     
    
       <package name="UsersAction" namespace="" extends="struts-default">  
    
            <action name="UsersAction_*" class="usersAction" method="{1}">  
    
                <result name="list">/page/users.jsp</result>  
    
            </action>  
    
        </package>  
    
    </struts>   

    第四步:在src下创建包com.zhaoxuan.projectdemo.action,并创建Action类UsersAction 

    package com.zhaoxuan.projectdemo.action;   
    
     
    
    import javax.annotation.Resource;   
    
    import org.springframework.context.annotation.Scope;   
    
    import org.springframework.stereotype.Controller;   
    
    import com.opensymphony.xwork2.ActionContext;   
    
    import com.zhaoxuan.projectdemo.pojo.Users;   
    
    import com.zhaoxuan.projectdemo.service.UsersService;   
    
      
    
    @Controller  
    
    @Scope("prototype")   
    
    public class UsersAction {   
    
           
    
        private static final long serialVersionUID = 1L;   
    
      
    
        @Resource private UsersService usersService;    //Server层   
    
        private Users users;   
    
           
    
        public String list(){   
    
            ActionContext.getContext().put("users",usersService.list());   
    
            return "list";   
    
        }   
    
        
    
        //----------------get/set---------------------//   
    
        public Users getUsers() {   
    
            return users;   
    
        }   
    
        public void setUsers(Users users) {   
    
            this.users = users;   
    
        }   
    
    }  

    第五步:创建一个用户列表页面users.jsp,这里我用两种方式显示列表,ognl和jstl两种,但都要注意在页面头部加上他们的标签.

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
    
    <%@ taglib uri="/struts-tags" prefix="s"%>  
    
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
    
    <html>  
    
      <head>  
    
        <title>用户列表</title>  
    
           
    
        <meta http-equiv="pragma" content="no-cache">  
    
        <meta http-equiv="cache-control" content="no-cache">  
    
        <meta http-equiv="expires" content="0">    
    
      </head>  
    
         
    
      <body>  
    
       ONGL:   
    
       <br/>  
    
       <br/>  
    
       <s:iterator value="#request.users">  
    
        <s:property value="id"/>,<s:property value="name"/>,<s:property value="pwd"/>,<s:property value="gender"/><br/>  
    
       </s:iterator>  
    
       <br/>  
    
       <br/>  
    
       JSTL/EL:   
    
       <br/>  
    
       <br/>  
    
       <c:forEach items="${users}" var="users">  
    
            ${users.id },${users.name },${users.pwd },${users.gender }<br/>  
    
       </c:forEach>  
    
       <br/>  
    
       <br/>  
    
      </body>  
    
    </html>  

    好了,刷新项目,启动服务,接下来在浏览器地址栏中输入:

    最后效果:

    在此我们的整合就正式完毕并成功了,并附上项目的目录结构:

    OK,谢谢大家的支持....

  • 相关阅读:
    杭州电acm理工大舞台版
    String.Split()功能
    android layout物业介绍
    讨厌OpenSSL
    Android Bundle类别
    多项式回归
    如何直接串行电缆以及空调制解调器串行电缆之间的区别?
    为什么写科技博客是情侣如此重要?
    SSH框架总结(帧分析+环境结构+示例源代码下载)
    RapidXml用法
  • 原文地址:https://www.cnblogs.com/xuanzai/p/2681226.html
Copyright © 2020-2023  润新知