JavaWeb 笔记之 Spring 整合 Struts2

Spring 在 Web 应用中的使用

1. Web 应用中 IOC 容器何时创建

应该在 WEB 应用被服务器加载时就创建 IOC 容器: 即在 ServletContextListener#contextInitialized(ServletContextEvent sce) 方法中创建 IOC 容器.然后把 IOC 容器放入 ServletContxt的属性中,方便访问;同时Spring 配置文件的名字和位置应该也是可配置的! 将其配置到当前 WEB 应用的初始化参数中较为合适.

示例:

  <!-- 监听器中 IOC 容器的获取以及 放入位置 -->
  public void contextInitialized(ServletContextEvent servletContextEvent)  { 
    	
    	ServletContext servletContext = servletContextEvent.getServletContext();
    	String value = servletContext.getInitParameter("configLocation");
    	
    	ApplicationContext ctx = new ClassPathXmlApplicationContext(value);
    	servletContext.setAttribute("applicationContext", ctx);
  }
    
  <!-- web.xml 中可配置的 Spring 配置文件 -->
  <context-param>
    <param-name>configLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

2. 使用步骤

  • 需要额外加入的 jar 包:
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar
  • 需要在 web.xml 文件中加入如下配置:
!-- 配置 Spring 配置文件的名称和位置 -->
<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>classpath:applicationContext.xml</param-value>
</context-param>

<!-- 启动 IOC 容器的 ServletContextListener -->
<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

Spring 整合 Struts2

  • 整合目标:spring 的 IOC 容器管理 Struts2 的 Action
  • 整合步骤:
  1. 首先按上面方式配置 Spring 在 Web 应用中的使用
  2. 引入struts2 的 Jar 包、web,xml 中配置 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>
  1. 在 Spring 的 IOC 容器中配置 Struts2 的 Action

注意: 在 IOC 容器中配置 Struts2 的 Action 时, 需要配置 scope 属性, 其值必须为 prototype

<bean id="personAction" 
	class="com.atguigu.spring.struts2.actions.PersonAction"
	scope="prototype">
	<property name="personService" ref="personService"></property>	
</bean>
  1. 配置 Struts2 的配置文件: action 节点的 class 属性需要指向 IOC 容器中该 bean 的 id
<action name="person-save" class="personAction">
	<result>/success.jsp</result>
</action> 
  1. 加入 struts2-spring-plugin.jar 包

整合原理:

  • 通过添加 struts2-spring-plugin.jar 以后, Struts2 会先从 IOC 容器中获取 Action 的实例.
if (appContext.containsBean(beanName)) {
    o = appContext.getBean(beanName);
} else {
    Class beanClazz = getClassInstance(beanName);
    o = buildBean(beanClazz, extraContext);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值