• springMVC(二): @RequestBody @ResponseBody 注解实现分析


    一、继承结构

    @RequestBody、@ResponseBody的处理器:RequestResponseBodyMethodProcessor

    @ModelAttribute处理器: ModelAttributeMethodProcessor

    HttpEntity处理器: HttpEntityMethodProcessor

    参数值解析器: HandlerMethodArgumentResolver

    返回值处理器: HandlerMethodReturnValueHandler

    使用HttpMessageConverter 转换方法参数: AbstractMessageConverterMethodArgumentResolver

    二、 处理过程

    1. RequestResponseBodyMethodProcessor的resolveArgument过程

        @Override
        public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    
         //返回@RequestBody需要的参数, Spring使用我们自定义的RequestBodyAdvice, ResponseBodyAdvice发生在这里 Object arg
    = readWithMessageConverters(webRequest, parameter, parameter.getGenericParameterType()); String name = Conventions.getVariableNameForParameter(parameter);
         //输入参数转换成Java对象发生在这里,后面有专门的文章讲解,注意:每次请求绑定的对象的重新生成的 WebDataBinder binder
    = binderFactory.createBinder(webRequest, arg, name); if (arg != null) { validateIfApplicable(binder, parameter); if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) { throw new MethodArgumentNotValidException(parameter, binder.getBindingResult()); } } mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult()); return arg; } @Override protected <T> Object readWithMessageConverters(NativeWebRequest webRequest, MethodParameter methodParam, Type paramType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException { HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class); ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(servletRequest);
         //调用父类的readWithMessageCoverters()方法 Object arg
    = readWithMessageConverters(inputMessage, methodParam, paramType); if (arg == null) { if (methodParam.getParameterAnnotation(RequestBody.class).required()) { throw new HttpMessageNotReadableException("Required request body is missing: " + methodParam.getMethod().toGenericString()); } } return arg; }


  • 相关阅读:
    jquery_DOM笔记3
    jquery_DOM笔记2
    mac之jdk环境变量配置
    360导致的mysql问题解决
    windows服务器apache配置https教程
    生成自己openssl的证书
    wkhtmltopdf中文乱码
    安装ruby、rails
    extjs中返回数据时id不能重复,否则数据会被合并
    gzip压缩ext-all.js
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/8617039.html
Copyright © 2020-2023  润新知