SpringMVC框架详细教程(九)_使用 @RequestParam 将请求参数绑定至方法参数
使用 @RequestParam 将请求参数绑定至方法参数
你可以使用 @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.
相关推荐
JudeJoo 2020-08-21
meleto 2020-08-15
haidaoxianzi 2020-07-04
小鱿鱼 2020-06-26
haidaoxianzi 2020-06-14
qingjiuquan 2020-05-30
melonjj 2020-01-05
飘零的云 2014-05-11
melonjj 2019-12-25
凯哥Java 2019-12-21
咻pur慢 2019-12-16
boneix 2020-10-21
咻pur慢 2020-06-15
qingjiuquan 2020-06-07
zhangdy0 2020-05-31
HappyHeng 2020-05-16
whbing 2020-04-11
小鱿鱼 2020-03-20