springboot控制層傳遞參數(shù)為非必填值
需求是查詢(xún)?nèi)吭u(píng)價(jià)時(shí),后端控制層的level為非必選項(xiàng),即為空。
這里@requestparam(required=false)就可以處理level為非必須值的情況。
如果沒(méi)有這一行,當(dāng)level為空時(shí),會(huì)返回空白頁(yè)面。
這里要注意一下!是個(gè)坑
controller層接收參數(shù)的形式
1.參數(shù)存在于請(qǐng)求路徑中
1.請(qǐng)求的參數(shù):http://localhost:8080/postman/123
123作為參數(shù)傳遞到后臺(tái),接收方法:使用@pathvariable注解
@pathvariable是spring3.0的一個(gè)新功能:接收請(qǐng)求路徑中占位符的值
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( "接收到的參數(shù)" +id); } } |
2.請(qǐng)求的參數(shù):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( "接收到的參數(shù)" +id); //接收到的參數(shù)1234 } |
2.參數(shù)在請(qǐng)求體中
1.參數(shù)以k-v鍵值對(duì)的形式發(fā)送
后臺(tái)接收
1
2
3
4
|
@postmapping public void testpost3(person person){ system.out.println( "接收到的參數(shù)" +person); //接收到的參數(shù)person(name=笑爛臉, age=23, sex=男) } |
2.參數(shù)以json對(duì)象的形式發(fā)送
注:前后端分離的項(xiàng)目,參數(shù)一般都是以json對(duì)象的形式發(fā)送
后臺(tái)接收
1
2
3
4
|
@postmapping public void testpost4( @requestbody person person){前后端分離的項(xiàng)目,前端傳遞的數(shù)據(jù)都是json對(duì)象,所以后臺(tái)想要接受對(duì)應(yīng)的數(shù)據(jù),必須要加 @requestbody 注解,否則接收不了 system.out.println( "接收到的參數(shù)" +person); //接收到的參數(shù)person(name=笑爛臉, age=23, sex=男) } |
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家.
原文鏈接:https://blog.csdn.net/wonderbell/article/details/113251988