struts2和spring整合时需要注意的地方

本文介绍如何将Struts2与Spring框架整合使用。主要内容包括:导入必要的依赖包commons-logging和struts2-spring-plugin;配置web.xml,设置Spring的ContextLoaderListener监听器;以及调整struts.xml配置文件,使Struts2能正确地从Spring容器中获取Bean实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、首先要记得导入依赖包:除了一些基本的包之外,还要记得导入这两个包——commons-logging和struts2-spring-plugin
commons-loggin.jar是Spring的必备包,用来记录程序运行的日志文件
(在libs文件夹下的jakarta-commons包下)
struts2-spring-plugin.jar必须要导入:作用是在struts.xml中,
每个action配置的class属性为applicationContext.xml中的bean的id属性的值,
就是靠这个包来实现查找匹配的


2、配置web.xml
1 配置监听器——org.springframework.web.context.ContextLoaderListener
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

该监听器会默认加载WebContent下的WEB-INF/applicationcontext.xml文件
我们也可以通过contextConfigLocation参数改变配置文件的路径:
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>WEB-INF/a/b/.../applicationContext.xml</param-value>
    </context-param>
     
          延伸:关于<param-value>的值——即路径:
    <!-- 如果放在WebRoot根目录,则为:applicationContext.xml和beans.xml
    如果没有放在根目录,则为  /WEB-INF/applicationContext.xml-前面加"/"+路径
    若在src下,则为  classpath:/cn/hncu/User/servlet/beans.xml-前面加"/"+路径
  -->
  如下面(两个之间用","隔开):
  <param-value>
  /WEB-INF/applicationContext.xml,
  classpath:beans.xml
  </param-value>
     
   2、对struts.xml配置文件的一个地方进行修改即可
    原来的配置文件action为:
    <action name="user" class="cn.hncu.user.userAction"></action> 
      整合的配置文件action为:
      <action name="user" class="userAction">
      --注:这里的calss从Spring容器里面拿,而不是自己new对象,
      所以这里为容器中<bean>中的id的值
      (特别注意:struts框架会从Spring容器中拿对象是依靠之前导入的struts2-spring-plugin.jar包,否则不会到Spring容器中去找,会报错说找不到userAction类)
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值