@PathVariable和@RequestParam的使用说明

要说明@PathVariable和@RequestParam的使用,首先介绍 @RequestMapping
RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
RequestMapping:Annotation for mapping web requests onto methods in request-handling classes with flexible method signatures.Both Spring MVC and Spring WebFlux support this annotation.
RequestMapping注解有六个属性,常用的是value,method;还有consumes,produces,params,headers。
value属性:指定请求的实际地址,当只设置value属性时,默认省略不写
即:@RequestMapping("/hello")或@RequestMapping(value="/hello")
value的uri值为以下三类:
A)可以指定为普通的具体值;
B)可以指定为含有某变量的值(URI Template Patterns with Path Variables);
C)可以指定为含正则表达式的值( URI Template Patterns with Regular Expressions)。

HelloController.java极简代码示例,既有PathVariable也有RequestParam

@RestController
public class HelloController {
	@RequestMapping("/hellopv/{name}")
	public String helloPV(@PathVariable String name, @RequestParam String username) {
		String hello = "Hello " + username + " [" + name + "] !";
		return hello;
	}
}

感性认识一下,测试上述代码http://cos6743:8081/hellopv/tom?username=YangTom
url
@PathVariable是处理requet uri template中variable 的注解,实现了url入参绑定到方法参数上。
即:可以获取URL请求路径中的变量值,比如:RequestMapping("/hellopv/{name}")中的name

@RequestParam获取URL请求数据,是常用来处理简单类型的绑定注解。
通过Request.getParameter()获取入参,故此可以处理url中的参数,也可以处理表单提交的参数和上传的文件。

拓展
handler method 参数绑定常用的注解,根据处理的Request的不同内容分为四类常用类型
A、处理requet uri 部分(指uri template中variable)的注解: @PathVariable;
B、处理request header部分的注解: @RequestHeader, @CookieValue;
C、处理request body部分的注解:@RequestParam, @RequestBody;
D、处理attribute类型是注解: @SessionAttributes, @ModelAttribute;

参考资料:
SpringMvc之参数绑定注解详解

猜你喜欢

转载自blog.csdn.net/weixin_44153121/article/details/86538329