Spring校驗@RequestParams和@PathVariables引數
我們在寫Rest API介面時候會用到很多的@RequestParam和@PathVariable進行引數的傳遞,但是在校驗的時候,不像使用@RequestBody那樣的直接寫在實體類中,我們這篇文章講解一下如何去校驗這些引數。
依賴配置
- 要使用Java Validation API,我們必須新增validation-api 依賴項:
<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.1.Final</version> </dependency>
- 通過新增@Validated註解來啟用控制器中的@RequestParams和@PathVariables的驗證:
@RestController @RequestMapping("/") @Validated public class Controller { // ... }
校驗@RequestParam
- 我們將數字作為請求引數傳遞給控制器方法
@GetMapping("/name-for-day") public String getNameOfDayByNumber(@RequestParam Integer dayOfWeek) { // ... }
- 我們保證dayOfWeek的值在1到7之間,我們使用@Min和@Max註解
@GetMapping("/name-for-day") public String getNameOfDayByNumber(@RequestParam @Min(1) @Max(7) Integer dayOfWeek) { // ... }
任何與這些條件不匹配的請求都將返回HTTP狀態500,並顯示預設錯誤訊息。
如果我們嘗試呼叫http://localhost:8080/name-for-day?dayOfWeek=24 這將返回以下響應資訊:
There was an unexpected error (type=Internal Server Error, status=500). getNameOfDayByNumber.dayOfWeek: must be less than or equal to 7
當然我們也可以在@Min和@Max註解後面加上message
引數進行修改預設的返回資訊。
校驗@PathVariable
和校驗@RequestParam一樣,我們可以使用javax.validation.constraints包中的註解來驗證@PathVariable。
- 驗證String引數不是空且長度小於或等於10
@GetMapping("/valid-name/{name}") public void test(@PathVariable("name") @NotBlank @Size(max = 10) String username) { // ... }
- 任何名稱引數超過10個字元的請求都會導致以下錯誤訊息:
There was an unexpected error (type=Internal Server Error, status=500). createUser.name:size must be between 0 and 10
通過在@Size註解中設定message引數,可以覆蓋預設訊息。
其實我們可以看到校驗@RequestParam和@PathVariable引數和我們校驗@RequestBody方式一致,只不過一個是寫在了實體中,一個寫在了外部,當然我們也可以將@RequestParam的引數寫入到實體類中,進行使用@RequestParam註解進行引入,比如我們使用一個分頁的例項
- 分頁實體類
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements.See the NOTICE file * distributed with this work for additional information * regarding copyright ownership.The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License.You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhuanqb.param.page; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; /** * PageParam <br/> * 描述 : PageParam <br/> * 作者 : qianmoQ <br/> * 版本 : 1.0 <br/> * 建立時間 : 2018-09-23 下午7:40 <br/> * 聯絡作者 : <a href="mailTo:[email protected]">qianmoQ</a> */ @Data @ToString @NoArgsConstructor @AllArgsConstructor public class PageParam { @NotNull(message = "每頁資料顯示數量不能為空") @Min(value = 5) @Max(value = 100) private Integer size; // 每頁數量 @NotNull(message = "當前頁顯示數量不能為空") @Min(value = 1) @Max(value = Integer.MAX_VALUE) private Integer page; // 當前頁數 private Boolean flag = true; }
- @RequestParam呼叫方式
@GetMapping(value = "list") public CommonResponseModel findAll(@Validated PageParam param) { ... }
這樣的話可以使我們的校驗定製化更加簡單。