springboot控制层传递参数为非必填值

需求是查询全部评价时,后端控制层的level为非必选项,即为空。

这里@RequestParam(required=false)就可以处理level为非必须值的情况。

如果没有这一行,当level为空时,会返回空白页面。

这里要注意一下!是个坑

Controller层接收参数的形式

1.参数存在于请求路径中

1.请求的参数:http://localhost:8080/postman/123

123作为参数传递到后台,接收方法:使用@PathVariable注解

@PathVariable是spring3.0的一个新功能:接收请求路径中占位符的值

@RestController
@RequestMapping("postman")
public class controllerTest {
    /*
            localhost:8080/postman/***
     */
    @PostMapping("{id}")
    public void testPost(@PathVariable("id") Long id){
        System.out.println("接收到的参数"+id);
    }
}

2.请求的参数:http://localhost:8080/postman?id=123

接收方法:使用注解@RequestParam(“id”)

   /*
            localhost:8080/postman?id=1234
     */
    @GetMapping
    public void testPost2(@RequestParam("id") Long id){
        System.out.println("接收到的参数"+id);//接收到的参数1234
    }

2.参数在请求体中

1.参数以K-V键值对的形式发送

后台接收

@PostMapping
public void testPost3(Person person){
   System.out.println("接收到的参数"+person);//接收到的参数Person(name=笑烂脸, age=23, sex=男)
}

2.参数以json对象的形式发送

注:前后端分离的项目,参数一般都是以JSON对象的形式发送

后台接收

@PostMapping
public void testPost4(@RequestBody Person person){前后端分离的项目,前端传递的数据都是json对象,所以后台想要接受对应的数据,必须要加@RequestBody注解,否则接收不了
    System.out.println("接收到的参数"+person);//接收到的参数Person(name=笑烂脸, age=23, sex=男)
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持悠悠之家.

点赞(154)

评论列表共有 0 条评论

立即
投稿
返回
顶部