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
- 整合步骤:
- 首先按上面方式配置 Spring 在 Web 应用中的使用
- 引入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>
- 在 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>
- 配置 Struts2 的配置文件: action 节点的 class 属性需要指向 IOC 容器中该 bean 的 id
<action name="person-save" class="personAction">
<result>/success.jsp</result>
</action>
- 加入 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);
}