您的位置:首页 > 移动开发 > WebAPP

配置MVC模式WebApplication及应用上下文关联的方法 推荐

2009-05-23 23:19 465 查看
配置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-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>

此时可以让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>
或:
<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>
配置完成之后,即可通过WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext()在Web应用中获取WebApplicationContext引用,再进一步得到Spring配置的各个bean(context.getBean("beanName"))。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息