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

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

Spring校验@RequestParams和@PathVariables参数相关推荐

  1. 在Spring MVC中使用注解的方式校验RequestParams

    概述   Spring MVC支持Bean Validation,通过这个验证技术,可以通过注解方式,很方便的对输入参数进行验证,之前使用的校验方式,都是基于Bean对象的,但是在@RequestPa ...

  2. java requestparams_详解在Spring MVC中使用注解的方式校验RequestParams

    概述 Spring MVC支持Bean Validation,通过这个验证技术,可以通过注解方式,很方便的对输入参数进行验证,之前使用的校验方式,都是基于Bean对象的,但是在@RequestPara ...

  3. 使用 Spring Validation 优雅地进行参数校验

    引言 不知道大家平时的业务开发过程中 controller 层的参数校验都是怎么写的?是否也存在下面这样的直接判断? public String add(UserVO userVO) {if(user ...

  4. Spring(十)--Spring校验

    Spring校验使用场景 Spring常规校验 Spring数据绑定 SpringWeb参数绑定 SpringWebMVC/SpringWebFlux处理方法参数校验 Validator接口设计 接口 ...

  5. Spring AOP切面的时候参数的传递

    Spring AOP切面的时候参数的传递 Xml: <?xml version="1.0" encoding="UTF-8"?> <beans ...

  6. 掌握 Spring Boot 运行内存及内存参数设置:助力高效应用部署与优化

    pring Boot 是当今非常流行的 Java 应用框架之一,在企业级应用开发中被广泛使用.应用部署和优化是企业级应用开发的一个非常重要的方面.在这篇博客中,我们将学习如何掌握 Spring Boo ...

  7. 企业实战之Spring拦截器《统一参数校验》

    在前面的一些文章中我们有讲到,通过拦截器我们可以做很多的事情,包括接口统一的 参数校验. 登录校验.权限校验等,也可以做一些HTTP响应体写入逻辑,比如我们另一篇文章所说的<解决跨域问题> ...

  8. Spring Boot 拦截器 请求参数MD5签名校验

    拦截器定义 /*** 拦截器 请求参数签名校验* Created by jiyang on 14:47 2017/12/14*/ @Component @Slf4j public class Para ...

  9. 【Spring】Spring hibernate JSR-303 Validator 自定义参数校验器

    1.概述 在默认的情况下 Spring Boot 会引入关于 Hibernate Validator 机制来支持 JSR-303 验证规范:另外一方面 , 因为业务会 比较复杂,所以需要 自 定义验证 ...

最新文章

  1. python快速编程入门课后简答题答案-Python编程:从入门到实践(课后习题8)
  2. 不同平台上安装python的方式是一样的对还是错_不可以在同一台计算机上安装多个不同的Python版本...
  3. jQuery选择器之可见性过滤选择器Demo
  4. 面向对象编程--之二
  5. CVE-2019-15107 Webmin远程命令执行漏洞复现
  6. 目标检测回归损失函数——L1、L2、smooth L1
  7. CyclicBarrier多线程
  8. 关于位域如何节省内存(C++)
  9. tensorflow-训练(train)/测试(test)
  10. ROS学习—【在solidworks环境中将六自由度机械臂转换为URDF模型】
  11. Java编程基础知识(一)
  12. K60解锁以及IAR Missing or malformed ...FlashK60Dxxx128K.flash错误的修改
  13. Python获取基金收益计算
  14. 手机版浏览器f12_小科普 | 如何用浏览器的F12装逼?
  15. Blender建模(一)
  16. 英语中容易混淆的单词发音: 一
  17. 根据微信公众号关注/取消关注事件,获取用户信息
  18. android lint 安全检测,Android Lint检查
  19. 35美元与35万美元
  20. 通过C编程实现病毒的文件感染功能…

热门文章

  1. java 并发模型总类_java并发编程系列-内存模型基础
  2. C++右值引用与转移语义
  3. 事物传递机制、应用、加载时机
  4. 关于颜色值透明度的设置
  5. 使用最大似然法来求解线性模型(1)
  6. 数据结构——各排序算法的比较
  7. 什么是SNAT、DNAT?
  8. android 自定义text,android – 使用自定义textSize实现自定义TextView
  9. android 过滤数组中的重复元素,Flutter List数组避免插入重复数据的实现
  10. rabbin负载均衡