Controller-请求处理

参数注解

@RequestParam 映射参数

Simple Mapping 简单映射

从URL参数 映射到函数参数。 必须保持参数名一致

例:

URL: http://localhost:8080/spring-mvc-basics/api/foos?id=abc

1
2
3
4
5
@GetMapping("/api/foos")
@ResponseBody
public String getFoos(@RequestParam String id) {
return "ID: " + id;
}

name 属性 - Specifying the Request Parameter Name 指定请求参数名

参数名不一致时,手动指定对应的请求参数名 name = "id"

1
2
3
4
5
@PostMapping("/api/foos")
@ResponseBody
public String addFoo(@RequestParam(name = "id") String fooId, @RequestParam String name) {
return "ID: " + fooId + " Name: " + name;
}

省略写法: @RequestParam(“id”)

使用属性 namevalue都可以

required 属性 - Optional Request Parameters 可选请求参数

required 缺省为 true
缺少参数时 会抛出 MissingServletRequestParameterException 异常,返回 400 错误码

required = false 缺少参数时, 方法参数 值为 null ,

1
2
3
4
5
@GetMapping("/api/foos")
@ResponseBody
public String getFoos(@RequestParam(required = false) String id) {
return "ID: " + id;
}