Spring校驗@RequestParams和@PathVariables參數

咱們在寫Rest API接口時候會用到不少的@RequestParam和@PathVariable進行參數的傳遞,可是在校驗的時候,不像使用@RequestBody那樣的直接寫在實體類中,咱們這篇文章講解一下如何去校驗這些參數。java

依賴配置


  • 要使用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,並顯示默認錯誤消息。express

若是咱們嘗試調用http://localhost:8080/name-for-day?dayOfWeek=24這將返回如下響應信息:apache

There was an unexpected error (type=Internal Server Error, status=500).
getNameOfDayByNumber.dayOfWeek: must be less than or equal to 7

固然咱們也能夠在@Min和@Max註解後面加上message參數進行修改默認的返回信息。api

校驗@PathVariable


和校驗@RequestParam同樣,咱們能夠使用javax.validation.constraints包中的註解來驗證@PathVariable。app

  • 驗證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參數,能夠覆蓋默認消息。less

其實咱們能夠看到校驗@RequestParam和@PathVariable參數和咱們校驗@RequestBody方式一致,只不過一個是寫在了實體中,一個寫在了外部,固然咱們也能夠將@RequestParam的參數寫入到實體類中,進行使用@RequestParam註解進行引入,好比咱們使用一個分頁的實例maven

  • 分頁實體類
/**
 * 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) {
        ...
    }

這樣的話能夠使咱們的校驗定製化更加簡單。ui

相關文章
相關標籤/搜索