Springboot中@RequestParam和@PathVariable詳解

@RequestParam

@RequestParam註解一般是加在Controller的方法參數上

下面我們來分析一下加@RequestParam與不加@RequestParam的區別

第一種情況,加@RequestParam

@RequestMapping("/test")
public void test(@RequestParam Integer testId){
    
}

@RequestParam註解默認的屬性值required爲true,代表必須加參數。也就是說 ,上面的Controller訪問的時候必須是 localhost:8080/test?testId=xxx


第二種情況,不加@RequestParam

@RequestMapping("/test")
public void test(Integer testId){
    
}

不加@RequestParam,代表可加參數或不加參數都能訪問

也就是說localhost:8080/test?testId=xxx 和 localhost:8080/test都能訪問到。

@RequestParam註解除了required屬性,還有幾個常用的參數defaultValue、value等

defaultValue

@RequestMapping("/test")
public void test(@RequestParam(defaultValue = "0") Integer testId){
    
}

這樣的話,帶了參數就會接收參數,不帶參數就使用默認值作爲testId的值


value

@RequestMapping("/test")
public void test(@RequestParam(value = "id") Integer testId){
    
}

這樣訪問的時候就可以這樣訪問 localhost:8080/test?id=xxx


@PathVariable

@RequestParam和@PathVariable都能夠完成類似的功能,本質上,都是用戶的輸入,只不過輸入的部分不同,@PathVariable在URL路徑部分輸入,而@RequestParam在請求的參數部分輸入。

示例:

@RequestMapping("/test/{testId}")
public void test(@PathVariable("testId") Integer id){
    
}

當我們輸入 localhost:8080/test/xxx的時候,就會把xxx的值綁定到 id 上。

URL 中的 {xxx} 佔位符可以通過@PathVariable(“xxx“) 綁定到操作方法的入參中,當@PathVariable不指定括號裏的值(“xxx”)有且只有一個參數時,URL 中的 {xxx} 必須跟入參屬性的命名一致上。

也就是說下面的代碼同樣能用localhost:8080/test/xxx訪問到

@RequestMapping("/test/{id}")
public void test(@PathVariable Integer id){
    
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章