@PathVariable和@RequestParam的使用说明

本文深入解析了@RequestMapping注解的功能及使用场景,包括其六个属性的详细解释,并对比了@PathVariable与@RequestParam的作用与区别,帮助读者掌握Spring MVC中请求映射与参数绑定的核心概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

要说明@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之参数绑定注解详解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值