@RequestParam将方法参数绑定到Web请求参数,语法:
@RequestParam <数据类型> <变量名称>;
代码案例:
@RestController
@RequestMapping("/api")
@Validated
public class HelloWorldController {
@GetMapping("/hello")
public ResponseEntity<?> sayHello(
@RequestParam @Size(min= 1, max = 5, message =
"firstname length must be between 1 and 5") String firstname,
@RequestParam String middlename,
@RequestParam(required = false) String lastname){
/* check lastname value */
lastname = lastname != null ? lastname : "{lastname-is-optional}";
return ResponseEntity.ok("Hello " + firstname + " " + middlename + " " + lastname);
}
}
如果结合Swagger的API注释,你的代码如下:
@ApiOperation(value = "")
@RequestMapping(method = GET, value = "/customcollection/{id}/data")
public Iterable<CustomeType> getData(@ApiParam(value = "The identifier of the time series.")
@PathVariable String id,
@ApiParam(name = "startDate", value = "start date", defaultValue = "")
@RequestParam("startDate") String startDate,
@ApiParam(name = "endDate", value = "end date", defaultValue = "")
@RequestParam("endDate") String endDate)
其中ApiParam是swagger的参数,RequestParam是REST API,如果使用模型对象替代一个个RequestParam,则更加使得代码精简,然后使用 JSR 303:Bean Validation 对模型对象中字段进行校验:
public class Person {
@NotNull
private int id;
@NotBlank
@Size(min = 1, max = 20)
private String firstName;
@NotBlank
@Pattern(regexp ="[SOME REGULAR EXPRESSION]")
private String lastName;
@Min(0)
@Max(100)
private int age;
//... Constructor, getters, setters, ...
}