public interface HandlerMethodArgumentResolver { //該解析器是否支持parameter參數的解析 boolean supportsParameter(MethodParameter parameter); //將方法參數從給定請求(webRequest)解析爲參數值並返回 Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception; }
public void afterPropertiesSet() { if (this.argumentResolvers == null) { //初始化SpringMVC默認的方法參數解析器,並添加至argumentResolvers(HandlerMethodArgumentResolverComposite) List<HandlerMethodArgumentResolver> resolvers = getDefaultArgumentResolvers(); this.argumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers); } if (this.initBinderArgumentResolvers == null) { //初始化SpringMVC默認的初始化綁定器(@InitBinder)參數解析器,並添加至initBinderArgumentResolvers(HandlerMethodArgumentResolverComposite) List<HandlerMethodArgumentResolver> resolvers = getDefaultInitBinderArgumentResolvers(); this.initBinderArgumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers); } if (this.returnValueHandlers == null) { //獲取默認的方法返回值解析器 List<HandlerMethodReturnValueHandler> handlers = getDefaultReturnValueHandlers(); this.returnValueHandlers = new HandlerMethodReturnValueHandlerComposite().addHandlers(handlers); } initControllerAdviceCache(); }
//默認的參數解析,建立了默認的24個參數解析器,並添加至resolvers //這裏的24個參數解析器都是針對不一樣的參數類型來解析的 private List<HandlerMethodArgumentResolver> getDefaultArgumentResolvers() { List<HandlerMethodArgumentResolver> resolvers = new ArrayList<HandlerMethodArgumentResolver>(); // 基於註解的參數解析器 //通常用於帶有@RequestParam註解的簡單參數綁定,簡單參數好比byte、int、long、double、String以及對應的包裝類型 resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), false)); //用於處理帶有@RequestParam註解,且參數類型爲Map的解析綁定 resolvers.add(new RequestParamMapMethodArgumentResolver()); //通常用於處理帶有@PathVariable註解的默認參數綁定 resolvers.add(new PathVariableMethodArgumentResolver()); //也是用於帶有@PathVariable註解的Map相關參數綁定,後續還有一些默認的參數解析器。後續還有一些參數解析器,我這裏都不一一解釋了。想具體確認某個參數會交個哪一個參數解析器處理,能夠經過如下解析器的supportsParameter(MethodParameter parameter)方法得知 resolvers.add(new PathVariableMapMethodArgumentResolver()); resolvers.add(new MatrixVariableMethodArgumentResolver()); resolvers.add(new MatrixVariableMapMethodArgumentResolver()); resolvers.add(new ServletModelAttributeMethodProcessor(false)); resolvers.add(new RequestResponseBodyMethodProcessor(getMessageConverters())); resolvers.add(new RequestPartMethodArgumentResolver(getMessageConverters())); resolvers.add(new RequestHeaderMethodArgumentResolver(getBeanFactory())); resolvers.add(new RequestHeaderMapMethodArgumentResolver()); resolvers.add(new ServletCookieValueMethodArgumentResolver(getBeanFactory())); resolvers.add(new ExpressionValueMethodArgumentResolver(getBeanFactory())); // 基於類型的參數解析器 resolvers.add(new ServletRequestMethodArgumentResolver()); resolvers.add(new ServletResponseMethodArgumentResolver()); resolvers.add(new HttpEntityMethodProcessor(getMessageConverters())); resolvers.add(new RedirectAttributesMethodArgumentResolver()); resolvers.add(new ModelMethodProcessor()); resolvers.add(new MapMethodProcessor()); resolvers.add(new ErrorsMethodArgumentResolver()); resolvers.add(new SessionStatusMethodArgumentResolver()); resolvers.add(new UriComponentsBuilderMethodArgumentResolver()); // Custom arguments if (getCustomArgumentResolvers() != null) { resolvers.addAll(getCustomArgumentResolvers()); }
//它的元素在RequestMappingHandlerAdapter類的afterPropertiesSet方法中被添加,存放的是SpringMVC一些默認的HandlerMethodArgumentResolver參數解析器 private final List<HandlerMethodArgumentResolver> argumentResolvers = new LinkedList<HandlerMethodArgumentResolver>(); //存放已經解析過的參數,已經對應的HandlerMethodArgumentResolver解析器。加快查找過程 private final Map<MethodParameter, HandlerMethodArgumentResolver> argumentResolverCache = new ConcurrentHashMap<MethodParameter, HandlerMethodArgumentResolver>(256);
@Controller @RequestMapping("/ParameterBind") public class ParameterBindTestController { @ResponseBody @RequestMapping("/test1") public String test1(int id){ System.out.println(id); return "test1"; } }
private ModelAndView invokeHandleMethod(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) throws Exception { ServletWebRequest webRequest = new ServletWebRequest(request, response); WebDataBinderFactory binderFactory = getDataBinderFactory(handlerMethod); ModelFactory modelFactory = getModelFactory(handlerMethod, binderFactory); //根據handlerMethod和binderFactory建立一個ServletInvocableHandlerMethod。後續把請求直接交給ServletInvocableHandlerMethod執行。 //createRequestMappingMethod方法比較簡單,把以前RequestMappingHandlerAdapter初始化的argumentResolvers和returnValueHandlers添加至ServletInvocableHandlerMethod中 ServletInvocableHandlerMethod requestMappingMethod = createRequestMappingMethod(handlerMethod, binderFactory); ModelAndViewContainer mavContainer = new ModelAndViewContainer(); mavContainer.addAllAttributes(RequestContextUtils.getInputFlashMap(request)); modelFactory.initModel(webRequest, mavContainer, requestMappingMethod); mavContainer.setIgnoreDefaultModelOnRedirect(this.ignoreDefaultModelOnRedirect); AsyncWebRequest asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response); asyncWebRequest.setTimeout(this.asyncRequestTimeout); final WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); asyncManager.setTaskExecutor(this.taskExecutor); asyncManager.setAsyncWebRequest(asyncWebRequest); asyncManager.registerCallableInterceptors(this.callableInterceptors); asyncManager.registerDeferredResultInterceptors(this.deferredResultInterceptors); if (asyncManager.hasConcurrentResult()) { Object result = asyncManager.getConcurrentResult(); mavContainer = (ModelAndViewContainer) asyncManager.getConcurrentResultContext()[0]; asyncManager.clearConcurrentResult(); if (logger.isDebugEnabled()) { logger.debug("Found concurrent result value [" + result + "]"); } requestMappingMethod = requestMappingMethod.wrapConcurrentResult(result); } requestMappingMethod.invokeAndHandle(webRequest, mavContainer); if (asyncManager.isConcurrentHandlingStarted()) { return null; } return getModelAndView(mavContainer, modelFactory, webRequest); }
public final Object invokeForRequest(NativeWebRequest request, ModelAndViewContainer mavContainer, Object... providedArgs) throws Exception { //從request中解析出HandlerMethod方法所須要的參數,並返回Object[] Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs); if (logger.isTraceEnabled()) { StringBuilder builder = new StringBuilder("Invoking ["); builder.append(this.getMethod().getName()).append("] method with arguments "); builder.append(Arrays.asList(args)); logger.trace(builder.toString()); } //經過反射執行HandleMethod中的method,方法參數爲args。並返回方法執行的返回值 Object returnValue = invoke(args); if (logger.isTraceEnabled()) { logger.trace("Method [" + this.getMethod().getName() + "] returned [" + returnValue + "]"); } return returnValue; }
/** * 獲取當前請求的方法參數值。 */ private Object[] getMethodArgumentValues( NativeWebRequest request, ModelAndViewContainer mavContainer, Object... providedArgs) throws Exception { //獲取方法參數數組 MethodParameter[] parameters = getMethodParameters(); //建立一個參數數組,保存從request解析出的方法參數 Object[] args = new Object[parameters.length]; for (int i = 0; i < parameters.length; i++) { MethodParameter parameter = parameters[i]; parameter.initParameterNameDiscovery(parameterNameDiscoverer); GenericTypeResolver.resolveParameterType(parameter, getBean().getClass()); args[i] = resolveProvidedArgument(parameter, providedArgs); if (args[i] != null) { continue; } //判斷以前RequestMappingHandlerAdapter初始化的那24個HandlerMethodArgumentResolver(參數解析器),是否存在支持該參數解析的解析器 if (argumentResolvers.supportsParameter(parameter)) { try { args[i] = argumentResolvers.resolveArgument(parameter, mavContainer, request, dataBinderFactory); continue; } catch (Exception ex) { if (logger.isTraceEnabled()) { logger.trace(getArgumentResolutionErrorMessage("Error resolving argument", i), ex); } throw ex; } } if (args[i] == null) { String msg = getArgumentResolutionErrorMessage("No suitable resolver for argument", i); throw new IllegalStateException(msg); } } return args; }
public Object resolveArgument( MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { //首先獲取參數解析器,這裏獲取的邏輯是首先從argumentResolverCache緩存中獲取該MethodParameter匹配的HandlerMethodArgumentResolver。若是爲空,遍歷初始化定義的那24個。查找匹配的HandlerMethodArgumentResolver,而後添加至argumentResolverCache緩存中 HandlerMethodArgumentResolver resolver = getArgumentResolver(parameter); Assert.notNull(resolver, "Unknown parameter type [" + parameter.getParameterType().getName() + "]"); //解析參數 return resolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory); }
public final Object resolveArgument( MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { //獲取int的Class對象 Class<?> paramType = parameter.getParameterType(); //根據參數定義建立一個NamedValueInfo對象 NamedValueInfo namedValueInfo = getNamedValueInfo(parameter); //根據參數名解析出對象的值 Object arg = resolveName(namedValueInfo.name, parameter, webRequest); if (arg == null) { if (namedValueInfo.defaultValue != null) { arg = resolveDefaultValue(namedValueInfo.defaultValue); } else if (namedValueInfo.required) { handleMissingValue(namedValueInfo.name, parameter); } arg = handleNullValue(namedValueInfo.name, arg, paramType); } else if ("".equals(arg) && (namedValueInfo.defaultValue != null)) { arg = resolveDefaultValue(namedValueInfo.defaultValue); } //上面步驟獲取的args是String類型,而後轉換爲方法參數所須要的類型(int) if (binderFactory != null) { WebDataBinder binder = binderFactory.createBinder(webRequest, null, namedValueInfo.name); arg = binder.convertIfNecessary(arg, paramType, parameter); } handleResolvedValue(arg, namedValueInfo.name, parameter, mavContainer, webRequest); return arg; }
String[] paramValues = webRequest.getParameterValues(name); if (paramValues != null) { arg = paramValues.length == 1 ? paramValues[0] : paramValues; }
因此這裏返回的值就是9999,這裏返回的值仍是String類型的。而須要的參數是int類型的。而後經過binder.coverIfNecessary方法把String轉換爲int類型返回。html
@ResponseBody @RequestMapping("/test2") public String test2(User u){ System.out.println(u.toString()); return "test1"; }
resolvers.add(new ServletModelAttributeMethodProcessor(false)); resolvers.add(new ServletModelAttributeMethodProcessor(true));
/** *帶有@ModelAttribute註解返回true * parameter不是簡單類型也返回true. */ public boolean supportsParameter(MethodParameter parameter) { if (parameter.hasParameterAnnotation(ModelAttribute.class)) { return true; } else if (this.annotationNotRequired) { return !BeanUtils.isSimpleProperty(parameter.getParameterType()); } else { return false; } }
/** * 解析model中的參數,若是從ModelAndViewContainer未找到,直接經過反射實例化一個對象。具體實例化是經過父類的createAttribute方法,經過調用BeanUtils.instantiateClass方法來實例化的。這個對象即是後續傳給test2(User u)方法的對象,可是此時建立的對象裏面的值都還爲空,注入值是經過bindRequestParameters方法來實現的。 */ public final Object resolveArgument( MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest request, WebDataBinderFactory binderFactory) throws Exception { String name = ModelFactory.getNameForParameter(parameter); Object attribute = (mavContainer.containsAttribute(name)) ? mavContainer.getModel().get(name) : createAttribute(name, parameter, binderFactory, request); WebDataBinder binder = binderFactory.createBinder(request, attribute, name); if (binder.getTarget() != null) { //將請求綁定至目標binder的target對象,也就是剛剛建立的attribute對象。 bindRequestParameters(binder, request); //若是有驗證,則驗證參數 validateIfApplicable(binder, parameter); if (binder.getBindingResult().hasErrors()) { if (isBindExceptionRequired(binder, parameter)) { throw new BindException(binder.getBindingResult()); } } } // Add resolved attribute and BindingResult at the end of the model Map<String, Object> bindingResultModel = binder.getBindingResult().getModel(); mavContainer.removeAttributes(bindingResultModel); mavContainer.addAllAttributes(bindingResultModel); return binder.getTarget(); }
版權聲明
做者:wycm
出處:https://www.cnblogs.com/w-y-c-m/p/8443892.html
您的支持是對博主最大的鼓勵,感謝您的認真閱讀。
本文版權歸做者全部,歡迎轉載,但未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接,不然保留追究法律責任的權利。
java