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.
- WebApplicationContext webApplicationContext = WebApplicationContextUtils.
getWebApplicationContext(request.getSession().getServletContext());
Therefore, you can retrieve the Web Application Context object in Servlet Context:
- 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:
- LUserService userService = (LUserService)
webApplicationContext.getBean("userService");
- Servlet Context range
- Brief Analysis on the concept of Servlet 3.0 API
- Servlet comments and deployment descriptors
- New Features of Java Servlet and Servlet 3.0
- Potential risks of Servlet and JSP