配置MVC模式WebApplication及应用上下文关联的方法
如果用Struts框架和Spring集成来实现Controller部分,配置通常可以这样配置。
web.xml
<!--struts action config-->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value><!--config each detail action in struts rules-->
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!--struts action config-->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value><!--config each detail action in struts rules-->
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
struts-config.xml
<struts-confg>
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation" value="/WEB-INF/springContext.xml"/><!--plug-in 模式加载Spring配置文件-->
</plug-in>
</struts-config>
<struts-confg>
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation" value="/WEB-INF/springContext.xml"/><!--plug-in 模式加载Spring配置文件-->
</plug-in>
</struts-config>
此时可以让action class extends to org.springframework.web.struts.ActionSupport。
在action类里可以通常如下途径得到应用上下文,再进一步得到Spring配置的各个bean。(context.getBean("beanName"))
WebApplicationContext context = getWebApplicationContext();
如果用Spring来实现所有MVC,配置通常可以这样:
web.xml
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener<!--Lister加载-->
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener<!--Lister加载-->
</listener-class>
</listener>
或:
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet<!--Servlet加载-->
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-name>context</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet<!--Servlet加载-->
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
通过以上配置,Web容器会自动加载/WEB-INF/applicationContext.xml初始化ApplicationContext实例,如果需要指定配置文件位置,可通过context-param加以指定:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/myApplicationContext.xml</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/myApplicationContext.xml</param-value>
</context-param>
配置完成之后,即可通过WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext()在Web应用中获取WebApplicationContext引用,再进一步得到Spring配置的各个bean(context.getBean("beanName"))。
本文转自 dannyy1026 51CTO博客,原文链接:
http://blog.51cto.com/dannyyuan/160311