Spring MVC Dispatcherservlet

Source: Internet
Author: User

    • Dispatcherservlet UML Diagram

This analysis: Httpservlet->httpservletbean->framworkservlet->dispacherservlet

  • What is ServletContext?
    ServletContext, is a global storage space for information, the server starts, it exists, the server shuts down, and it is released. Request, one user can have multiple; session, one user; ServletContext, all users share one. Therefore, in order to save space and improve efficiency, in servletcontext, it is necessary to put the required, important, all users need to share the thread is a security of some information.

  • What is Webapplicationcontext?
    As the name implies, Webapplicationcontext is a spring IOC container that relies on the Web container. The prerequisite is that the container starts after the Web container is started. So how do you start the context of the spring Web with a Web container?

  • Httpservletbean class

    Public final void Init () throws Servletexception {if (this.logger.isDebugEnabled ()) {This.logger.debug ("Initial    Izing servlet ' "+ this.getservletname () +" ' "); }//Set the servlet initialization parameter to the component propertyvalues PVs = new Httpservletbean.servletconfigpropertyvalues (This.getservletconfig (    ), this.requiredproperties);            if (!pvs.isempty ()) {try {beanwrapper bw = propertyaccessorfactory.forbeanpropertyaccess (this);            Resourceloader Resourceloader = new Servletcontextresourceloader (This.getservletcontext ());            Bw.registercustomeditor (Resource.class, New Resourceeditor (Resourceloader, This.getenvironment ()));            This.initbeanwrapper (BW);        Bw.setpropertyvalues (PVs, true); } catch (Beansexception var4) {if (this.logger.isErrorEnabled ()) {This.logger.error ("Failed to            Set bean properties on servlet ' "+ this.getservletname () +" ' ", VAR4);        } throw VAR4; }}//give subclass initialFrameworkservlet, the method of sub-class covering This.initservletbean (); if (this.logger.isDebugEnabled ()) {This.logger.debug ("Servlet" + this.getservletname () + "' configured successful    Ly "); }}
  • Frameworkservlet class

     protected final void initServletBean() throws ServletException {        //省略        //        try {            //初始化web上下文            this.webApplicationContext = this.initWebApplicationContext();            //初始化            this.initFrameworkServlet();        }                 //省略
    Protected Webapplicationcontext Initwebapplicationcontext () {Webapplicationcontext Rootcontext =        Webapplicationcontextutils.getwebapplicationcontext (Getservletcontext ());        Webapplicationcontext WAC = null;            if (this.webapplicationcontext! = null) {//build and inject a context instance WAC = This.webapplicationcontext; if (WAC instanceof Configurablewebapplicationcontext) {Configurablewebapplicationcontext CWAC = (Config                Urablewebapplicationcontext) WAC;                    if (!cwac.isactive ()) {//the context has not yet been refreshed, provide services such as Setting the parent context, setting the application context ID, etc if (cwac.getparent (                        ) = = null) {//The context instance is injected without an explicit parent, set                  The root application context (if any; could be null) as the parent      Cwac.setparent (Rootcontext);                } configureandrefreshwebapplicationcontext (CWAC);        }}} if (WAC = = null) {//Find already bound context WAC = Findwebapplicationcontext (); } if (WAC = = null) {//No context instance is defined-this servlet--create a local one means        Set to Contextloaderlistener WAC = Createwebapplicationcontext (Rootcontext); } if (!this.refresheventreceived) {//Either the context is not a configurableapplicationcontext with R Efresh//Support or the context injected at construction time had already been//refreshed-T            Rigger initial Onrefresh manually here.        Onrefresh (WAC);            } if (This.publishcontext) {//Publish the context as a servlet context attribute.            String attrname = Getservletcontextattributename (); Getservletcontext (). SetAttribute (Attrname, WAC); if (this.logger.isDebugEnabled ()) {This.logger.debug ("Published Webapplicationcontext of servlet '" + GetS            Ervletname () + "' as ServletContext attribute with name [" + Attrname + "]");    }} return WAC; }

As can be seen from the Initwebapplicationcontext () method, basically if Contextloaderlistener loads the context as the root context (Dispatcherservlet's parent container).

    • Dispatcherservlet class
      ```
      **
      • This implementation calls {@link #initStrategies}.
        */
        @Override
        The WAC in Frameworkservlet
        protected void Onrefresh (ApplicationContext context) {
        Initstrategies (context);
        }
      /**
      • Initialize the strategy objects that this servlet uses.
      • May is overridden in subclasses on order to initialize further strategy objects.
        */
        protected void Initstrategies (ApplicationContext context) {
        Initmultipartresolver (context);
        Initlocaleresolver (context);
        Initthemeresolver (context);
        Take two types of beans out of the context
        Inithandlermappings (context);
        Inithandleradapters (context);
        Inithandlerexceptionresolvers (context);
        Initrequesttoviewnametranslator (context);
        Initviewresolvers (context);
        Initflashmapmanager (context);
        }

doDispatch
protected void Dodispatch (HttpServletRequest request, httpservletresponse response) throws Exception {//omit ... try {            Omit ... try {processedrequest = Checkmultipart (request);            multipartrequestparsed = (processedrequest! = Request);            Determine handler for the current request.            Mappedhandler = GetHandler (processedrequest); if (Mappedhandler = = NULL | | Mappedhandler.gethandler () = = null) {Nohandlerfound (processedrequest, respons                e);            Return            }//Determine handler adapter for the current request.            Handleradapter ha = Gethandleradapter (Mappedhandler.gethandler ());            Process last-modified Header, if supported by the handler.            String method = Request.getmethod ();            Boolean isget = "GET". Equals (method); if (Isget | | "HEAD". Equals (method)) {Long lastmodified = ha.getlastmodified (Request, MAPPEDHANDLER.GEthandler ()); if (logger.isdebugenabled ()) {Logger.debug ("last-modified value for [" + Getrequesturi (Request) + "] I                S: "+ lastmodified);                    } if (new Servletwebrequest (request, Response). Checknotmodified (lastmodified) && isget) {                Return                }}//Call all interceptors for Prehandle if (!mappedhandler.applyprehandle (processedrequest, response)) {            Return            }//actually invoke the handler.            MV = Ha.handle (processedrequest, Response, Mappedhandler.gethandler ());            if (asyncmanager.isconcurrenthandlingstarted ()) {return;            } applydefaultviewname (Processedrequest, MV);        Invoke the Posthandle method of all interceptors registered Mappedhandler.applyposthandle (processedrequest, response, MV); }//Omit ...//render draw mv Processdispatchresult (Processedrequest, Response, MAppedhandler, MV, dispatchexception); }//Omit ... finally {if (asyncmanager.isconcurrenthandlingstarted ()) {//Instead of Postha Ndle and Aftercompletion if (mappedhandler! = null) {mappedhandler.applyafterconcurrenthandling            Started (processedrequest, response); }}//Omit ...}}

```
1. When the container starts, locate the Context-param in the configuration file as the key-value pair in the ServletContext
2. Then locate the listener, and the container invokes its contextinitialized (Servletcontextevent event) method to perform the operation
3.spring provides us with a context initialization listener that implements the Servletcontextlistener interface: Contextloaderlistener

4.spring provides us with an IOC container that requires us to specify the container's configuration file, which is then initialized and created by the listener. Requires you to specify the address and file name of the configuration file, be sure to use: Contextconfiglocation as the parameter name.

    • What is initialized after the spring context container is configured

1. The servlet container starts and creates a "global context" for the application: ServletContext
2. The container invokes the Contextloaderlistener configured in Web. XML, initializes the Webapplicationcontext context (that is, the IOC container), loads the Context-param specified profile information into the IOC container. Webapplicationcontext is saved as a key-value pair in ServletContext
3. The container initializes the servlet configured in Web. XML, initializes its own context information servletcontext, and loads the configuration information for its settings into that context. Sets the Webapplicationcontext to its parent container.
4. All subsequent servlet initializations are created in 3 steps, initializing their own context and setting Webapplicationcontext to their parent context.

Spring MVC Dispatcherservlet

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.