Spring Source code reading: How does Spring MVC process HTTP requests?

Source: Internet
Author: User

Spring Source code reading: How does Spring MVC process HTTP requests?
Through reading the source code, Spring MVC can understand the initial process of ApplicationContext and the initialization process of Spring MVC, today, let's take a look at how SpringMVC processes HTTP requests. HTTP requests can be divided into GET, POST, PUT, DELETE, OPTIONS, and TRACE based on the request method. The most common ones are GET and POST. Spring uses processRequest (req, rep) for processing these HTTP requests; copies the code @ Override protected final void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {processRequest (request, response);}/*** Delegate POST requests to {@ link # processRequest }. * @ see # doService */@ Override protected final void doPost (HttpServletRequest request, HttpServletResponse response) t Hrows ServletException, IOException {processRequest (request, response);} copy the Code and in the processRequest method, we can see that the request is processed by a doService (). Copy the code/*** Exposes the DispatcherServlet-specific request attributes and delegates to {@ link # doDispatch} * for the actual dispatching. * // @ Override protected void doService (HttpServletRequest request, HttpServletResponse response) throws Exception {if (logger. isDebugEnabled () {String requestUri = urlPathHelper. getRequestUri (request); logger. debug ("DispatcherServlet with name'" + getServletNam E () + "'processing" + request. getMethod () + "request for [" + requestUri + "]");} // Keep a snapshot of the request attributes in case of an include, // to be able to restore the original attributes after the include. map <String, Object> attributesSnapshot = null; if (WebUtils. isIncludeRequest (request) {logger. debug ("Taking snapshot of request attributes before include"); attributesSnapshot = New HashMap <String, Object> (); Enumeration attrNames = request. getAttributeNames (); while (attrNames. hasMoreElements () {String attrName = (String) attrNames. nextElement (); if (this. cleanupAfterInclude | attrName. startsWith ("org. springframework. web. servlet ") {attributesSnapshot. put (attrName, request. getAttribute (attrName) ;}}// Make framework objects available to handlers and view objec Ts. request. setAttribute (WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext (); request. setAttribute (LOCALE_RESOLVER_ATTRIBUTE, this. localeResolver); request. setAttribute (THEME_RESOLVER_ATTRIBUTE, this. themeResolver); request. setAttribute (THEME_SOURCE_ATTRIBUTE, getThemeSource (); try {doDispatch (request, response);} finally {// Restore the original attribute snapshot, in case of an in Clude. if (attributesSnapshot! = Null) {restoreAttributesAfterInclude (request, attributesSnapshot) ;}} copy the code doDispatch: copy the code/*** Process the actual dispatching to the handler. * <p> The handler will be obtained by applying the servlet's HandlerMappings in order. * The HandlerAdapter will be obtained by querying the servlet's installed HandlerAdapters * to find the first that supports the handler class. * <p> All HTTP methods Are handled by this method. it's up to HandlerAdapters or handlers * themselves to decide which methods are acceptable. * @ param request current HTTP request * @ param response current HTTP response * @ throws Exception in case of any kind of processing failure */protected void doDispatch (HttpServletRequest request, HttpServletResponse response) throws Exception {HttpServletRequest processedReques T = request; HandlerExecutionChain mappedHandler = null; int interceptorIndex =-1; try {ModelAndView mv; boolean errorView = false; try {// check whether it is a file upload request, if a file upload request is sent, the request is converted to a subclass encapsulated in Spring: DefaultMultipartHttpServletRequest. The encapsulated class cannot obtain non-file form fields, you need to understand the code design of this part. ProcessedRequest = checkMultipart (request); // Determine handler for the current request. mappedHandler = getHandler (processedRequest, false); if (mappedHandler = null | mappedHandler. getHandler () = null) {noHandlerFound (processedRequest, response); return;} // Determine handler adapter for the current request. // The adapter mode 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 () {String requestUri = urlPathHelper. getRequestUri (request); logger. debug ("Last-Modified value for [" + requestUri + "] I S: "+ lastModified);} if (new ServletWebRequest (request, response ). checkNotModified (lastModified) & isGet) {return ;}// similar to Struts2, the interceptor is also used to append HTTP requests. // Apply preHandle methods of registered interceptors. handlerInterceptor [] interceptors = mappedHandler. getInterceptors (); if (interceptors! = Null) {for (int I = 0; I <interceptors. length; I ++) {HandlerInterceptor interceptor = interceptors [I]; if (! Interceptor. preHandle (processedRequest, response, mappedHandler. getHandler () {triggerAfterCompletion (mappedHandler, interceptorIndex, processedRequest, response, null); return;} interceptorIndex = I ;}} // call your action Code // Actually invoke the handler. mv = ha. handle (processedRequest, response, mappedHandler. getHandler (); // obtain the view name based on the model view. // Do we need view name translation? If (mv! = Null &&! Mv. hasView () {mv. setViewName (getdefaviewviewname (request);} // post processing of the interceptor // Apply postHandle methods of registered interceptors. if (interceptors! = Null) {for (int I = interceptors. length-1; I> = 0; I --) {HandlerInterceptor interceptor = interceptors [I]; interceptor. postHandle (processedRequest, response, mappedHandler. getHandler (), mv) ;}} catch (ModelAndViewDefiningException ex) {logger. debug ("ModelAndViewDefiningException encountered", ex); mv = ex. getModelAndView ();} catch (Exception ex) {Object handler = (mappedHandler! = Null? MappedHandler. getHandler (): null); mv = processHandlerException (processedRequest, response, handler, ex); errorView = (mv! = Null);} // render the page // Did the handler return a view to render? If (mv! = Null &&! Mv. wasCleared () {render (mv, processedRequest, response); if (errorView) {WebUtils. clearErrorRequestAttributes (request) ;}} else {if (logger. isDebugEnabled () {logger. debug ("Null ModelAndView returned to DispatcherServlet with name'" + getServletName () + "': assuming HandlerAdapter completed request handling");} // Trigger after-completion for successful outcome. triggerAfterCompletion (map PedHandler, interceptorIndex, processedRequest, response, null);} catch (Exception ex) {// Trigger after-completion for thrown exception. triggerAfterCompletion (mappedHandler, interceptorIndex, processedRequest, response, ex); throw ex;} catch (Error err) {ServletException ex = new handle ("Handler processing failed", err ); // Trigger after-completion for thrown exception. trigg ErAfterCompletion (mappedHandler, interceptorIndex, processedRequest, response, ex); throw ex;} finally {// clear the temporary file in the file upload request // Clean up any resources used by a multipart request. if (processedRequest! = Request) {cleanupMultipart (processedRequest) ;}} copy the code in the Process of processing the request above: it involves the interceptor and adapter mode. The benefits of using the interceptor are not mentioned in the previous blogs. Here, I would like to briefly introduce the advantages of using the video companion mode. In the above code, the code for using the adapter is: // Actually invoke the handler. mv = ha. handle (processedRequest, response, mappedHandler. getHandler ());

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.