How to inject service into a servlet with spring

Source: Internet
Author: User

There are two ways to solve this problem (the second one is recommended)

Method One:

Rewrite the servlet's init () method directly, with the following code:

public void init (ServletConfig servletconfig) throws Servletexception {ServletContext ServletContext = Servletconfig.getservletcontext (); Webapplicationcontext Webapplicationcontext = Webapplicationcontextutils.getwebapplicationcontext (ServletContext) ; Autowirecapablebeanfactory autowirecapablebeanfactory = Webapplicationcontext.getautowirecapablebeanfactory (); Autowirecapablebeanfactory.configurebean (this, bean_name);}

The bean_name here are the services we need to inject into the spring container, but this is not a good approach because we need to do this in every servlet.

Method Two:

We can write a bean similar to "org.springframework.web.struts.DelegatingRequestProcessor", and then inject our service into the servlet through a configured method, The specific method is as follows,

Step 1: Write the delegate class Delegatingservletproxy

Package com.telek.pba.base.util; Import java.io.IOException; Import Javax.servlet.genericservlet;import Javax.servlet.servlet;import Javax.servlet.servletexception;import Javax.servlet.servletrequest;import Javax.servlet.ServletResponse; Import Org.springframework.web.context.webapplicationcontext;import  Org.springframework.web.context.support.WebApplicationContextUtils; /** * Below is a delegate like Org.springframework.web.struts.DelegatingRequestProcessor * For configuring the method to inject service * into the servlet @author Liyinwei * */public class Delegatingservletproxy extends genericservlet{/** * */private static final long serialversion UID = 1l;private String targetbean;private Servlet proxy; @Overridepublic void Service (ServletRequest req, servletresponse Res) throws Servletexception, IOException { Proxy.service (req, res);} /** * Initialize */public void init () throws servletexception {This.targetbean = Getservletname (); Getservletbean ();p Roxy.init ( Getservletconfig ());} /** * Get bean */private void Getservletbean () {WebapplicaTioncontext WAC = Webapplicationcontextutils.getrequiredwebapplicationcontext (Getservletcontext ()); This.proxy = ( Servlet) Wac.getbean (Targetbean);} }

Step 2: Modify the Web. XML configuration

In pure servlet mode, we configure the following methods:

<servlet>  <description> Activity Launch Module activity query paging servlet</description>  <display-name> Launchactivityqueryservlet</display>  <servlet-name>launchactivityqueryservlet</servlet-name >  <servlet-class>com.telek.pba.launch.servlet.LaunchActivityQueryServlet</servlet-class> <servlet> <servlet-mapping>  <servlet-name>LaunchActivityQueryServlet</servlet-name>  <url-pattern>/servlet/launch/LaunchActivityQueryServlet</url-pattern></servlet-mapping> </servlet>

If we use this proxy approach, the configuration should be modified to:

<servlet>  <description> Activity Launch Module activity query paging servlet</description>  <display-name> Launchactivityqueryservlet</display>  <servlet-name>launchactivityqueryservlet</servlet-name >  <servlet-class>com.telek.pba.base.util.delegatingservletproxy</servlet-class><servlet > <servlet-mapping>  <servlet-name>launchActivityQueryServlet</servlet-name>  

Note: By default, in the servlet configuration, the first letter of the launchactivityquery is generally uppercase, and we have noted in the title that we use the spring annotation pattern, and if the annotations are automatically scanned, by default, the value of the annotation is the letter lowercase , that is: launchactivityquery, so in our new configuration, be careful to change the first letter to lowercase, otherwise you will not be able to find the bean error.

Step 3: So far, we can inject the servlet like the way ssh was injected, here's a small example:

Package com.telek.pba.launch.servlet; Import java.io.IOException; Import Javax.annotation.resource;import Javax.servlet.servletexception;import Javax.servlet.http.HttpServlet; Import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.springframework.stereotype.Component; Import Com.telek.pba.base.model.pbauserinfo;import Com.telek.pba.launch.dao.IPbaActivityInfoCurrentDAO; @Componentpublic class Launchactivityqueryservlet extends HttpServlet {private static final long serialversionuid = 1L;  /injected ipbaactivityinfocurrentdao@resourceprivate Ipbaactivityinfocurrentdao Pbaactivityinfocurrentdao; /** * Constructor of the object. */public Launchactivityqueryservlet () {super ();}/** * Destruction of the servlet. <br/> */public void Destroy () {Super.destroy ();//Just puts "destroy" string in log//Put your code here}/** * Th E Doget method of the servlet. <br/> * * This method was called when a form have its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the Client * @throws servletexception If an error occurred * @throws IOException If an error occurred */public void Doget (Http ServletRequest request, HttpServletResponse response) throws Servletexception, IOException {//sth to do}/** * the doPost m Ethod of the servlet. <br/> * * This method was called when a form have its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the Client * @throws servletexception If an error occurred * @throws IOException If an error occurred */public void DoPost (HTT Pservletrequest request, HttpServletResponse response) throws Servletexception, IOException {//sth to do}/** * Initializa tion of the servlet. <br/> * * @throws servletexception If an error occurs */public void init () throws Servletexception {//Put your COD e here}}

Finally, be aware that in the spring configuration file, configure the path of the package to be automatically scanned:

<context:component-scan base-package= "Com.telek.pba.*.dao.impl, Com.telek.pba.*.service.impl, com.telek.pba.*. Servlet "></context:component>

Done!

How to inject service into a servlet with spring

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.