java param request_使用@RequestParam将请求参数绑定至方法参数
正版2本grasshopper入門晉級(jí)手冊(cè)
101.5元
包郵
(需用券)
去購(gòu)買 >
你可以使用 @RequestParam 注解將請(qǐng)求參數(shù)綁定到你控制器的方法參數(shù)上。
下面這段代碼展示了它的用法:
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";
}
}
若參數(shù)使用了該注解,則該參數(shù)默認(rèn)是必須提供的,但你也可以把該參數(shù)標(biāo)注為非必須的:只需要將 @RequestParam 注解的 required 屬性設(shè)置為 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 是將請(qǐng)求的參數(shù)設(shè)置為 null ,所以方法里的參數(shù)需要為引用類型(Integer),如果使用的是基本類型(int)會(huì)出現(xiàn)以下錯(cuò)誤:
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元
包郵
(需用券)
去購(gòu)買 >
總結(jié)
以上是生活随笔為你收集整理的java param request_使用@RequestParam将请求参数绑定至方法参数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java加法器_javacc例子:加法器
- 下一篇: java scanner类int_Jav