SPRINGMVC Source Code Analysis-Handlermethod

Source: Internet
Author: User

Handlermethod and subclasses are primarily used to encapsulate information about method invocations, and subclasses also provide responsibilities for invocation, parameter preparation, and return value handling.

Analyze the responsibilities of each class (by the way, the analysis directory):

The Handlermethod encapsulation method defines related information, such as classes, methods, parameters, and so on.

Usage Scenario: When handlermapping is used

Invocablehandlermethod adding parameter preparation, method invocation function

Usage scenario: Execution using @modelattribute annotations uses

Servletinvocablehandlermethod Add return value handling responsibilities, ResponseStatus processing

Usage scenarios: Execution of HTTP-related methods is used, such as invoking processing execution

1. Handlermethod

Handlermethod can be simply understood to keep the Pojo of the method information.

So the main thing here is to look at the properties of the definition:

1 package Org.springframework.web.method; 2 public class Handlermethod {3     /** what ghost, to provide sub-class logger, so far rare in the source code */4     protected final Log logger = Logfactory.getl OG (handlermethod.class); 5     //The class where the method resides, if it is a string type, you can go to the container to get 6     private final Object bean; 7     //method 8     Private final method; 9
   
    //class managed container-     private final beanfactory beanfactory;11     //method parameters of the     private final methodparameter[] Parameters;13     //If the method is a bridged method, then the original method is the same as the     private final method bridgedmethod;15     //... 16}
   


Most of it should be a look at the comments to understand, we explain below:

All the familiarity here is final type and cannot be modified, so if a change occurs, new is required.

If the bean is a string, it is in Createwithresolvedbean to find the container to get the instance.

The Methodparameter class encapsulates parameter-related information.

Provides a get return value, determines whether the type of void, and read annotations

Createwithresolvedbean logic is actually simple:

Confirm that if the bean is of type string, the beanfactory is obtained in the Handlermethod and uses the private (Handlermethod Handlermethod, Object handler) New one.

1//HANDLERMETHOD2 public     Handlermethod Createwithresolvedbean () {3         Object handler = this.bean;4         if ( This.bean instanceof String) {5             string beanname = (string) this.bean;6             handler = This.beanFactory.getBean ( Beanname); 7         }8         return new Handlermethod (this, handler); 9     }

Methodparameter can be determined according to method and Parameterindex (parameter subscript), and other properties can be obtained from both.

Because there is no information about the parameter name in the reflection, and this is needed, Spring adds a parameter name Finder parameternamediscover.

This way the type of the return value is stored in the parameters attribute, and the subscript is distinguished by-1.

Methodparameter has a subclass of two inner classes in Handlermethod.

1 package Org.springframework.core; 2 public class Methodparameter {3     ///Parameter 4     private final method; 5     //Parameter construction method 6     private Final C Onstructor constructor; 7     //parameter subscript 8     private final int parameterindex; 9     //parameter type     class<?> parametertype;11     / /type of parameter type     genericparametertype;13     //parameter use note (     annotation[] PARAMETERANNOTATIONS;15     //Parameter Finder-     private parameternamediscoverer parameternamediscoverer;17     // Parameter name of the     private String parametername;19     //parameter nesting level, such as map<string> in the map is 1,string to a     private int NestingLevel = 1;21     //subscript for each layer     /** Map from the integer level to integer type index */23     map<integer, intege r> typeindexesperlevel;24     //What the hell? Just one construction method used, others are not using the     map<typevariable, type> typevariablemap;26     // ... 27}

2. Invocablehandlermethod

Habitual, seeing Invocable, would think that spring would define an interface to define the callable concept, but not.

2 responsibilities are added here: Parameter preparation and method execution.

The parameter prepares the delegate handlermethodargumentresolver to carry on the concrete analysis. The resolution needs to use the Webdatabinder, so by the way. I'm interested in the parametric parser.

2.1 Let's take a look at the parameter Preparation section.

To find the logic for a parameter value:

A, first the parameter name Finder to get the parameter name

b, look up values from externally supplied parameter lists (actually judged by type)

C, if not provided directly, use the parameter parser to create

D, if still not obtained, direct error

 1 package org.springframework.web.method.support; 2 3 public class Invocablehandlermethod extends Handlermethod {4//Parameter resolver 5 private handlermethodargumentresolve Rcomposite argumentresolvers = new Handlermethodargumentresolvercomposite (); 6//Parameter parser needs to use 7 private webdatabinderfactory databinderfactory; 8//Parameter name Finder 9 private Parameternamediscoverer parameternamediscoverer = new Localvariabletableparameternamediscove RER (), Private object[] Getmethodargumentvalues (nativewebrequest request, Modelandviewcontainer MA vcontainer,13 Object ... providedargs) throws Exception {methodparameter[] parameters = GetMethod  Parameters (); object[] args = new object[parameters.length];17 for (int i = 0; i < parameters.length; i++) {methodparameter parameter = parameters[i];19 parameter.initparameternamediscovery (parame Ternamediscoverer); 20//Find parameter name GenerictypEresolver.resolveparametertype (parameter, Getbean (). GetClass ()); 22//The value from the supplied parameter value Providedargs is found in arg S[i] = resolveprovidedargument (parameter, Providedargs); + if (args[i]! = null) {continue;2                 6}27//parse with parameter parser (argumentresolvers.supportsparameter (parameter)) {29 try {args[i] = argumentresolvers.resolveargument (parameter, Mavcontainer, request, Databinde                 rfactory) continue;32} catch (Exception ex) {ex;34 }35}36//parameters can not be obtained is required to error the PNS if (args[i] = = null) {Strin G msg = Getargumentresolutionerrormessage ("No suitable resolver for argument", I); new Illegalstat Eexception (msg);}41}42 return args;43}44 private Object resolveprovidedargumen T (Methodparameter Parameter, Object ... providedargs) {Providedargs = = null) {null;48}49 for (Object Providedarg:providedargs)                 {50//unexpectedly is a type-judged Parameter.getparametertype (). Isinstance (Providedarg)) {52 Return providedarg;53}54}55 return null;56}57 58//... 59 60}

2.2 Method execution

The logic here is actually very simple:

Delegate gets the required parameters for the method execution

Forcing a method to become available

Handling exceptions during method execution

 1 package org.springframework.web.method.support;  2 3 public class Invocablehandlermethod extends Handlermethod {4//... 5 Public final Object invokeforrequest (nativewebrequest request, 6 Modelandvi         Ewcontainer Mavcontainer, 7 Object ... Providedargs) throws Exception {8 object[] args = getmethodargumentvalues (Request, Mavcontainer, Providedargs); 9 Object returnvalue = Invoke (args), return returnvalue;11}12 Private Object Invoke (object: .             args) throws Exception {reflectionutils.makeaccessible (This.getbridgedmethod ()); try {16             Return Getbridgedmethod (). Invoke (Getbean (), args),}18 catch (IllegalArgumentException e) {19 String msg = Getinvocationerrormessage (E.getmessage (), args); throw new IllegalArgumentException (MSG, e); 2 1}22 catch (invocationtargetexception e){Unwrap//for handlerexceptionresolvers ... Throwable targetexception = E.gettargetexception (); if (targetexception instanceof Runtimeexc eption) {runtimeexception) targetexception;27}28 else if (targetexcepti On instanceof Error) {throw (Error) targetexception;30}31 else if (targetexcep                 tion instanceof Exception) {$ throw (Exception) targetexception;33}34 else {35  String msg = Getinvocationerrormessage ("Failed to Invoke Controller method", args); New IllegalStateException (MSG, targetexception); 37}38}39}40 41}

3. Servletinvocablehandlermethod

Delegate Handlermethodreturnvaluehandler add return value processing function

Add @responsestatus annotation Support.

The @responsestatus annotation used here two attributes: Value status code, reason writing to response

3.1 Logic when setting the response status:

ResponseStatus is not set to return

Responsereason exists then goes into error

Set ResponseStatus to Request,redirectview need to use

1//Servletinvocablehandlermethod 2     private void Setresponsestatus (Servletwebrequest webRequest) throws IOException {3         if (this.responsestatus = = null) {4             return; 5         } 6  7         if (Stringutils.hastext ( This.responsereason)) {8             webrequest.getresponse (). Senderror (This.responseStatus.value (), This.responsereason ); 9         }10         else {             webrequest.getresponse (). SetStatus (This.responseStatus.value ());         /To is picked up by the REDIRECTVIEW15         webrequest.getrequest (). SetAttribute (View.response_status_attribute, This.responsestatus);     

3.2 Invokeandhandle

Delegate parent class execution request

Add ResponseStatus Support

Then judge what is done, and meet any one of the following:

The notmodified of the request is true, using @responsestatus annotations, Mavcontainer requesthandled is True

Delegate Handlermethodreturnvaluehandler Package return value

 1//Servletinvocablehandlermethod 2 public final void Invokeandhandle (Servletwebrequest webRequest, 3 Mo Delandviewcontainer Mavcontainer, Object ... Providedargs) throws Exception {4 5 Object returnvalue = Invokeforre Quest (WebRequest, Mavcontainer, Providedargs); 6 7 setresponsestatus (webRequest); 8 9 if (returnvalue = = null) {Ten if (isrequestnotmodified (webRequest) | | hasresponsestatus () | | mavco             Ntainer.isrequesthandled ()) {mavcontainer.setrequesthandled (true); return;13 }14}15 Else if (Stringutils.hastext (This.responsereason)) {Mavcontainer.setrequesthand             LED (true); Return;18}19 mavcontainer.setrequesthandled (false); try {23 This.returnValueHandlers.handleReturnValue (ReturnValue, Getreturnvaluetype (returnvalue), Mavcontainer, WebRequest       ),}25 catch (Exception ex) {26      if (logger.istraceenabled ()) {Logger.trace (Getreturnvaluehandlingerrormessage ("Error handling RET Urn value ", returnvalue), ex);}29 throw ex;30}31}

Http://www.cnblogs.com/leftthen/p/5229204.html

SPRINGMVC Source Code Analysis-Handlermethod

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.