介绍Servlet容器与Context

开发 后端
本文介绍Servlet容器与Servlet Context,以及介绍强制转化要使用接口,如果使用实现类会报类型转换错误。

Servlet容器启动创建了许多对象,如Servlet,filter,listener,spring等等那么如何使用这些对象呢?

下面介绍在Servlet(或者Filter,或者Listener)中使用spring的IOC容器默认情况下Servlet容器创建spring容器对象,注入到Servlet Context中,Servlet Context对象又是注入到session对象中,session对象又是注入到request对象中,request对象又是注入到Servlet对象中,(其实不是很标准的注入,是传参数,或者对属性直接付值)。层层依赖可以得到spring容器对象。

  1. WebApplicationContext webApplicationContext = WebApplicationContextUtils.
    getWebApplicationContext(request.getSession().getServletContext());  

所以可以直接在Servlet Context取出Web Application Context对象:

  1. WebApplicationContext webApplicationContext = (WebApplicationContext) 
    servletContext.getAttribute(WebApplicationContext.
    ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);  

事实上Web Application ContextUtils.getWebApplicationContext方法就是使用上面的代码实现的,建议使用上面上面的静态方法

注意:在使用web Application Context.getBean("ServiceName")的时候,前面强制转化要使用接口,如果使用实现类会报类型转换错误。如:

  1. LUserService userService = (LUserService) 
    webApplicationContext.getBean("userService"); 

【编辑推荐】

  1. Servlet Context的范围
  2. 浅析Servlet 3.0 API的概念
  3. Servlet注释与部署描述符
  4. Java Servlet和Servlet 3.0的新特性
  5. Servlet和JSP潜在的隐患
责任编辑:佚名 来源: 中国IT实验室
相关推荐

2009-07-09 13:39:52

Servlet Con

2009-07-09 11:27:59

Servlet容器

2009-07-08 16:19:41

Servlet ConServlet Con

2009-07-08 10:12:04

Servlet Con

2022-03-31 15:17:04

JavaSocketServlet容器

2022-03-10 08:24:17

Docker容器SaaS

2009-07-09 13:04:37

Servlet接口

2009-07-09 15:30:53

Servlet容器会话跟踪

2013-09-02 09:18:59

2009-07-08 14:22:36

Servlet容器匹配过程

2009-07-08 14:01:47

Servlet容器

2009-07-07 16:23:05

Servlet容器

2009-07-07 15:24:49

Http Servle

2009-07-07 09:51:49

Servlet实例

2010-05-27 15:05:23

ServletJava

2009-07-09 13:23:44

Servlet 2.4

2009-05-18 10:43:17

TomcatServletJetty

2009-07-06 16:16:33

Servlet容器工作

2009-07-03 11:21:43

Servlet和JSPJSP路径

2009-07-07 16:05:15

Servlet和Jav
点赞
收藏

51CTO技术栈公众号