SpringMVC source code parsing, springmvc source code

Source: Internet
Author: User

SpringMVC source code parsing, springmvc source code

HandlerMethod and subclass are mainly used to encapsulate information about method calls. Subclass also provides the responsibility for calling, parameter preparation, and return value processing.

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

HandlerMethod encapsulates information related to method definitions, such as classes, methods, and parameters.

Use Case: HandlerMapping

InvocableHandlerMethod

Use Case: Run @ ModelAttribute annotation to use

ServletInvocableHandlerMethod: add the responsibility for processing returned values, and handle ResponseStatus.

Use Case: it is used to execute http-related methods, for example, call processing and execution.

 

1. HandlerMethod

HandlerMethod can be simply understood as a pojo for keeping method information.

So here we mainly look at the defined attributes:

1 package org. springframework. web. method; 2 public class HandlerMethod {3/** what is the ghost, providing logger to the subclass, so far the source code is rare */4 protected final Log logger = LogFactory. getLog (HandlerMethod. class); 5 // the class of the Method. If it is of the String type, you can obtain 6 private final Object beans from the container; 7 // method 8 private final Method method; 9 // class management container 10 private final BeanFactory beanFactory; 11 // method parameter 12 private final MethodParameter [] parameters; 13 // if the method is the bridged method, corresponding to the original Method 14 private final Method bridgedMethod; 15 //... 16}


Most of them can be understood by looking at the annotations. Let's explain the following:

All the familiarity here is of the final type and cannot be modified. Therefore, if any modification occurs, new is required.

If the bean is string, you can find the container in createWithResolvedBean to get the instance.

The MethodParameter class encapsulates parameter-related information.

Provides the ability to obtain return values, determine whether the void type is used, and read annotations.

 

The createWithResolvedBean logic is actually very simple:

Confirm that if the bean is of the String type, obtain it from the container BeanFactory and use private HandlerMethod (HandlerMethod handlerMethod, Object handler) to create a 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, which can be uniquely determined based on the method and parameterIndex (parameter subscript). Other attributes can be obtained based on the two parameters.

Because there is no Parameter Name Information in reflection, and this is required, Spring adds a parameter name finder ParameterNameDiscover.

The returned values are stored in the parameters attribute, and the subscript is distinguished by-1.

MethodParameter has two subclass of internal classes in HandlerMethod.

1 package org. springframework. core; 2 public class MethodParameter {3 // Method of the parameter 4 private final method Method; 5 // Construction method of the parameter 6 private final Constructor constructor; 7 // parameter subscript 8 private final int parameterIndex; 9 // parameter type 10 private Class <?> ParameterType; 11 // Type parameter Type 12 private Type genericParameterType; 13 // Annotation used by the parameter 14 private Annotation [] parameterAnnotations; 15 // parameter name finder 16 private ParameterNameDiscoverer parameterNameDiscoverer; 17 // parameter name 18 private String parameterName; 19 // parameter nesting level, for example, Map <String> is 1, string is 220 private int nestingLevel = 1; 21 // subscript 22/** Map from Integer level to Integer type index */23 Map <Integer, Integer> TypeIndexesPerLevel; 24 // What's the ghost? This method is used for one constructor. None of the other methods use 25 Map <TypeVariable, Type> typeVariableMap; 26 //... 27}

 

 

2. InvocableHandlerMethod

Habitually, when you see Invocable, you will think of whether Spring will define an interface to define the callable concept, but there is no.

Two responsibilities are added here: parameter preparation and method execution.

The parameter is required to delegate HandlerMethodArgumentResolver to perform specific parsing. WebDataBinder is required for parsing, so take it by the way. If you are interested in the parameter parser, click here.

 

2.1 let's take a look at the parameter preparation section.

Search for the logic of a parameter value:

A. First, delegate the parameter name Finder to obtain the parameter name.

B. Find the value from the list of parameters provided by the outside (it is determined based on the type)

C. If it is not provided directly, use the parameter parser to create

D. If it is still not obtained, an error is reported directly.

1 package org. springframework. web. method. support; 2 3 public class InvocableHandlerMethod extends HandlerMethod {4 // parameter parser 5 private parser argumentResolvers = new Parser (); 6 // The parameter parser requires 7 private WebDataBinderFactory; 8 // parameter name finder 9 private ParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTablePa RameterNameDiscoverer (); 10 11 private Object [] getMethodArgumentValues (12 NativeWebRequest request, ModelAndViewContainer mavContainer, 13 Object... providedArgs) throws Exception {14 15 MethodParameter [] parameters = getMethodParameters (); 16 Object [] args = new Object [parameters. length]; 17 for (int I = 0; I <parameters. length; I ++) {18 MethodParameter parameter = parameters [I]; 19 parameter. initPa RameterNameDiscovery (parameterNameDiscoverer); 20 // search for the parameter name 21 GenericTypeResolver. resolveParameterType (parameter, getBean (). getClass (); 22 // find the value 23 args [I] = resolveProvidedArgument (parameter, providedArgs) from the provided parameter value providedArgs; 24 if (args [I]! = Null) {25 continue; 26} 27 // use the parameter parser to parse 28 if (argumentResolvers. supportsParameter (parameter) {29 try {30 args [I] = argumentResolvers. resolveArgument (parameter, mavContainer, request, dataBinderFactory); 31 continue; 32} catch (Exception ex) {33 throw ex; 34} 35} 36 // The 37 if (args [I] = null) {38 String msg = getArgumentResolutionErrorMessage ("No suitable resolver for argument ", i); 39 throw new IllegalStateException (msg); 40} 41} 42 return args; 43} 44 45 private Object resolveProvidedArgument (MethodParameter parameter, Object... providedArgs) {46 if (providedArgs = null) {47 return null; 48} 49 for (Object providedArg: providedArgs) {50 // 51 if (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:

Parameters required for method execution by Delegation

Forcibly change the method to available

Exception in handling 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                                          ModelAndViewContainer mavContainer, 7                                          Object... providedArgs) throws Exception { 8         Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs); 9         Object returnValue = invoke(args);10         return returnValue;11     }12 13     private Object invoke(Object... args) throws Exception {14         ReflectionUtils.makeAccessible(this.getBridgedMethod());15         try {16             return getBridgedMethod().invoke(getBean(), args);17         }18         catch (IllegalArgumentException e) {19             String msg = getInvocationErrorMessage(e.getMessage(), args);20             throw new IllegalArgumentException(msg, e);21         }22         catch (InvocationTargetException e) {23             // Unwrap for HandlerExceptionResolvers ...24             Throwable targetException = e.getTargetException();25             if (targetException instanceof RuntimeException) {26                 throw (RuntimeException) targetException;27             }28             else if (targetException instanceof Error) {29                 throw (Error) targetException;30             }31             else if (targetException instanceof Exception) {32                 throw (Exception) targetException;33             }34             else {35                 String msg = getInvocationErrorMessage("Failed to invoke controller method", args);36                 throw new IllegalStateException(msg, targetException);37             }38         }39     }40 41 }

 

 

3. ServletInvocableHandlerMethod

Delegate HandlerMethodReturnValueHandler to add the return value processing function

Added @ ResponseStatus annotation support.

 

The @ ResponseStatus annotation used here has two attributes: value status code, and the description text written by reason to response

 

3.1 logic for setting response status:

Response if responseStatus is not set

If responseReason exists, an error occurs.

Set responseStatus to request, which must be used by RedirectView

 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 {11             webRequest.getResponse().setStatus(this.responseStatus.value());12         }13 14         // to be picked up by the RedirectView15         webRequest.getRequest().setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, this.responseStatus);16     }

3.2 invokeAndHandle

Delegate the parent class to execute the request

Added ResponseStatus support

Then determine how the execution is completed to satisfy any of the following requirements:

The notModified of the request is true. The @ ResponseStatus annotation is used, and the requestHandled of the mavContainer is true.

Delegate HandlerMethodReturnValueHandler to encapsulate returned values

 1 // ServletInvocableHandlerMethod 2     public final void invokeAndHandle(ServletWebRequest webRequest, 3             ModelAndViewContainer mavContainer, Object... providedArgs) throws Exception { 4  5         Object returnValue = invokeForRequest(webRequest, mavContainer, providedArgs); 6  7         setResponseStatus(webRequest); 8  9         if (returnValue == null) {10             if (isRequestNotModified(webRequest) || hasResponseStatus() || mavContainer.isRequestHandled()) {11                 mavContainer.setRequestHandled(true);12                 return;13             }14         }15         else if (StringUtils.hasText(this.responseReason)) {16             mavContainer.setRequestHandled(true);17             return;18         }19 20         mavContainer.setRequestHandled(false);21 22         try {23             this.returnValueHandlers.handleReturnValue(returnValue, getReturnValueType(returnValue), mavContainer, webRequest);24         }25         catch (Exception ex) {26             if (logger.isTraceEnabled()) {27                 logger.trace(getReturnValueHandlingErrorMessage("Error handling return value", returnValue), ex);28             }29             throw ex;30         }31     }

 

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.