最近学习了Struts2,做了一个简单的登录的例子,采用SSH2进行整合。由于登录的例子挺简单,DAO层,Service层,Struts Action等文件就没有在此详细写出来,下面列出了整合时一些关键的配置:
Spring配置:
<!-- spring中配置Action,由Spring管理创建 -->
<bean id="userAction" scope="prototype" class="com.xxh.actions.UserAction">
<property name="userServ">
<ref bean="userServ"/>
</property>
</bean>
<!-- 事务配置 -->
<tx:advice id="myAdvice">
<tx:attributes>
<tx:method name="login" read-only="true"/>
</tx:attributes>
</tx:advice>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<aop:config>
<aop:pointcut id="daoPoint" expression="execution(* com.xxh.daos.*.*(..))" />
<aop:advisor advice-ref="myAdvice" pointcut-ref="daoPoint"/>
</aop:config>
<!-- DAO配置 -->
<bean id="userDao" class="com.xxh.daos.UserDao">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<!-- 业务逻辑配置 -->
<bean id="userServ" class="com.xxh.serv.UserServ">
<property name="userDao">
<ref bean="userDao"/>
</property>
</bean>
Struts2 Action配置struts.xml:
<constant name="struts.objectFactory" value="spring"/>
<package name="default" namespace="/actions" extends="struts-default">
<action name="login" class="userAction">
<result name="success">/success.jsp</result>
<result name="fail">/index.jsp</result>
</action>
</package>
Web.xml文件的配置:
<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>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
由于在Struts2运行时使用Spring来创建对象,需要在Struts配置文件中加入<constant name="struts.objectFactory" value="spring"/>,加入后如果得到下面的错误:
严重: Exception starting filter struts2
Cannot locate the chosen ObjectFactory implementation: spring - [unknown location]
出现这个错误的原因是项目中少了struts2-spring-plugin-2.1.6.jar包,加上该包就没问题了。
SSH2整合示例
最新推荐文章于 2022-03-22 11:25:37 发布