Struts2与Spring的整合

今天倒腾了半天,终于是把这个两个框架整合到一起了。还是要写一下总结,同时给大家一些帮助。

开发环境:myeclipse 9.0(不好用!)tomcat6.0

1.准备工作

需要导入的包:struts2与spring基本的包就不用说了,我用的是struts2.1  Spring 3.0,

尤其要注意 别少导入的几个是:Spring3.0 Web Libraries  ;

struts支持spring的插件:struts2-spring-plugin-2.1.8.1.jar  将这个jar文件放到lib目录下

2.web.xml 的配置

除了struts2的核心配置外,我们还要加入spring的配置,代码如下:

<!--指明spring配置文件的位置!-->

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath*:applicationContext*.xml</param-value>

</context-param>

<!-加载spring的配置文件!-->

<listener>

<listener-class>

org.springframework.web.context.ContextLoaderListener

</listener-class>

</listener>

注:如果你在运行的时候发现有no found class org.springframework.web.context.LoaderListener 的异常 ,那你要注意你的Spring3.0 Web 包的导入了

3.application.xml 的配置

<beans>

<bean id="userService" class="com.test.service.UserServiceImpl"></bean>

<bean id="userAction" class="com.test.action.UserAction">

       <property name="userService">

         <ref bean="userService"/>

      </property>

</bean>

</beans>

4.UserAction 类 这个不用多说,注意的是userService 属性的getter 和 setter 方法

public class UserAction {

     private User user = new User();

     public User getUser() {

         return user;

     }

 public void setUser(User user) {

         this.user = user;

     }          

private UserService userService;          

public UserService getUserService()

{         

           return userService;

 }     

public void setUserService(UserService userService)

{

         this.userService = userService;

 }

     public String checkLogin(){

         if(userService.checkLogin(user))

         {

                 System.out.println("ok");

         }

           else   

             System.out.println("sorry");  

                     return "succ";

     }

}

5.struts.xml 的配置,把原先class的路径换成spring中配置action的bean 的id

<struts> <package name="test" extends="struts-default">  

    <action name="login" class="userAction" method="checkLogin">

         <result name="succ">index.jsp</result>

     </action>

</package>

</struts>   

原文地址:https://www.cnblogs.com/jameslif/p/3489475.html