天天看點

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){
    
}
           

繼續閱讀