java param request_使用@RequestParam将请求参数绑定至方法参数
正版2本grasshopper入門晉級手冊
101.5元
包郵
(需用券)
去購買 >
你可以使用 @RequestParam 注解將請求參數綁定到你控制器的方法參數上。
下面這段代碼展示了它的用法:
package com.pudding.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class EditPetForm {
@GetMapping("/pets")
public String setupForm(@RequestParam int petId) {
System.out.println(petId);
return "petForm";
}
}
若參數使用了該注解,則該參數默認是必須提供的,但你也可以把該參數標注為非必須的:只需要將 @RequestParam 注解的 required 屬性設置為 false 即可:
package com.pudding.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class EditPetForm {
@GetMapping("/pets")
public String setupForm(@RequestParam(value = "petId", required = false) Integer petId) {
System.out.println(petId);
return "petForm";
}
}
注意:這里使用的 required = false 是將請求的參數設置為 null ,所以方法里的參數需要為引用類型(Integer),如果使用的是基本類型(int)會出現以下錯誤:
java.lang.IllegalStateException: Optional int parameter 'petId' is present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type.
java 11官方入門(第8版)教材
79.84元
包郵
(需用券)
去購買 >
總結
以上是生活随笔為你收集整理的java param request_使用@RequestParam将请求参数绑定至方法参数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java加法器_javacc例子:加法器
- 下一篇: java scanner类int_Jav