在普通web项目的servlet和filter中获取spring上下文
来源:互联网 发布:2017药品中标数据目录 编辑:程序博客网 时间:2024/05/01 03:00
文章来源:http://blog.csdn.net/zhiweiv/archive/2008/10/21/3118857.aspx
之前一直是在web项目中使用struts2然后通过plugin集成spring,action生成的细节全部由plugin实现了,对于我们是透明的。过几天学校留个作业只能用普通的jsp+servlet做,之前一直是透明的使用spring,对spring的初始化及bean的获取一直没什么概念。这回正好用的上,就研究了一下ContextLoaderListener ContextLoader和StrutsSpringObjectFactory的源码。经过一番阅读对spring的初始化和获取bean有了一些印象。
在spring中的org.springframework.beans.factory.BeanFactory接口getBean(String id)用来获取spring管理的bean。而我们一般使用实现了该接口的ApplicationContext接口。所以只要我们在servlet中取得了ApplicationContext接口的实现类,就可以获取spring管理的bean了。
首先是在web.xml中配置listener
- <listener>
- <listener-class>
- org.springframework.web.context.ContextLoaderListener
- </listener-class>
- </listener>
- //实例化一个ContextLoader,然后调用它的initWebApplicationContext方法
- public void contextInitialized(ServletContextEvent event) {
- this.contextLoader = createContextLoader();
- this.contextLoader.initWebApplicationContext(event.getServletContext());
- }
- protected ContextLoader createContextLoader() {
- return new ContextLoader();
- }
Servlet
。它的大概意思就是这个方法通过ContextLoaderListener获取WebApplicationContext。所以在servlet中就可以通过如下方法实现获取spring上下文
- import javax.servlet.http.HttpServlet;
- import org.springframework.context.ApplicationContext;
- import org.springframework.web.context.support.WebApplicationContextUtils;
- public class NewServlet extends HttpServlet {
- public ApplicationContext getApplicationContext(){
- return WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
- }
- }
使用方法
- public void test(){
- TestBean testBean=(TestBean)this.getApplicationContext().getBean("testBean");
- }
在filter里面server会给它注入一个FilterConfig对象,在filter里可以使用FilterConfig的filterConfig.getServletContext()方法获取servlet上下文,所以在filter里获取spring的上下文方法如下
- public ApplicationContext getApplicationContext() {
- return WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
- }
- 在普通web项目的servlet和filter中获取spring上下文
- web项目的servlet和filter中获取spring上下文
- 在web项目中获取spring上下文
- 在SpringMVC的Controller中获取spring上下文和springMVC上下文
- 在servlet、filter、Taglib中获取Spring Bean
- 在web项目中获取ApplicationContext上下文的3种主要方式及适用情况
- 普通类获取spring上下文
- Servlet,Listener和Filter 获取ServletContext (application上下文环境)
- web应用中获取spring上下文的方法
- web项目中简单的管理spring的上下文
- web.xml中servlet, spring, filter, listenr的配置
- Filter或Servlet中获取Spring Bean的方法
- 在spring项目的普通java类中获取service或dao
- spring在普通类中获取session和request,springsession
- 在servlet中或者在filter中获取spring容器中的bean
- 在Servlet Filter中使用Spring容器
- 在Servlet Filter中使用Spring容器
- 【N转ITeye】java项目中相对路径的获取(普通项目和web项目均有)
- 一个实用垃圾清除的批处理
- 消息队列
- 网站用户单点登陆解决方案
- 自己从程序中创建位图,然后将其显示出来
- SQL注入批量更新语句
- 在普通web项目的servlet和filter中获取spring上下文
- Servlet中的Listener
- Servlet和Filter的url匹配以及url-pattern详解
- 关于src源文件在web-inf目录下的部署问题
- JSP中的Cookie
- Cookie跨域操作
- Grails-学习资料汇总
- javascript浏览器兼容性(不断更新中)
- 我的读书