欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

@PathVariable和@RequestParam傳參為空問題及解決

 更新時間:2021年11月05日 09:18:28   作者:眉梢i  
這篇文章主要介紹了@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

小結(jié)一下

required = false屬性設(shè)置前端可以不傳數(shù)據(jù),當在使用@RequestParam時直接寫上,不需要改變地址映射,當使用@PathVariable時,需要在地址映射上面寫入多個地址映射。而且必須寫required = false,不然報500

使用@pathvariable與@requestparam碰到的問題

1.@pathvariable

可以將 URL 中占位符參數(shù)綁定到控制器處理方法的入?yún)⒅校篣RL 中的 {x} 占位符可以通過@PathVariable("x") 綁定到操作方法的入?yún)⒅小?/p>

@GetMapping("/test/{id}")
public String test(@PathVariable("id") String id){
    System.out.println("test:"+id);
    return SUCCESS;
}

可以看出使用@pathvariable注解它直接從url中取參,但是如果參數(shù)是中文就會出現(xiàn)亂碼情況,這時應(yīng)該使用@requestparam注解

2.@requestparam

它是直接從請求中取參,它是直接拼接在url后面(demo?name=張三)

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

注:如果參數(shù)不必須傳入的話,我們從源碼中可以看出兩者required默認為true,如圖:

所以我們可以這樣寫,只寫一個例子

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

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論