Spring MVC Holistic Processing process

Source: Internet
Author: User
Tags mutex

I. Spring's overall structure

First look at the overall structure of spring MVC

Two. Processing process

1. The first stop to request processing is dispatcherservlet. It is the control core of the entire spring MVC. Like most Java Web Frameworks, all of spring MVC's requests go through a core front-end controller (Servlet). Dispatcherservlet maps each request to a handler through one or more handler mappings. The handler mapping is configured in the context of the Web application and is the bean that implements the Handlermapping interface. It is responsible for returning an appropriate handler (that is, controller) for the request. Handler mappings typically map requests to handlers (controllers) based on the URL of the request.

The Handlermappings assembly has been completed before the beginning of the dispatcher.

1      Public void setdetectallhandlermappings (boolean  detectallhandlermappings) {2         this. detectallhandlermappings = detectallhandlermappings; 3     }

Match the available handlermapping in handlermappings

1 protectedHandlerexecutionchain GetHandler (HttpServletRequest request)throwsException {2          for(Handlermapping HM: This. Handlermappings) {3             if(logger.istraceenabled ()) {4 Logger.trace (5"Testing handler Map [" + HM + "] in Dispatcherservlet with Name '" + getservletname () + "'");6             }7Handlerexecutionchain handler =Hm.gethandler (request);8             if(Handler! =NULL) {9                 returnhandler;Ten             } One         } A         return NULL; -}

Get handler

1      Public FinalHandlerexecutionchain GetHandler (HttpServletRequest request)throwsException {2Object handler = gethandlerinternal(request);3         if(Handler = =NULL) {4Handler =Getdefaulthandler ();5         }6         if(Handler = =NULL) {7             return NULL;8         }9         //Bean name or resolved handler?Ten         if(HandlerinstanceofString) { OneString HandlerName =(String) handler; AHandler =Getapplicationcontext (). Getbean (handlerName); -         } -  theHandlerexecutionchain Executionchain =Gethandlerexecutionchain (handler, request); -         if(Corsutils.iscorsrequest (Request)) { -Corsconfiguration GlobalConfig = This. corsconfigsource.getcorsconfiguration (request); -Corsconfiguration Handlerconfig =getcorsconfiguration (handler, request); +corsconfiguration config = (GlobalConfig! =NULL?Globalconfig.combine (handlerconfig): handlerconfig); -Executionchain =Getcorshandlerexecutionchain (Request, Executionchain, config); +         } A         returnExecutionchain; at}

  

2. Once the Dispatcherservlet chooses the appropriate controller, it calls the controller to process the request.

1 protectedModelandview handleinternal (httpservletrequest request,2HttpServletResponse response, Handlermethod Handlermethod)throwsException {3 4 checkrequest (request);5 6         if(Getsessionattributeshandler (Handlermethod). Hassessionattributes ()) {7Applycacheseconds (Response, This. cachesecondsforsessionattributehandlers);8         }9         Else {Ten Prepareresponse (response); One         } A  -         //Execute Invokehandlermethod in synchronized block if required. -         if( This. Synchronizeonsession) { theHttpSession session = Request.getsession (false); -             if(Session! =NULL) { -Object Mutex =Webutils.getsessionmutex (session); -                 synchronized(mutex) { +                     returnInvokehandlermethod (Request, response, Handlermethod); -                 } +             } A         } at  -         returnInvokehandlermethod (Request, response, Handlermethod); -}
View Code

Returns a Modelandview object that contains the requested view

  Return Getmodelandview (Mavcontainer, Modelfactory, webRequest);

3. When the controller finishes processing the request, the model and view name (sometimes the View object) is returned to Dispatcherservlet. The model contains the properties that the controller will pass to the view for display. If the name of the view is returned, it is parsed into the view object and then rendered. The basic class for binding models and views is modelandview 
4. When Dispatcherservlet receives the model and view name, it resolves the logical view name into the View object and renders it. Dispatcherservlet parses a view from one or more view parsers. The view resolver is configured in the context of the Web application and is the bean that implements the Viewresolver interface. Its task is to return the attempted object based on the logical view name.  

 protected  View resolveviewname (String viewName, map<string, object>  model, locale locale, httpservletrequest request)  throws   Exception { for  (Viewresolver viewresolv ER: this  .viewresolvers) {view View             = Viewresolver.resolveviewname (viewName, locale);  if  (view! = null   return   view; }}  return  null  ; }

5. Once dispatcherservlet the view name resolution as an attempted object, it renders the view object and passes the model returned by the controller. The task of the view is to present the model properties to the user.

  

1     protectedhttpservletrequest getrequesttoexpose (httpservletrequest originalrequest) {2         if( This. exposecontextbeansasattributes | | This. exposedcontextbeannames! =NULL) {3             return NewContextexposinghttpservletrequest (4OriginalRequest, Getwebapplicationcontext (), This. exposedcontextbeannames);5         }6         returnoriginalrequest;7}

Interpretation of the processing flow for the first diagram

Spring Workflow Description1. The user sends the request to the server, the request is captured by the spring front-end control Servelt dispatcherservlet; 2. Dispatcherservlet parses the request URL to get the request Resource Identifier (URI). Then, according to the URI, call handlermapping to obtain all related objects of the handler configuration (including handler objects and the interceptor corresponding to the handler object), and finally return as Handlerexecutionchain objects; 3. Dispatcherservlet according to the obtained handler, choose a suitable handleradapter. ( Notes: If the handleradapter is successfully obtained, the Prehandler (...) of the interceptor will start executing at this time.  METHOD) 4. Extract the model data from the request, populate the handler entry, and start executing the handler (Controller). In the process of populating the handler, depending on your configuration, spring will do some extra work for you: Httpmessageconveter: Converts the request message (such as JSON, XML, and so on) to an object, converting the object to the specified response Information Data transformation: Yes, Request a message for data conversion. such as string conversion to Integer, double, and other data is radical: The request message is formatted data.  Data validation such as converting a string to a formatted number or a formatted date: Verifies the validity of the data (length, format, and so on), and the validation results are stored in Bindingresult or error 5.  Handler returns a Modelandview object to Dispatcherservlet after execution is complete; 6. Based on the returned Modelandview, select a suitable viewresolver (must be viewresolver already registered in the spring container) to return to Dispatcherservlet; 7. The Viewresolver combines model and view to render view 8. Returns the rendered result to the client.

Spring MVC Holistic Processing process

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.