---
title: "SSH2整合示例"
author: "freeglad"
date: "2009-05-06T21:20:00Z"
tags: ["AOP", "Bean", "Spring", "Struts", "配置管理"]
slug: "ssh2"
draft: false
lastmod: "2009-05-06T21:20:00Z"
id: 586392
url: "https://freeglad.iteye.com/blog/586392"
---

最近学习了Struts2，做了一个简单的登录的例子，采用SSH2进行整合。由于登录的例子挺简单，DAO层，Service层，Struts Action等文件就没有在此详细写出来，下面列出了整合时一些关键的配置：

**Spring配置：**  
**&lt;!-- spring中配置Action，由Spring管理创建 --&gt;**  
**&lt;bean id="userAction" scope="prototype" class="com.xxh.actions.UserAction"&gt;**  
**&lt;property name="userServ"&gt;**  
**&lt;ref bean="userServ"/&gt;**  
**&lt;/property&gt;**  
**&lt;/bean&gt;**

&lt;!-- 事务配置 --&gt;  
&lt;tx:advice id="myAdvice"&gt;  
&lt;tx:attributes&gt;  
&lt;tx:method name="login" read-only="true"/&gt;  
&lt;/tx:attributes&gt;  
&lt;/tx:advice&gt;  
&lt;bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt;  
&lt;property name="sessionFactory"&gt;  
&lt;ref bean="sessionFactory"/&gt;  
&lt;/property&gt;  
&lt;/bean&gt;  
&lt;aop:config&gt;  
&lt;aop:pointcut id="daoPoint" expression="execution(* com.xxh.daos.\*.\*(..))" /&gt;  
&lt;aop:advisor advice-ref="myAdvice" pointcut-ref="daoPoint"/&gt;  
&lt;/aop:config&gt;

&lt;!-- DAO配置 --&gt;  
&lt;bean id="userDao" class="com.xxh.daos.UserDao"&gt;  
&lt;property name="sessionFactory"&gt;  
&lt;ref bean="sessionFactory"/&gt;  
&lt;/property&gt;  
&lt;/bean&gt;

&lt;!-- 业务逻辑配置 --&gt;  
&lt;bean id="userServ" class="com.xxh.serv.UserServ"&gt;  
&lt;property name="userDao"&gt;  
&lt;ref bean="userDao"/&gt;  
&lt;/property&gt;  
&lt;/bean&gt;

**Struts2 Action配置struts.xml：**  
**&lt;constant name="struts.objectFactory" value="spring"/&gt;**  
&lt;package name="default" namespace="/actions" extends="struts-default"&gt;  
&lt;action name="login" class="userAction"&gt;  
&lt;result name="success"&gt;/success.jsp&lt;/result&gt;  
&lt;result name="fail"&gt;/index.jsp&lt;/result&gt;  
&lt;/action&gt;  
&lt;/package&gt;

**Web.xml文件的配置：**  
&lt;filter&gt;  
&lt;filter-name&gt;struts2&lt;/filter-name&gt;  
&lt;filter-class&gt;org.apache.struts2.dispatcher.FilterDispatcher&lt;/filter-class&gt;  
&lt;/filter&gt;  
&lt;filter-mapping&gt;  
&lt;filter-name&gt;struts2&lt;/filter-name&gt;  
&lt;url-pattern&gt;/\*&lt;/url-pattern&gt;  
&lt;/filter-mapping&gt;

&lt;context-param&gt;  
&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;  
&lt;param-value&gt;/WEB-INF/classes/applicationContext.xml&lt;/param-value&gt;  
&lt;/context-param&gt;  
&lt;listener&gt;  
&lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;  
&lt;/listener&gt;

由于在Struts2运行时使用Spring来创建对象，需要在Struts配置文件中加入&lt;constant name="struts.objectFactory" value="spring"/&gt;，加入后如果得到下面的错误：  
严重: Exception starting filter struts2  
Cannot locate the chosen ObjectFactory implementation: spring - \[unknown location]

出现这个错误的原因是项目中少了**struts2-spring-plugin-2.1.6.jar**包，加上该包就没问题了。