实际开发中,项目多数会选择使用Spring整合Struts2框架。对于使用Spring框架的Web应用,我们不能手动创建Spring容器,而是通过配置文件,声明式地创建Spring容器。为了让Spring容器随着Web应用的启动而自动地创建起来,可以借助于ServletContextListener监听器完成,该监听器可以在Web应用启动时回调自定义方法从而创建Spring容器。
Spring提供了一个ContextLoaderListener,该监听器类实现了ServletContextListener接口,可以作为监听器使用。那么该监听器类的回调方法根据什么东西创建Spring容器呢?答案当然是Spring的配置文件。如果有多个配置文件需要载入,考虑使用<context-param.../>元素来确定配置文件。ContextLoaderListener加载时,会查找名为contextConfigLocation的初始化参数,因此配置<context-param.../>时应指定参数名为contextConfigLocation。参数值为Spring的多个配置文件,文件之间以逗号隔开。
Spring根据指定配置文件创建WebApplicationContext对象,并将其保存在Web应用的ServletContext中。如果要获得Spring容器对象,可以通过如下代码:
WebApplicationContext ctx=
WebApplicationContextUtils.getWebApplicationContext(servletContext);
web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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>
</web-app>
index.jsp :
<body>
<a href="test">点击我</a>
</body>
ok.jsp :
<body>
操作成功,已获得Spring容器实例,控制台已经输出了容器对象...
</body>
struts.xml :
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<package name="demo" extends="struts-default">
<action name="test" class="com.action.TestAction">
<result>/ok.jsp</result>
</action>
</package>
</struts>
TestAction.java :
public class TestAction extends ActionSupport {
@Override
public String execute() throws Exception {
ServletContext servletContext=ServletActionContext.getServletContext();
WebApplicationContext ctx=
WebApplicationContextUtils.getWebApplicationContext(servletContext);
System.out.println(ctx);
return "success";
}
}
控制台输出:
如果将Spring的配置文件放在WEB-INF目录下:
则修改web.xml的<param-value>的值为:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/beans.xml</param-value>
</context-param>