一、前言
web相关知识探索三中研究了请求中所带的参数是如何映射到接口参数中的,也即请求参数如何与接口参数绑定。主要有四种、分别是注解方式、Servlet API方式、复杂参数、以及自定义对象参数。web相关知识探索三中主要研究了注解方式以及Servlet API方式。本次研究主要是复杂参数底层绑定原理。
二、 复杂参数底层绑定原理
一、测试用例
请求的接口当中,还可以放入这些类型作为参数,Map、Model(map、model里面的数据会被默认放在request的请求域 request.setAttribute)、Errors/BindingResult、RedirectAttributes( 重定向携带数据)、ServletResponse(response)、SessionStatus、UriComponentsBuilder、ServletUriComponentsBuilder。
/*** 请求进来这个接口,然后往map设置数据,同时也往model和request设置数据,* 处理完之后再转发到下一个接口,下一个接口再从请求域中拿出map和model中设置的数据* 这里主要是验证,接口参数map和moddel,请求进来时,携带到的值是放在请求域中的* Map<String,Object> map, Model model, HttpServletRequest request 都是可以给request域中放数据,* @param map* @param model* @param request* @return*/@GetMapping("/test")public String testParam(Map<String,Object> map, Model model, HttpServletRequest request, HttpServletResponse response){map.put("test1","mapTest");model.addAttribute("test2","modelTest");request.setAttribute("test3","requestTest");Cookie cookie = new Cookie("test4","cookieTest");response.addCookie(cookie);return "forward:/success";}@GetMapping("/success")@ResponseBodypublic Map testSuccess(HttpServletRequest request){Object test1 = request.getAttribute("test1");Object test2 = request.getAttribute("test2");Object test3 = request.getAttribute("test3");Map mp = new HashMap();mp.put("test1",test1);mp.put("test2",test2);mp.put("test3",test3);return mp;}
二、底层原理
一、Map参数解析
请求进来以后,直接到匹配合适的参数解析器这一步,第一个参数是Map类型的,所以需要的是能够解析Map类型参数的解析器。
上面是判断那种解析器支持解析Map类型参数,下面开始解析Map类型参数
// 解析map类型参数@Nullablepublic Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {Assert.state(mavContainer != null, "ModelAndViewContainer is required for model exposure");// 直接从一个ModelAndViewContainer(模型和视图容器)对象中获取一个modelreturn mavContainer.getModel();}// 获取模型对象public ModelMap getModel() {默认会进入这条路径if (this.useDefaultModel()) {return this.defaultModel;} else {if (this.redirectModel == null) {this.redirectModel = new ModelMap();}return this.redirectModel;}}
获取到的model对象是一个
private final ModelMap defaultModel = new BindingAwareModelMap();也就是说,获取到的是一个BindingAwareModelMap对象,可以查看他的继承和实现发现,BindingAwareModelMap 是Model 也是Map。
二、Model参数解析
从HandlerMethodArgumentResolverComposite类中的方法resolveArgument里面的代码
resolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory);这里是开始解析参数的地方,从这里进入会发现,和map的解析是一模一样的。也是获取到一个BindingAwareModelMap对象。而且和前一个map用的还是同一个对象。
三、map参数和model参数会被放到请求域当中
一、处理返回值
刚开始BindingAwareModelMap对象是空的,等到执行完接口后,接口里面会进行赋值,这个对象就有数据了。目标方法执行完,会将所有的数据都放在 ModelAndViewContainer;包含要去的页面地址View。还包含Model数据
// 处理请求接口以及处理接口返回数据public void invokeAndHandle(ServletWebRequest webRequest, ModelAndViewContainer mavContainer, Object... providedArgs) throws Exception {// 处理接口Object returnValue = this.invokeForRequest(webRequest, mavContainer, providedArgs);this.setResponseStatus(webRequest);if (returnValue == null) {if (this.isRequestNotModified(webRequest) || this.getResponseStatus() != null || mavContainer.isRequestHandled()) {this.disableContentCachingIfNecessary(webRequest);mavContainer.setRequestHandled(true);return;}} else if (StringUtils.hasText(this.getResponseStatusReason())) {mavContainer.setRequestHandled(true);return;}mavContainer.setRequestHandled(false);Assert.state(this.returnValueHandlers != null, "No return value handlers");try {// 处理返回结果,mavContainer也被作为参数传入进去了this.returnValueHandlers.handleReturnValue(returnValue, this.getReturnValueType(returnValue), mavContainer, webRequest);} catch (Exception var6) {if (logger.isTraceEnabled()) {logger.trace(this.formatErrorForReturnValue(returnValue), var6);}throw var6;}}// 处理返回值public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {//找到返回值处理器,这里之后在返回值部分细细研究 HandlerMethodReturnValueHandler handler = this.selectHandler(returnValue, returnType);if (handler == null) {throw new IllegalArgumentException("Unknown return value type: " + returnType.getParameterType().getName());} else {//这里是处理返回值的具体逻辑handler.handleReturnValue(returnValue, returnType, mavContainer, webRequest);}}// 具体处理返回值逻辑public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {// 如果返回值是字符串会进入到这里if (returnValue instanceof CharSequence) {String viewName = returnValue.toString();// 将返回值保存到ModelAndViewContainer对象中,view属性一般就是地址,model也就是数据,ModelAndView就是携带数据到达指定的地址当中mavContainer.setViewName(viewName);if (this.isRedirectViewName(viewName)) {mavContainer.setRedirectModelScenario(true);}} else if (returnValue != null) {throw new UnsupportedOperationException("Unexpected return type: " + returnType.getParameterType().getName() + " in method: " + returnType.getMethod());}}
二、将map、model数据设置到请求域中
下面是上图中invokeHandlerMethod方法中
invocableMethod.invokeAndHandle(webRequest, mavContainer, new Object[0]);这段代码涉及到的源码
// 处理请求接口以及处理接口返回数据public void invokeAndHandle(ServletWebRequest webRequest, ModelAndViewContainer mavContainer, Object... providedArgs) throws Exception {// 处理接口Object returnValue = this.invokeForRequest(webRequest, mavContainer, providedArgs);this.setResponseStatus(webRequest);if (returnValue == null) {if (this.isRequestNotModified(webRequest) || this.getResponseStatus() != null || mavContainer.isRequestHandled()) {this.disableContentCachingIfNecessary(webRequest);mavContainer.setRequestHandled(true);return;}} else if (StringUtils.hasText(this.getResponseStatusReason())) {mavContainer.setRequestHandled(true);return;}mavContainer.setRequestHandled(false);Assert.state(this.returnValueHandlers != null, "No return value handlers");try {// 处理返回结果,mavContainer也被作为参数传入进去了this.returnValueHandlers.handleReturnValue(returnValue, this.getReturnValueType(returnValue), mavContainer, webRequest);} catch (Exception var6) {if (logger.isTraceEnabled()) {logger.trace(this.formatErrorForReturnValue(returnValue), var6);}throw var6;}}// 处理返回值public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {//找到返回值处理器,这里之后在返回值部分细细研究 HandlerMethodReturnValueHandler handler = this.selectHandler(returnValue, returnType);if (handler == null) {throw new IllegalArgumentException("Unknown return value type: " + returnType.getParameterType().getName());} else {//这里是处理返回值的具体逻辑handler.handleReturnValue(returnValue, returnType, mavContainer, webRequest);}}// 具体处理返回值逻辑public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {// 如果返回值是字符串会进入到这里if (returnValue instanceof CharSequence) {String viewName = returnValue.toString();// 将返回值保存到ModelAndViewContainer对象中,view属性一般就是地址,model也就是数据,ModelAndView就是携带数据到达指定的地址当中mavContainer.setViewName(viewName);if (this.isRedirectViewName(viewName)) {mavContainer.setRedirectModelScenario(true);}} else if (returnValue != null) {throw new UnsupportedOperationException("Unexpected return type: " + returnType.getParameterType().getName() + " in method: " + returnType.getMethod());}}
下面是上图中invokeHandlerMethod方法中
var15 = this.getModelAndView(mavContainer, modelFactory, webRequest);涉及到的源码
获取ModelAndView对象@Nullableprivate ModelAndView getModelAndView(ModelAndViewContainer mavContainer, ModelFactory modelFactory, NativeWebRequest webRequest) throws Exception {// 这里会更新model主要逻辑在自定义参数对象这块再研究modelFactory.updateModel(webRequest, mavContainer);if (mavContainer.isRequestHandled()) {return null;} else {ModelMap model = mavContainer.getModel();// 获取modelMap中的对象,并保存到ModelAndView中ModelAndView mav = new ModelAndView(mavContainer.getViewName(), model, mavContainer.getStatus());if (!mavContainer.isViewReference()) {mav.setView((View)mavContainer.getView());}// 处理重定向数据if (model instanceof RedirectAttributes) {Map<String, ?> flashAttributes = ((RedirectAttributes)model).getFlashAttributes();HttpServletRequest request = (HttpServletRequest)webRequest.getNativeRequest(HttpServletRequest.class);if (request != null) {// 将请求数据放到请求上下文当中RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes);}}return mav;}}
以上使用处理器适配器调用具体handler就处理完了,让然后会返回一个ModelAndView对象。之后回到DispatcherServlet类中的doDispatch方法当中。这个时候需要关注这个方法里面
this.processDispatchResult(processedRequest, response, mappedHandler, mv, (Exception)dispatchException);这块代码片段,主要是处理派发结果,这里就会往请求域中设置数据。
private void processDispatchResult(HttpServletRequest request, HttpServletResponse response, @Nullable HandlerExecutionChain mappedHandler, @Nullable ModelAndView mv, @Nullable Exception exception) throws Exception {// 这部分是处理异常的boolean errorView = false;if (exception != null) {if (exception instanceof ModelAndViewDefiningException) {this.logger.debug("ModelAndViewDefiningException encountered", exception);mv = ((ModelAndViewDefiningException)exception).getModelAndView();} else {Object handler = mappedHandler != null ? mappedHandler.getHandler() : null;mv = this.processHandlerException(request, response, handler, exception);errorView = mv != null;}}// ModelAndView不为空时,且没有被清理if (mv != null && !mv.wasCleared()) {// 这里是去渲染页面的this.render(mv, request, response);if (errorView) {WebUtils.clearErrorRequestAttributes(request);}} else if (this.logger.isTraceEnabled()) {this.logger.trace("No view rendering, null ModelAndView returned.");}if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {if (mappedHandler != null) {mappedHandler.triggerAfterCompletion(request, response, (Exception)null);}}}// 开始去渲染页面protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {Locale locale = this.localeResolver != null ? this.localeResolver.resolveLocale(request) : request.getLocale();response.setLocale(locale);// 获取视图名String viewName = mv.getViewName();View view;// 开始解析视图if (viewName != null) {view = this.resolveViewName(viewName, mv.getModelInternal(), locale, request);if (view == null) {throw new ServletException("Could not resolve view with name '" + mv.getViewName() + "' in servlet with name '" + this.getServletName() + "'");}} else {view = mv.getView();if (view == null) {throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a View object in servlet with name '" + this.getServletName() + "'");}}if (this.logger.isTraceEnabled()) {this.logger.trace("Rendering view [" + view + "] ");}try {if (mv.getStatus() != null) {response.setStatus(mv.getStatus().value());}// 上面代码拿到了视图,这里就开始去渲染了view.render(mv.getModelInternal(), request, response);} catch (Exception var8) {if (this.logger.isDebugEnabled()) {this.logger.debug("Error rendering view [" + view + "]", var8);}throw var8;}}// 开始进行视图解析@Nullableprotected View resolveViewName(String viewName, @Nullable Map<String, Object> model, Locale locale, HttpServletRequest request) throws Exception {if (this.viewResolvers != null) {Iterator var5 = this.viewResolvers.iterator();while(var5.hasNext()) {ViewResolver viewResolver = (ViewResolver)var5.next();View view = viewResolver.resolveViewName(viewName, locale);if (view != null) {return view;}}}return null;}@Nullablepublic View resolveViewName(String viewName, Locale locale) throws Exception {// 拿到请求域中的所有数据,和ModelAndView中的model数据(也就是接口中设置的数据)无关RequestAttributes attrs = RequestContextHolder.getRequestAttributes();Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes");List<MediaType> requestedMediaTypes = this.getMediaTypes(((ServletRequestAttributes)attrs).getRequest());if (requestedMediaTypes != null) {List<View> candidateViews = this.getCandidateViews(viewName, locale, requestedMediaTypes);// 拿到视图名,然后返回View bestView = this.getBestView(candidateViews, requestedMediaTypes, attrs);if (bestView != null) {return bestView;}}String mediaTypeInfo = this.logger.isDebugEnabled() && requestedMediaTypes != null ? " given " + requestedMediaTypes.toString() : "";if (this.useNotAcceptableStatusCode) {if (this.logger.isDebugEnabled()) {this.logger.debug("Using 406 NOT_ACCEPTABLE" + mediaTypeInfo);}return NOT_ACCEPTABLE_VIEW;} else {this.logger.debug("View remains unresolved" + mediaTypeInfo);return null;}}// 这里是开始渲染数据的部分public void render(@Nullable Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {if (this.logger.isDebugEnabled()) {this.logger.debug("View " + this.formatViewName() + ", model " + (model != null ? model : Collections.emptyMap()) + (this.staticAttributes.isEmpty() ? "" : ", static attributes " + this.staticAttributes));}// 这里是创建合并数据HashMap对象,其实就是将model中个数据放到这个map当中Map<String, Object> mergedModel = this.createMergedOutputModel(model, request, response);// 准备响应this.prepareResponse(request, response);// 渲染合并输出的数据,就是在这里放到了请求域中this.renderMergedOutputModel(mergedModel, this.getRequestToExpose(request), response);}// 渲染合并输出的数据,就是在这里放到了请求域中protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {// 就是在这行代码里将值设置到请求域当中this.exposeModelAsRequestAttributes(model, request);this.exposeHelpers(request);String dispatcherPath = this.prepareForRendering(request, response);RequestDispatcher rd = this.getRequestDispatcher(request, dispatcherPath);if (rd == null) {throw new ServletException("Could not get RequestDispatcher for [" + this.getUrl() + "]: Check that the corresponding file exists within your web application archive!");} else {if (this.useInclude(request, response)) {response.setContentType(this.getContentType());if (this.logger.isDebugEnabled()) {this.logger.debug("Including [" + this.getUrl() + "]");}rd.include(request, response);} else {if (this.logger.isDebugEnabled()) {this.logger.debug("Forwarding to [" + this.getUrl() + "]");}rd.forward(request, response);}}}// 设置数据到请求域当中,其实就是循环遍历了合并数据后的Map集合,将里面的值设置到请求域中protected void exposeModelAsRequestAttributes(Map<String, Object> model, HttpServletRequest request) throws Exception {model.forEach((name, value) -> {if (value != null) {request.setAttribute(name, value);} else {request.removeAttribute(name);}});}