[Spring] Inject spring bean, servlet container and spring container into servlet

Source: Internet
Author: User

1. servlet container

The entire servlet lifecycle seems to be handled by the servlet container.

If you place it in a spring container for creation, the servlet object can be created by the spring container, but the servlet container may not know that the servlet exists because it is not in its container.

Therefore, the servlet should be handed over to the Web server and not to spring for management.

 

2. Let servlet context load spring context. servlet uses the object/bean in spring Context

In Web applications that use spring containers, dependencies between business objects can be configured with spring-context.xml files, and spring containers are responsible for the creation of dependent objects.

To use spring containers in servlet to manage business objects, you usually need to use webapplicationcontextutils. getrequiredwebapplicationcontext (getservletcontext () to obtain the webapplicationcontext, and then call webapplicationcontext. getbean ("beanname") is used to obtain the object reference. In fact, dependency lookup is used to obtain the object, and the bean name of the Application object is hardcoded In the servlet code.

In this way, the bean in the spring container is loaded into the servlet container, that is, the bean in spring is put into the bean of Web. xml.

 

3. Make servlet aware of bean in spring

To perceive bean in spring in servlet, follow these steps:

1-define Servlet as bean in the spring-context.xml file and put it together with the bean definition to be applied;

2-implement a proxy servlet that uses webapplicationcontext to get the servlet object defined in the spring-context.xml and delegate the task to the servlet defined in the spring-context.xml

3-use contextloaderlistener in Web. XML to initialize the context of spring, and use initialization parameters in the definition of proxy servlet to define the bean name of servlet in the spring-context.xml.

4-define the ing of the proxy servlet in Web. xml.

In this way, the dependencies between Servlet and business objects are managed using spring, and the object name to be referenced is not hardcoded In the servlet.

 

Iv. Sample Code

Web. xml

<! -- The definition of the root spring container shared by all servlets and filters --> <! -- To allow spring to load configuration files other than znserver-servlet, servlet listener contextloaderlistener --> <context-param> <param-Name> contextconfiglocation </param-Name> <param-value>/WEB-INF/server-servlet.xml/WEB-INF </Param -value> </context-param> <! -- Creates the spring container shared by all servlets and filters --> <! -- Used together with the above, load the spring container to separate the beans unavailable to the local Java program from the locally available ones and put them in different configuration files, to run the local Java program --> <listener-class> Org. springframework. web. context. contextloaderlistener </listener-class> </listener> <! -- Processes application requests --> <! -- Process application requests,/APP /.. next --> <servlet-Name> appservlet </servlet-Name> <servlet-class> Org. springframework. web. servlet. dispatcherservlet </servlet-class> <init-param> <param-Name> contextconfiglocation </param-Name> <param-value>/WEB-INF/server-bean.xml </param-value> <! -- Beans in the server-bean.xml that require URL Processing, for example, Controller --> </init-param> <load-on-startup> 1 </load-on-startup> </servlet> <servlet-mapping> <servlet-Name> appservlet </servlet-Name> <URL-pattern>/</url-pattern> </servlet-mapping> <! -- Start initialservlet, initialize the application and several important objects --> <servlet> <description> </description> <display-Name> proxyservlet </display-Name> <servlet-Name> proxyservlet </servlet- name> <servlet-class> Org. ccnt. med. common. delegatingservletproxy </servlet-class> <load-on-startup> 2 </load-on-startup> </servlet> <servlet-mapping> <servlet-Name> proxyservlet </ servlet-Name> <URL-pattern>/proxyservlet </url-pattern> </servlet-mapping>

Server-servlet.xml

<bean id="proxyServlet" class="org.ccnt.med.common.ProxyServlet"/>

Delegatingservletproxy. Java

public class DelegatingServletProxy extends GenericServlet {    private String targetBean;    private Servlet proxy;        @Override    public void service(ServletRequest arg0, ServletResponse arg1)            throws ServletException, IOException {        proxy.service(arg0, arg1);    }    @Override    public void init() throws ServletException {        this.targetBean = getServletName();        getServletBean();        proxy.init(getServletConfig());    }        private void getServletBean() {        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());        this.proxy = (Servlet)wac.getBean(targetBean);//get proxyBean    }}

Proxyservlet. Java

public class ProxyServlet extends HttpServlet{        private Logger logger = LoggerFactory.getLogger(ProxyServlet.class);        @Autowired    private QueryService queryService;    public void setQueryService(QueryService queryService)    {        this.queryService = queryService;    }        private static final long serialVersionUID = 1L;        /**     * @see HttpServlet#HttpServlet()     */    public ProxyServlet() {        super();    }        /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)     */    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {            }    /**     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)     */    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub    }    @Override    public void init(ServletConfig config) throws ServletException {        logger.info("~~~START~~~");    }    }

 

V. Summary

After all the configurations are completed, you can use spring MVC with peace of mind. Recall the process:

1. Set spring listener in Web. XML to import spring-context.xml.

Configure the delegatingservletproxy Servlet

2. Configure bean proxyservlet in the spring-context.xml

3. In delegatingservletproxy. Java, set the proxy servlet-proxyservlet

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.