Struts、Spring、Hibernate整合


 

Struts、Spring、Hibernate整合
一、创建web工程,搭建Struts框架开发环境:
这里只导入了项目中所需要的重要的jar包,以后根据业务要求继续导入相关的包。
步骤1:导入struts框架所需的jar包
步骤2:在web.xml中配置struts2.0主过滤器
步骤3:导入struts.xml配置文件
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
        <!--  配置 Struts2 的主过滤器 -->
        <filter>
                 <filter-name>struts2</filter-name>
                <filter-class>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>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
<struts>
        <!-- 配置为开发模式 -->
    <constant name="struts.devMode" value="true" />
    <!-- 配置扩展名为 action -->
        <constant name="struts.action.extension" value="action"/>
    <package name="default" namespace="/" extends="struts-default">
    </package>
   
</struts>
二、搭建Hibernate开发环境:
创建数据库:
这里只导入了项目中所需要的重要的jar包,以后根据业务要求继续导入相关的包。
工程目录:
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
<hibernate-configuration>
        <session-factory>
                 <!-- 配置 Hibernate: 属性配置参考   Hibernate 发型包 \project\etc\hibernate.properties -->
                 <!-- JDBC 的基本链接 -->
                 <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
                 <property name="connection.username">root</property>
                 <property name="connection.password">root</property>
                 <property name="connection.url">jdbc:mysql://localhost:3306/xbmuoa</property>
                 <!-- 配置数据库方言 -->
                 <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
                 <!-- 根据映射产生表结构的类型 :
                         create-drop: 木有表结构创建,下次启动时删除重新创建。适合学习阶段
                         create :只做创建
                         update :探测表结构够的变化,对于数据库没有的,进行更新操作。适合学习阶段
                         validate :对比与数据库的结构
                  -->
                 <property name="hibernate.hbm2ddl.auto">update</property>
                 <!-- 显示 sql 语句及格式:开发调试阶段非常有用 -->
                 <property name="hibernate.show_sql">true</property>
                 <property name="hibernate.format_sql">true</property>
                 
                 <!-- 告知映射文件 -->
                 
        </session-factory>
</hibernate-configuration>
Person.hbm.xml (暂时性先写个映射文件的模板)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<hibernate-mapping package="cn.xbmu.oa.domain">
        
</hibernate-mapping>
三、搭建Spring开发环境:
这里只导入了项目中所需要的重要的jar包,以后根据业务要求继续导入相关的包。
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
        xmlns:tx=" http://www.springframework.org/schema/tx" ;
        <!-- 自动扫描与装配 bean -->
        <context:component-scan base-package="cn.xbmu.oa"></context:component-scan>
</beans>
以上已经将Struts、Spring、Hibernate开发所需要的jar包及其配置文件已经配置到web工程中了。
接下来,我们两两整合在一起。
四、Spring与Hibernate整合:
让Spring来管理SessionFactory和事务。
工程目录:
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
        xmlns:tx="http://www.springframework.org/schema/tx";
        <!-- 自动扫描与装配 bean -->
        <context:component-scan base-package="cn.xbmu.oa"></context:component-scan>
        <!-- 加载外部的 properties 配置文件 -->
        <context:property-placeholder location="classpath:jdbc.properties" />
        <!-- 配置数据库连接池( c3p0 -->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
                 <!-- 基本信息 -->
                 <property name="jdbcUrl" value="${jdbcUrl}"></property>
                 <property name="driverClass" value="${driverClass}"></property>
                 <property name="user" value="${username}"></property>
                 <property name="password" value="${password}"></property>
                 <!-- 其他配置 -->
                 <!-- 初始化时获取三个连接,取值应在 minPoolSize maxPoolSize 之间。 Default: 3 -->
                 <property name="initialPoolSize" value="3"></property>
                 <!-- 连接池中保留的最小连接数。 Default: 3 -->
                 <property name="minPoolSize" value="3"></property>
                 <!-- 连接池中保留的最大连接数。 Default: 15 -->
                 <property name="maxPoolSize" value="5"></property>
                 <!-- 当连接池中的连接耗尽的时候 c3p0 一次同时获取的连接数。 Default: 3 -->
                 <property name="acquireIncrement" value="3"></property>
                 <!-- 控制数据源内加载的 PreparedStatements 数量。如果 maxStatements maxStatementsPerConnection 均为 0 ,则缓存被关闭。 Default: 0 -->
                 <property name="maxStatements" value="8"></property>
                 <!-- maxStatementsPerConnection 定义了连接池内单个连接所拥有的最大缓存 statements 数。 Default: 0 -->
                 <property name="maxStatementsPerConnection" value="5"></property>
                 <!-- 最大空闲时间 ,1800 秒内未使用则连接被丢弃。若为 0 则永不丢弃。 Default: 0 -->
                 <property name="maxIdleTime" value="1800"></property>
        </bean>
        <!-- 配置 SessionFactory -->
        <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
                 <property name="dataSource" ref="dataSource"></property>
                 <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
        </bean>
        <!-- 配置声明式的事务管理(采用基于注解的方式) -->
        <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
                 <property name="sessionFactory" ref="sessionFactory"></property>
        </bean>
        <tx:annotation-driven transaction-manager="transactionManager" />
</beans>
jdbc.properties
jdbcUrl          = jdbc:mysql:///xbmuoa
driverClass      = com.mysql.jdbc.Driver
username= root
password= root 

SpringTest.java
package cn.xbmu.oa.test;
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {
        private ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        
        // 测试 SessionFactory
        @Test
        public void testSessionFactory(){
                 SessionFactory sessionFactory = (SessionFactory) ac.getBean("sessionFactory");
                 System.out.println(sessionFactory);
        }
}
使用Junit测试,结果:
启动tomcat没有报错,说明以上环境的搭建都完全正确,并进行测试,也没有报错。

User.java
package cn.xbmu.oa.domain;
public class User {
        private Long id;
        private String name;
        public Long getId() {
                 return id;
        }
        public void setId(Long id) {
                 this.id = id;
        }
        public String getName() {
                 return name;
        }
        public void setName(String name) {
                 this.name = name;
        }
        
}

User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<hibernate-mapping package="cn.xbmu.oa.domain">
        <class name="User">
                 <id name="id">
                         <generator class="native"/>
                 </id>
                 <property name="name"/>
        </class>
</hibernate-mapping>
记得在hibernate.cfg.xml文件中引入映射文件。

TestService.java
package cn.xbmu.oa.test;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.xbmu.oa.domain.User;
@Service("testService")
public class TestService {
        @Resource
        private SessionFactory sessionFactory;
        @Transactional
        public void saveTwoUser(){
                 Session currentSession = sessionFactory.getCurrentSession();
                 currentSession.save(new User());
                 int i = 1 / 0;// 这里会抛出异常
                 currentSession.save(new User());
        }
}

SpringTest.java
package cn.xbmu.oa.test;
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {
        private ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        
        // 测试 SessionFactory
        @Test
        public void testSessionFactory(){
                 SessionFactory sessionFactory = (SessionFactory) ac.getBean("sessionFactory");
                 System.out.println(sessionFactory);
        }
        // 测试事务
        @Test
        public void testTransaction(){
                 TestService testService = (TestService) ac.getBean("testService");
                 testService.saveTwoUser();
        }
}

测试事务,报错,因为在 int i = 1 / 0这里发生了异常。
查询数据库xbmuoa中的表,没有数据
我们注释掉  int i = 1 / 0; 这句代码,重新测试,成功。
查询user表,里面已经有了保存的数据
我们,继续打开抛异常的语句,再测试;再注释抛异常的代码,再测试。查看表中的数据,发现了事务回滚了。
到此为止,我们顺利的将Spring与Hibernate整合在一起了。并测试了SessionFactory与事务,都正常。
五、Spring与Struts整合:
为了说明白,我们在整合之前写个Action,整合之后写个Action,看看他们之间的区别:
整合之前:
TestAction.java
package cn.xbmu.oa.test;
import com.opensymphony.xwork2.ActionSupport;
public class TestAction extends ActionSupport {
        @Override
        public String execute() throws Exception {
                 System.out.println("---------->TestAction execute()");
                 return "success";
        }
}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
<struts>
        <!-- 配置为开发模式 -->
    <constant name="struts.devMode" value="true" />
    <!-- 配置扩展名为 action -->
        <constant name="struts.action.extension" value="action"/>
    <package name="default" namespace="/" extends="struts-default">
        <!-- 测试用的 action -->
                 <action name="test" class="cn.xbmu.oa.test.TestAction">
                         <result name="success">/test.jsp</result>
                 </action>
    </package>
   
</struts>
test.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  <body>
        Struts2.0 添加成功 <br/>
  </body>
</html>
运行:
整合之后:
导入jar包,已经完成了整合

TestAction.java
package cn.xbmu.oa.test;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionSupport;
@Controller
@Scope("prototype")
public class TestAction extends ActionSupport {
        
        @Override
        public String execute() throws Exception {
                 System.out.println("---------->TestAction execute()");
                 return "success";
        }
}

struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
<struts>
        <!-- 配置为开发模式 -->
    <constant name="struts.devMode" value="true" />
    <!-- 配置扩展名为 action -->
        <constant name="struts.action.extension" value="action"/>
    <package name="default" namespace="/" extends="struts-default">
        <!-- 测试用的 action, 当与 Spring 整合后, class 属性写的就是 bean 的名称 -->
                 <action name="test" class="testAction">
                         <result name="success">/test.jsp</result>
                 </action>
    </package>
   
</struts>

发现,在控制台上报错,信息如下:
严重 : ********** FATAL ERROR STARTING UP STRUTS-SPRING INTEGRATION **********
Looks like the Spring listener was not configured for your web app!
Nothing will work until WebApplicationContextUtils returns a valid ApplicationContext.
You might need to add the following to web.xml:
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
四月 03, 2016 9:48:27 下午 com.opensymphony.xwork2.util.logging.commons.CommonsLogger error
严重 : Dispatcher initialization failed
java.lang.NullPointerException
        at com.opensymphony.xwork2.spring.SpringObjectFactory.getClassInstance(SpringObjectFactory.java:209)
        at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.verifyResultType(XmlConfigurationProvider.java:519)
        at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addResultTypes(XmlConfigurationProvider.java:490)
        at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addPackage(XmlConfigurationProvider.java:446)
        at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadPackages(XmlConfigurationProvider.java:264)
        at org.apache.struts2.config.StrutsXmlConfigurationProvider.loadPackages(StrutsXmlConfigurationProvider.java:111)
        at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:193)
        at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:55)
        at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:374)
        at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:418)
        at org.apache.struts2.dispatcher.ng.InitOperations.initDispatcher(InitOperations.java:69)
        at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.init(StrutsPrepareAndExecuteFilter.java:51)
        at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:279)
        at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:260)
        at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:105)
        at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4854)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5542)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:649)
        at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1245)
        at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1895)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
        at java.util.concurrent.FutureTask.run(FutureTask.java:262)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:724)
四月 03, 2016 9:48:27 下午 org.apache.catalina.core.StandardContext filterStart
严重 : Exception starting filter struts2
Class: com.opensymphony.xwork2.spring.SpringObjectFactory
File: SpringObjectFactory.java
Method: getClassInstance
Line: 209 - com/opensymphony/xwork2/spring/SpringObjectFactory.java:209:-1
        at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:431)
        at org.apache.struts2.dispatcher.ng.InitOperations.initDispatcher(InitOperations.java:69)
        at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.init(StrutsPrepareAndExecuteFilter.java:51)
        at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:279)
        at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:260)
        at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:105)
        at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4854)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5542)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:649)
        at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1245)
        at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1895)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
        at java.util.concurrent.FutureTask.run(FutureTask.java:262)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:724)
Caused by: java.lang.NullPointerException
        at com.opensymphony.xwork2.spring.SpringObjectFactory.getClassInstance(SpringObjectFactory.java:209)
        at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.verifyResultType(XmlConfigurationProvider.java:519)
        at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addResultTypes(XmlConfigurationProvider.java:490)
        at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addPackage(XmlConfigurationProvider.java:446)
        at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadPackages(XmlConfigurationProvider.java:264)
        at org.apache.struts2.config.StrutsXmlConfigurationProvider.loadPackages(StrutsXmlConfigurationProvider.java:111)
        at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:193)
        at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:55)
        at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:374)
        at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:418)
        ... 18 more
意思就是,没有和web工程整合,没有一个全局的工厂容器对象。
在web.xml中配置信息如下:
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
        <!-- 配置 Spring 的监听器,用于初始化 ApplicationContext 对象 -->
        <listener>
                <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <context-param>
                 <param-name>contextConfigLocation</param-name>
                <param-value>classpath:applicationContext*.xml</param-value>
        </context-param>
        <!--  配置 Struts2 的主过滤器 -->
        <filter>
                 <filter-name>struts2</filter-name>
                <filter-class>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>
TestAction.java
package cn.xbmu.oa.test;
import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionSupport;
@Controller
@Scope("prototype")
public class TestAction extends ActionSupport {
        
        @Resource
        private TestService testService;
        @Override
        public String execute() throws Exception {
                 System.out.println("---------->TestAction execute()");
                 testService.saveTwoUser();
                 return "success";
        }
}
在浏览器中运行,报错,是因为在 int i = 1 / 0出抛出了异常
注释掉这句抛异常的语句,继续运行,成功。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值