@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中取參,但是如果參數是中文就會出現(xiàn)亂碼情況,這時應該使用@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連接Hive實現(xiàn)自助取數的示例
這篇文章主要介紹了SpringBoot連接Hive實現(xiàn)自助取數的示例,幫助大家更好的理解和使用springboot框架,感興趣的朋友可以了解下2020-12-12淺談java String.split丟失結尾空字符串的問題
下面小編就為大家?guī)硪黄獪\談java String.split丟失結尾空字符串的問題。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02springboot的SpringPropertyAction事務屬性源碼解讀
這篇文章主要介紹了springboot的SpringPropertyAction事務屬性源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11