@PathVariable和@RequestParam传参为空问题及解决
@PathVariable和@RequestParam传参为空
@RestController
public class UserController {
@GetMapping(value = {"/xie/{name}","/xie"})
public String xie(@PathVariable(value = "name",required=false) String name){
return "my name is:"+name;
}
@GetMapping("/xie1")
public String xie1(@RequestParam(value = "name",required = false) String name){
return "my name is:"+name;
}
}
访问地址:
http://localhost:8080/xie/qiao

http://localhost:8080/xie

http://localhost:8080/xie1

http://localhost:8080/xie1?name=qiao

小结一下
required = false属性设置前端可以不传数据,当在使用@RequestParam时直接写上,不需要改变地址映射,当使用@PathVariable时,需要在地址映射上面写入多个地址映射。而且必须写required = false,不然报500
使用@pathvariable与@requestparam碰到的问题
1.@pathvariable
可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {x} 占位符可以通过@PathVariable("x") 绑定到操作方法的入参中。
@GetMapping("/test/{id}")
public String test(@PathVariable("id") String id){
System.out.println("test:"+id);
return SUCCESS;
}
可以看出使用@pathvariable注解它直接从url中取参,但是如果参数是中文就会出现乱码情况,这时应该使用@requestparam注解
2.@requestparam
它是直接从请求中取参,它是直接拼接在url后面(demo?name=张三)
@GetMapping("/demo")
public String test(@requestparam(value="name") String name){
System.out.println("test:"+name);
return SUCCESS;
}
注:如果参数不必须传入的话,我们从源码中可以看出两者required默认为true,如图:

所以我们可以这样写,只写一个例子
@GetMapping("/demo")
public String test(@requestparam(value="name", required = false) String name){
System.out.println("test:"+name);
return SUCCESS;
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
- springboot中@RequestParam和@PathVariable区别
- SpringBoot中@PathVariable、@RequestParam和@RequestBody的区别和使用详解
- Spring中@PathVariable和@RequestParam注解的用法区别
- Spring中@RequestParam、@RequestBody和@PathVariable的用法详解
- Springboot中@RequestParam和@PathVariable的用法与区别详解
- @PathVariable、@RequestParam和@RequestBody的区别
- 方法参数属性params,@PathVariable和@RequestParam用法及区别
- 使用@pathvariable与@requestparam碰到的一些问题及解决
- 聊聊@RequestParam,@PathParam,@PathVariable等注解的区别
- Java中@PathVariable 和 @RequestParam的区别小结
相关文章
浅谈Spring Boot、MyBatis、MyBatis-Plus 依赖版本对应关系
本文主要介绍了SpringBoot、MyBatis和MyBatis-Plus的依赖版本对应关系,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2024-11-11


最新评论