欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

介绍Servlet容器与Context

来源: javaer 分享于  点击 18769 次 点评:272

介绍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潜在的隐患

相关栏目:

用户点评