Spring校验@RequestParams和@PathVariables参数

栏目: Java · 发布时间: 5年前

内容简介:我们在写Rest API接口时候会用到很多的@RequestParam和@PathVariable进行参数的传递,但是在校验的时候,不像使用@RequestBody那样的直接写在实体类中,我们这篇文章讲解一下如何去校验这些参数。任何与这些条件不匹配的请求都将返回HTTP状态500,并显示默认错误消息。如果我们尝试调用

我们在写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) {
        ...
    }

这样的话可以使我们的校验定制化更加简单。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Facebook Effect

The Facebook Effect

David Kirkpatrick / Simon & Schuster / 2010-6-8 / USD 26.00

《Facebook 效应》的作者近距离地采访了与Facebook相关的人士,其中包括Facebook的创始人、员工、投资人、意向投资人以及合作伙伴,加起来超过了130人。这是真切详实的访谈,更是超级精彩的故事。作者以其细腻的笔触,精巧的叙事结构,解密了Facebook如何从哈佛的宿舍里萌发,创始人的内讧,权力之争,如何放弃华盛顿邮报的投资,怎样争取到第一个广告客户,而第一轮融资又如何获得一亿美元的......一起来看看 《The Facebook Effect》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

SHA 加密
SHA 加密

SHA 加密工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具