在spring-bootrestapi中傳遞和驗證RequestParam
@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); } }
- @Validated - 對控制器的每個方法執行驗證(如果有)。
- @RequestParam - 在變數中接受Web請求引數。(注意 :所有使用@RequestParam 註釋的變數接受的請求引數都是強制對應的,除非該引數設定required = false @RequestParam(required = false) )
- javax.validation.constraints 的@Size 用於驗證請求引數的長度,不符合條件將丟擲 ConstraintViolationException 。
- @RequestParam String middlename,:接受變數middlename中的 強制對應 引數。如果請求中不存在引數,則spring將丟擲 MissingServletRequestParameterException
- @RequestParam(required = false) String lastname):接受變數lastname中的 可選 引數。
@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,則更加使得程式碼精簡,然後使用ofollow,noindex" target="_blank">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, ... }