Introduction to Servlet containers and Context

Source: Internet
Author: User

The Servlet container has created many objects, such as Servlet, filter, listener, and spring. How can we use these objects?

The following describes how to use spring IOC container in Servlet, Filter, or Listener. By default, Servlet containers create spring container objects and inject them into Servlet Context, the Servlet Context object is injected into the session object, the session object is injected into the request object, and the request object is injected into the Servlet object. In fact, it is not a standard injection, but a parameter passing, or directly pay for the attribute ). Layer-by-layer dependencies can be used to obtain spring container objects.

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

Therefore, you can retrieve the Web Application Context object in Servlet Context:

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

In fact, the Web Application ContextUtils. getWebApplicationContext method is implemented using the above Code. We recommend that you use the above static method.

Note: When using web Application Context. getBean "ServiceName"), the interface must be used for forced conversion. If an implementation class is used, a type conversion error will be reported. For example:

 
 
  1. LUserService userService = (LUserService) 
    webApplicationContext.getBean("userService"); 
  1. Servlet Context range
  2. Brief Analysis on the concept of Servlet 3.0 API
  3. Servlet comments and deployment descriptors
  4. New Features of Java Servlet and Servlet 3.0
  5. Potential risks of Servlet and JSP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.