Springboot—@RequestParam和@PathVariable详解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a549654065/article/details/89366741

@RequestParam

@RequestParam注解一般是加在Controller的方法参数上

下面我们来分析一下加@RequestParam与不加@RequestParam的区别

第一种情况,加@RequestParam

@RequestMapping("/test")
public void test(@RequestParam Integer testId){
    
}

@RequestParam注解默认的属性值required为true,代表必须加参数。也就是说 ,上面的Controller访问的时候必须是 localhost:8080/test?testId=xxx


第二种情况,不加@RequestParam

@RequestMapping("/test")
public void test(Integer testId){
    
}

不加@RequestParam,代表可加参数或不加参数都能访问

也就是说localhost:8080/test?testId=xxxlocalhost:8080/test都能访问到。



@RequestParam注解除了required属性,还有几个常用的参数defaultValue、value等

defaultValue

@RequestMapping("/test")
public void test(@RequestParam(defaultValue = "0") Integer testId){
    
}

这样的话,带了参数就会接收参数,不带参数就使用默认值作为testId的值


value

扫描二维码关注公众号,回复: 6063639 查看本文章
@RequestMapping("/test")
public void test(@RequestParam(value = "id") Integer testId){
    
}

这样访问的时候就可以这样访问 localhost:8080/test?id=xxx


@PathVariable

@RequestParam和@PathVariable都能够完成类似的功能,本质上,都是用户的输入,只不过输入的部分不同,@PathVariable在URL路径部分输入,而@RequestParam在请求的参数部分输入。

示例:

@RequestMapping("/test/{testId}")
public void test(@PathVariable("testId") Integer id){
    
}

当我们输入 localhost:8080/test/xxx的时候,就会把xxx的值绑定到 id 上。

URL 中的 {xxx} 占位符可以通过@PathVariable(“xxx“) 绑定到操作方法的入参中,当@PathVariable不指定括号里的值(“xxx”)有且只有一个参数时,URL 中的 {xxx} 必须跟入参属性的命名一致上。

也就是说下面的代码同样能用localhost:8080/test/xxx访问到

@RequestMapping("/test/{id}")
public void test(@PathVariable Integer id){
    
}

猜你喜欢

转载自blog.csdn.net/a549654065/article/details/89366741