软件编程
位置:首页>> 软件编程>> java编程>> @PathVariable和@RequestParam传参为空问题及解决

@PathVariable和@RequestParam传参为空问题及解决

作者:眉梢i  发布时间:2023-01-06 02:27:00 

标签:@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

@PathVariable和@RequestParam传参为空问题及解决

http://localhost:8080/xie

@PathVariable和@RequestParam传参为空问题及解决

http://localhost:8080/xie1

@PathVariable和@RequestParam传参为空问题及解决

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

@PathVariable和@RequestParam传参为空问题及解决

小结一下

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,如图:

@PathVariable和@RequestParam传参为空问题及解决

@PathVariable和@RequestParam传参为空问题及解决

所以我们可以这样写,只写一个例子


@GetMapping("/demo")
public String test(@requestparam(value="name", required = false) String name){
    System.out.println("test:"+name);
    return SUCCESS;
}

来源:https://blog.csdn.net/qq_45225798/article/details/120473289

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com