ApplicationContext是Spring的容器环境通过ApplicationContext对象可以访问所有配置的bean
在Web开发开发中常常需要从JSP或者Servlet或者Action中获取ApplicationContext对象这时候就无法使用new关键字通过查找配置文件来实例化ApplicationContext这个对象了Spring通过WebApplicationContextUtils可以方便实现您的需求下面看个例子
一Spring+Struts环境下
配置webxml通过这个配置来获取的
<?xml version= encoding=UTF?>
<webapp xmlns=
xmlns:xsi=instance
xsi:schemaLocation=
app__xsd
version=>
<contextparam>
<paramname>contextConfigLocation</paramname>
<paramvalue>/WEBINF/applicationContextxml</paramvalue>
</contextparam>
<filter>
<filtername>struts</filtername>
<filterclass>orgapachestrutsdispatcherFilterDispatcher</filterclass>
</filter>
<filtermapping>
<filtername>struts</filtername>
<urlpattern>/*</urlpattern>
</filtermapping>
<listener>
<listenerclass>orgsprntextContextLoaderListener</listenerclass>
</listener>
<servlet>
<servletname>dispatcher</servletname>
<servletclass>orgspringframeworkwebservletDispatcherServlet</servletclass>
<loadonstartup></loadonstartup>
</servlet>
<servletmapping>
<servletname>dispatcher</servletname>
<urlpattern>*form</urlpattern>
</servletmapping>
</webapp>
在JSPServletAction中获取ApplicationContext
<%@ page import=lavasoftserviceTestService %>
<%@ page import=orgntextApplicationContext %>
<%@ page import=orgsprntextsupportWebApplicationContextUtils %>
<%@ page contentType=text/html;charset=UTF language=java %>
<html>
<head><title>Simple jsp page</title></head>
<body>
<%
//ApplicationContext ctx = WebApplicationContextUtilsgetWebApplicationContext(requestgetSession()getServletContext());
ApplicationContext ctx = WebApplicationContextUtilsgetWebApplicationContext(sessiongetServletContext());
TestService service = (TestService) ctxgetBean(testService);
String s = servicetest();
outprint(s);
%>
</body>
</html>
二Spring+JSP的环境
在此环境下webxml配置会有些变化
<?xml version= encoding=UTF?>
<webapp xmlns=
xmlns:xsi=instance
xsi:schemaLocation=
app__xsd
version=>
<contextparam>
<paramname>contextConfigLocation</paramname>
<paramvalue>/WEBINF/applicationContextxml</paramvalue>
</contextparam>
<listener>
<listenerclass>orgsprntextContextLoaderListener</listenerclass>
</listener>
<servlet>
<servletname>dispatcher</servletname>
<servletclass>orgspringframeworkwebservletDispatcherServlet</servletclass>
<loadonstartup></loadonstartup>
</servlet>
<servletmapping>
<servletname>dispatcher</servletname>
<urlpattern>*form</urlpattern>
</servletmapping>
</webapp>
获取的方式和上述完全一样
下面给出本例子的工程源码参看附件
下载附件
testspringweb
testspringweb