文章目录

  • 请求映射处理适配器:RequestMappingHandlerAdapter
  • 参数解析器:HandlerMethodArgumentResolver
  • 参数处理相关注解
    • 1.@PathVariable
    • 2.@RequestHeader
    • 3.@CookieValue
    • 4.@RequestParam
    • 5.@RequestPart
    • 6.@RequestBody
    • 7.@SessionAttributes
    • 8.@ModelAttribute
  • 其它注解
    • @AliasFor

请求映射处理适配器:RequestMappingHandlerAdapter

参数解析器:HandlerMethodArgumentResolver

HandlerMethodArgumentResolver和AbstractNamedValueMethodArgumentResolver是解析策略的上层定义和抽象。

关于这两个类可以参考https://securitit.blog.csdn.net/article/details/110110872的解析。

HandlerMethodArgumentResolver是个接口,只有俩个方法

public interface HandlerMethodArgumentResolver {boolean supportsParameter(MethodParameter var1);@NullableObject resolveArgument(MethodParameter var1, @Nullable ModelAndViewContainer var2, NativeWebRequest var3, @Nullable WebDataBinderFactory var4) throws Exception;
}
  • supportsParameter:用于判定是否需要处理该参数分解,返回true为需要,并会去调用下面的方法resolveArgument。
  • resolveArgument:真正用于处理参数分解的方法,返回的Object就是controller方法上的形参对象。

获取默认参数解析器
RequestMappingHandlerAdapter.getDefaultArgumentResolvers()

 private List<HandlerMethodArgumentResolver> getDefaultArgumentResolvers() {List<HandlerMethodArgumentResolver> resolvers = new ArrayList<>();// 基于注解的参数解析resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), false));resolvers.add(new RequestParamMapMethodArgumentResolver());resolvers.add(new PathVariableMethodArgumentResolver());resolvers.add(new PathVariableMapMethodArgumentResolver());resolvers.add(new MatrixVariableMethodArgumentResolver());resolvers.add(new MatrixVariableMapMethodArgumentResolver());resolvers.add(new ServletModelAttributeMethodProcessor(false));resolvers.add(new RequestResponseBodyMethodProcessor(getMessageConverters(), this.requestResponseBodyAdvice));resolvers.add(new RequestPartMethodArgumentResolver(getMessageConverters(), this.requestResponseBodyAdvice));resolvers.add(new RequestHeaderMethodArgumentResolver(getBeanFactory()));resolvers.add(new RequestHeaderMapMethodArgumentResolver());resolvers.add(new ServletCookieValueMethodArgumentResolver(getBeanFactory()));resolvers.add(new ExpressionValueMethodArgumentResolver(getBeanFactory()));resolvers.add(new SessionAttributeMethodArgumentResolver());resolvers.add(new RequestAttributeMethodArgumentResolver());// 基于类型的参数解析resolvers.add(new ServletRequestMethodArgumentResolver());resolvers.add(new ServletResponseMethodArgumentResolver());resolvers.add(new HttpEntityMethodProcessor(getMessageConverters(), this.requestResponseBodyAdvice));resolvers.add(new RedirectAttributesMethodArgumentResolver());resolvers.add(new ModelMethodProcessor());resolvers.add(new MapMethodProcessor());resolvers.add(new ErrorsMethodArgumentResolver());resolvers.add(new SessionStatusMethodArgumentResolver());resolvers.add(new UriComponentsBuilderMethodArgumentResolver());// 自定义参数解析if (getCustomArgumentResolvers() != null) {resolvers.addAll(getCustomArgumentResolvers());}// Catch-allresolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), true));resolvers.add(new ServletModelAttributeMethodProcessor(true));return resolvers;}

参数处理相关注解

参数绑定常用注解:

  1. 处理request uri 部分(这里指uri template中variable,不含queryString部分)的注解: @PathVariable;

  2. 处理request header部分的注解: @RequestHeader, @CookieValue;

  3. 处理request body部分的注解:@RequestParam, @RequestBody;

  4. 处理attribute类型的注解: @SessionAttributes, @ModelAttribute;

1.@PathVariable

当使用@RequestMapping URI template 样式映射时, 即 someUrl/{paramId}, 这时的paramId可通过 @Pathvariable注解绑定它传过来的值到方法的参数上。

@Controller
@RequestMapping(“/owners/{ownerId}”)
public class RelativePathUriTemplateController {  @RequestMapping(“/pets/{petId}”)  public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {      }
}

若方法参数名称和需要绑定的uri template中变量名称不一致,需要在@PathVariable(“name”)指定uri template中的名称。

使用的参数解析器:

  1. PathVariableMapMethodArgumentResolver
    在某些条件成立的情况下才会使用此类进行解析:

    • 方法参数由@PathVariable注解注释。
    • 方法参数类型必须是Map类型。
    • 注释方法参数的@PathVariable的value属性不能有值。
  2. PathVariableMethodArgumentResolver
    在某些条件成立的情况下才会使用此类进行解析:

    • 方法参数由@PathVariable注解注释。
    • 当方法参数类型是Map时,要求其必须由@PathVariable注解注释,同时@PathVariable的value属性必须有值。

2.@RequestHeader

@RequestHeader 注解,可以把Request请求header部分的值绑定到方法的参数上。

Host                    localhost:8080
Accept                  text/html,application/xhtml+xml,application/xml;q=0.9
Accept-Language         fr,en-gb;q=0.7,en;q=0.3
Accept-Encoding         gzip,deflate
Accept-Charset          ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive              300
@RequestMapping(“/displayHeaderInfo.do”)
public void displayHeaderInfo(@RequestHeader(“Accept-Encoding”) String encoding,  @RequestHeader(“Keep-Alive”) long keepAlive)  {}

request header部分的 Accept-Encoding的值,绑定到参数encoding上了, Keep-Alive header的值绑定到参数keepAlive上。

使用的参数解析器:

  1. RequestHeaderMapMethodArgumentResolver
    在某些条件成立的情况下才会使用此类进行解析:

    • 方法参数由@RequestHeader注解注释。
    • 方法参数类型必须是Map类型。
  2. RequestHeaderMethodArgumentResolver
    在某些条件成立的情况下才会使用此类进行解析:

    • 方法参数由@RequestHeader注解注释。
    • 方法参数类型不能为Map类型。

@RequestHeader是用来处理Web请求头中的信息,随着网站的多样和多元化,@RequestHeader使用频率会越来越广泛。

3.@CookieValue

@CookieValue 可以把Request header中关于cookie的值绑定到方法的参数上。

例如有如下Cookie值:

JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84
@RequestMapping(“/displayHeaderInfo.do”)
public void displayHeaderInfo(@CookieValue(“JSESSIONID”) String cookie)  {  }

即把JSESSIONID的值绑定到参数cookie上。

使用的参数解析器:

  1. ServletCookieValueMethodArgumentResolver
    ServletCookieValueMethodArgumentResolver实现了最主要的resolveName(…)方法,用于进行参数解析。

    • Cookie使用WebUtils.getCookie(…)从NativeWebRequest中解析。
    • 若方法参数是Cookie类型,那么直接返回Cookie类型。
    • 若方法参数非Cookie类型,那么urlPathHelper.decodeRequestString(…)解析得到String类型的值。

@CookieValue注解在实际应用中,作用还是很大的,传统Web开发中,Cookie是不可绕过的一环,掌握如何快速的通过Spring框架取值,可以帮助我们更快更好的完成任务。

4.@RequestParam

  • 常用来处理简单类型的绑定,通过Request.getParameter() 获取的String可直接转换为简单类型的情况( String–> 简单类型的转换操作由ConversionService配置的转换器来完成);因为使用request.getParameter()方式获取参数,所以可以处理get 方式中queryString的值,也可以处理post方式中 body data的值;

  • 用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST;

  • 该注解有两个属性: value、required; value用来指定要传入值的id名称,required用来指示参数是否必须绑定;

使用的参数解析器:

  1. RequestParamMapMethodArgumentResolver

  2. RequestParamMethodArgumentResolve

1)RequestParamMapMethodArgumentResolver

实现了HandlerMethodArgumentResolver的supportsParameter(…)和resolveArgument(…)方法。
使用条件:

  1. 方法参数由@RequestParam注解注释
  2. 方法参数类型必须是Map类型
    • 参数类型为MultiValueMap时,返回LinkedMultiValueMap实例,包含所有请求参数
    • 参数类型为Map时,返回LinkedHashMap实例,包含所有请求参数
  3. @RequestParam注解的name不能有值

2)RequestParamMethodArgumentResolver

RequestParamMethodArgumentResolver继承自抽象AbstractNamedValueMethodArgumentResolver

除了能处理@RequestParam注解外,还可以处理@RequestPart注解。

处理@RequestParam注解的条件:

  1. 方法参数由@RequestParam注解注释。
  2. 方法参数若是Map类型时,@RequestParam的name属性不能为空。
  3. 方法参数若不是Map类型时,都可以处理。

处理@RequestPart注解的条件

  1. 方法参数不可由@RequestPart注解注释。
  2. 方法参数类型为org.springframework.web.multipart.MultipartFile、org.springframework.web.multipart.MultipartFile集合、org.springframework.web.multipart.MultipartFile数组、javax.servlet.http.Part、javax.servlet.http.Part集合或javax.servlet.http.Part数组。
  3. 一个简单类型的方法参数,包括:boolean、byte、char、short、int、long、float、double、Enum.class、CharSequence.class、Number.class、Date.class、URI.class、URL.class、Locale.class或Class.class。

@RequestParam是用来处理Web请求头中的信息,随着网站的多样和多元化,@RequestParam使用频率会越来越广泛。

5.@RequestPart

@RequestPart用于将multipart/form-data类型数据映射到控制器处理方法的参数中。除了@RequestPart注解外,@RequestParam同样可以用于此类操作。

@Controller
@RequestMapping("/test")
public class RequestPartController {/*** 跳转页面.*/@GetMapping("test1")public ModelAndView requestPartHtml(HttpServletRequest req, HttpServletResponse res, ModelMap modelMap)throws Exception {}/*** RequestPart-MultipartFile接收参数.*/@ResponseBody@PostMapping("test2")public String requestPartMultipartFile(@RequestPart("file") MultipartFile multipartFile) throws Exception {}/*** RequestPart-Part接收参数.*/@ResponseBody@PostMapping("test3")public String requestPartPart(@RequestPart("file") Part part) throws Exception {}/*** RequestParam-MultipartFile接收参数.*/@ResponseBody@PostMapping("test4")public String requestParamMultipartFile(@RequestParam("file") MultipartFile multipartFile) throws Exception {}/*** RequestParam-Part接收参数.*/@ResponseBody@PostMapping("test5")public String requestParamPart(@RequestParam("file") Part part) throws Exception {}/*** Part接收参数.*/@ResponseBody@PostMapping("test6")public String part(HttpServletRequest req) throws Exception {Part part = req.getPart("file");}}

使用的参数解析器:

  1. RequestPartMethodArgumentResolver

  2. RequestHeaderMapMethodArgumentResolver
    在某些条件成立的情况下才会使用此类进行解析:

    • 方法参数由@RequestPart注解注释。
    • 方法参数不可由@RequestParam注解注释。
    • 方法参数类型为org.springframework.web.multipart.MultipartFile、org.springframework.web.multipart.MultipartFile集合、org.springframework.web.multipart.MultipartFile数组、javax.servlet.http.Part、javax.servlet.http.Part集合或javax.servlet.http.Part数组。
  3. RequestParamMethodArgumentResolver
    参考@RequestParam中的RequestParamMethodArgumentResolver用法

@RequestPart和@RequestParam都可以处理multipart/form-data类型数据,本质上并没有区别,使用任何一个都能达到期望的效果。文件上传在实际应用中也是必不可少的。

6.@RequestBody

  • 该注解常用来处理Content-Type: 不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等;

  • 它是通过使用HandlerAdapter 配置的HttpMessageConverters来解析post data body,然后绑定到相应的bean上的。

  • 因为配置有FormHttpMessageConverter,所以也可以用来处理 application/x-www-form-urlencoded的内容,处理完的结果放在一个MultiValueMap<String, String>里,这种情况在某些特殊需求下使用

Spring MVC中使用HandlerMethodArgumentResolver策略接口来定义处理器方法参数解析器,

使用的参数解析器:

  1. RequestResponseBodyMethodProcessor

    RequestResponseBodyMethodProcessor实现相对比较负责,其功能涉及范围较广,参数绑定仅是其功能之一。RequestResponseBodyMethodProcessor实现了HandlerMethodArgumentResolver的supportsParameter(…)和resolveArgument(…)方法。

    使用此类进行解析的条件:

    1. 方法参数由@RequestBody注解注释。

    具体使用流程:
    通过resolveArgument(…)方法中readWithMessageConverters(…)用来进行请求正文的读取,方法具体内容:

    • 获取请求的Content-Type,用于后续消息转换。
    • 获取参数类型,用于参数实例化及初始化。
    • 遍历消息转换器,通过参数类型匹配可用的消息转换。
    • 调用参数转换器进行请求正文的转换。
    • 处理请求增强器:RequestBodyAdvice方法beforeBodyRead(…)、afterBodyRead(…)和handleEmptyBody(…)。

7.@SessionAttributes

该注解用来绑定HttpSession中的attribute对象的值,便于在方法中的参数里使用。

该注解有value、types两个属性,可以通过名字和类型指定要使用的attribute 对象;

@Controller
@RequestMapping(“/editPet.do”)
@SessionAttributes(“pet”)
public class EditPetForm {  }

使用的参数解析器:

  1. SessionAttributeMethodArgumentResolver

8.@ModelAttribute

该注解有两个用法,一个是用于方法上,一个是用于参数上;

  • 用于方法上时: 通常用来在处理@RequestMapping之前,为请求绑定需要从后台查询的model;

  • 用于参数上时: 用来通过名称对应,把相应名称的值绑定到注解的参数bean上;要绑定的值来源于:

    • @SessionAttributes 启用的attribute 对象上;
    • @ModelAttribute 用于方法上时指定的model对象;
    • 上述两种情况都没有时,new一个需要绑定的bean对象,然后把request中按名称对应的方式把值绑定到bean中。

用到方法上:

@ModelAttribute  public Account addAccount(@RequestParam String number) {  return accountManager.findAccount(number);  }

这种方式实际的效果就是在调用@RequestMapping的方法之前,为request对象的model里put(“account”, Account)。

用在参数上:

@RequestMapping(value=“/owners/{ownerId}/pets/{petId}/edit”, method = RequestMethod.POST)
public String processSubmit(@ModelAttribute Pet pet) {  }

首先查询 @SessionAttributes有无绑定的Pet对象,若没有则查询@ModelAttribute方法层面上是否绑定了Pet对象,若没有则将URI template中的值按对应的名称绑定到Pet对象的各属性上。

其它注解

@AliasFor

参考文章:
Spring 全面解析——Spring 注解面面通

Spring参数解析器相关推荐

  1. spring MVC使用自定义的参数解析器解析参数

    目录 写在前面 编写自定义的参数解析器解析请求参数 项目结构 定义注解 实体类 controller 定义参数解析器 注册参数解析器 启动项目 发起请求查看结果 写在前面 如果还有小伙伴不知道spri ...

  2. Spring自定义参数解析器

      虽然Spring提供了比较完善的参数解析器,但是对于一些特殊的数据类型我们还是需要进行特殊处理,这样会提高代码的复杂度,增加冗余的代码,降低代码可读性和可维护性.所以自定义参数解析器是一个很好的解 ...

  3. Spring MVC自定义类型转换器Converter、参数解析器HandlerMethodArgumentResolver

    文章目录 一.前言 二.类型转换器Converter 1.自定义类型转换器 三.参数解析器 1.自定义分页参数解析器 2.自定义注解参数解析器 一.前言 Spring MVC源码分析相关文章已出: S ...

  4. springMvc(实现HandlerMethodArgumentResolver)自定义参数解析器

    由于之前用@RequestParam无法接收request payload 正文格式为json格式的字符串,只能使用@RequestBody整个接收,觉得麻烦,但是spring自带的参数解析器不具有这 ...

  5. (十六)ATP应用测试平台——java应用中的过滤器Filter、拦截器Interceptor、参数解析器Resolver、Aop切面,你会了吗?

    前言 过滤器Filter.拦截器Interceptor.参数解析器Resolver.Aop切面是我们应用开发中经常使用到的技术,到底该如何使用这些web附属功能, 本小节我们就分别介绍一下其各自的用法 ...

  6. 【第二十一讲】参数解析器

    [第二十一讲]参数解析器 文章目录 [第二十一讲]参数解析器 1-常见参数解析器 2-组合模式在 Spring 中的体现 总结 常见参数解析器 组合模式在 Spring 中的体现 ${} #{} 小技 ...

  7. 拦截器HandlerInterceptor+方法参数解析器HandlerMethodArgumentResolver用于统一获取当前登录用户信息

    文章目录 前言 一.拦截器+方法参数解析器 是什么? 二.具体实现步骤 1.自定义权限拦截器LoginInterceptor拦截所有request请求,并将token解析为currentUser,最终 ...

  8. springmvc自定义参数解析器/类型转换器

    概述 有些时候我们需要对GET请求的入参做自定义的处理,比较常见的就是字符串反序列化时间类型了,常用的像@DateTimeFormat注解,但是这需要在每个入参的属性上都加上这个注解,比较费手,那么我 ...

  9. SpringMVC 参数解析器

    一.问题 springMVC对于下面这种接口,参数是怎么解析的: @GetMapping("/hello/{id}") public void hello3(@PathVariab ...

最新文章

  1. 使用Cookie记录信息
  2. 【计算机组成原理】十进制数串
  3. php authcode java_PHP(authcode)加密解密
  4. python如何运行源文件_Python如何运行
  5. 5分钟 0元搭建个人独立博客网站(二)
  6. OpenGL显卡编程
  7. 华为隐藏功能扩大内存代码大全_发现将华为手机这3个功能打开,竟然可以将手机性能极限发挥...
  8. OpenCV调用摄像头+灰度图+高斯滤波+Canny算子
  9. 计算机导论操作系统教案,《计算机导论》教案.doc
  10. win10任务栏太宽而且调不了_win10系统任务栏变宽了的修复方法
  11. Load Runner:了解软件安装后目录http://www.boobooke.com/bbs/thread-1959-1-1.html
  12. STM32F103ZET6---【硬件篇】定时器
  13. 偏导数与全导数的关系 以及 偏微分与全微分的关系
  14. 【转】和老外聊天、发邮件常用英语缩写
  15. 虚拟机中ip地址总是自动变化解决办法
  16. 结构体初识———结构体成员
  17. 趣聊51之串口通信(实现篇)
  18. 重磅:微信安卓 8.0 版本来了,赶紧抢先内测体验吧
  19. 探究opencv中的moments函数和HuMoments函数
  20. Problem E: 农夫果园

热门文章

  1. Java 中(hash 0x7FFFFFFF)问题 哈希表中数组下标的计算
  2. 机器学习中正则化项L1和L2
  3. 浅谈Android模块化设计(模块化的一些思考)
  4. 【Unity技术积累】代码生成菱形地图
  5. 十进制小数化为二进制小数的方法是什么_二进制和十进制之间的互相转换
  6. Mininet 上启用 DCTCP 和 ECN 进行拥塞控制、使用 HTB 和 RED 队列进行流量控制
  7. 乐1Pro 乐视X800_官方线刷包_救砖包_解账户锁
  8. Chubby 和Zookeeper 的理解
  9. 拼多多被称为“假货之王”,为什么还成功上市了?
  10. C语音编程设计 (华中科技大学出版社)华中科技大学出版社 主编:龚义建 姚远 黄玉兰 课本课后例题(编程题)