SpringMVC中,@RequestParam,@PathVariable,@RequestBody的使用
- @RequestParam
HTML
<form action="demo" method="post">
<input type="text" name="name">
<input type="text" name="location">
<input type="submit">
<input type="checkbox" name="h" value="h12">
<input type="checkbox" name="h" value="h2">
<input type="checkbox" name="h" value="h3">
<input type="checkbox" name="h" value="h4">
</form>
Controllor
@RequestMapping("demo")
public String demo1(@RequestParam(value="name")String name1,@RequestParam(value="h")List<String>h) {
System.out.println("demo1");
System.out.println(name1+h);
return "Main.jsp";
}
-
@RequestParam(value="name")String name1
里面的value指的是匹配的参数名是name,
为了简化,可以这样写@RequestParam String name
,前提是能保证String后面的变量名和参数名是一样的 -
@RequestParam(value="h")List<String>h
可以接受复杂参数。 -
@RequestBody
传递的是json字符串,用在参数前 -
可以直接传递pojo比如:
@RequestMapping(value="demo",method = RequestMethod.POST)
@ResponseBody
public Peoplle demo1(Peoplle peoplle) {
System.out.println(peoplle);
return peoplle;
}
打印出来的数据 `Peoplle [name=张三, location=里斯]`
- 当参数为空的时候,防止报错,可以设置默认值
@RequestMapping("demo")
public String demo1(@RequestParam(defaultValue="null") Peoplle peoplle) {
System.out.println("demo1");
System.out.println(peoplle);
return "Main.jsp";
- 强制参数不能为空,否则报错
@RequestMapping("demo")
public String demo1(@RequestParam(required=true) Peoplle peoplle) {
System.out.println("demo1");
System.out.println(peoplle);
return "Main.jsp";
}
- @PathVariable
直接看代码吧
@Controller
public class DemoControler {
@RequestMapping("/demo/{id}")
public void demo1(@PathVariable String id) {
System.out.println(id);
}
console:da