我們在寫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:shichengoooo@163.com">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) {...}
這樣的話可以使我們的校驗定制化更加簡單。