目录
- springboot控制层传递参数为非必填值
-
controller层接收参数的形式
- 1.参数存在于请求路径中
- 2.参数在请求体中
springboot控制层传递参数为非必填值
需求是查询全部评价时,后端控制层的level为非必选项,即为空。
这里@requestparam(required=false)就可以处理level为非必须值的情况。
如果没有这一行,当level为空时,会返回空白页面。
这里要注意一下!是个坑


controller层接收参数的形式
1.参数存在于请求路径中
1.请求的参数:http://localhost:8080/postman/123
123作为参数传递到后台,接收方法:使用@pathvariable注解
@pathvariable是spring3.0的一个新功能:接收请求路径中占位符的值
?| 1 2 3 4 5 6 7 8 9 10 11 |
@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”)
?| 1 2 3 4 5 6 7 |
/*
localhost:8080/postman?id=1234
*/
@getmapping
public void testpost2(@requestparam("id") long id){
system.out.println("接收到的参数"+id);//接收到的参数1234
}
|
2.参数在请求体中
1.参数以k-v键值对的形式发送

后台接收
?| 1 2 3 4 |
@postmapping
public void testpost3(person person){
system.out.println("接收到的参数"+person);//接收到的参数person(name=笑烂脸, age=23, sex=男)
}
|
2.参数以json对象的形式发送
注:前后端分离的项目,参数一般都是以json对象的形式发送

后台接收
?| 1 2 3 4 |
@postmapping
public void testpost4(@requestbody person person){前后端分离的项目,前端传递的数据都是json对象,所以后台想要接受对应的数据,必须要加@requestbody注解,否则接收不了
system.out.println("接收到的参数"+person);//接收到的参数person(name=笑烂脸, age=23, sex=男)
}
|
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家.
原文链接:https://blog.csdn.net/wonderbell/article/details/113251988








发表评论
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。