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: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) {...}

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/275786.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

出色的社区网站_《最后的我们》中出色的制作系统

出色的社区网站游戏设计分析 (GAME DESIGN ANALYSIS) The Last of Us became an instant classic the day it was released, back in 2013. At the sunset of the sixth console generation, it felt like Naughty Dog managed to raise the bar in all critical areas of game…

入坑 Electron 开发跨平台桌面应用

‍作为一个跨平台的桌面应用开发框架&#xff0c;Electron 的迷人之处在于&#xff0c;它是建立在 Chromium 和 Node.js 之上的 —— 二位分工明确&#xff0c;一个负责界面&#xff0c;一个负责背后的逻辑&#xff0c;典型的「你负责貌美如花&#xff0c;我负责赚钱养家」。上…

Google 拼音会导致卡 Ctrl 键?

如果你使用 Windows 7 系统&#xff0c;并同时安装了 Google 输入法&#xff0c;那么 Firefox 启动时、WoW 时一定也常遇到卡住 Ctrl 键的问题。 今天仔细搜索了下&#xff0c;传说将输入法中“Ctrl键快速定位”关闭即可&#xff0c;有待验证&#xff0c;先记录着…转载于:http…

java 接口编程_JAVA面向接口编程

一、什么是面向接口编程要正确地使用Java语言进行面向对象的编程&#xff0c;从而提高程序的复用性&#xff0c;增加程序的可维护性、可扩展性&#xff0c;就必须是面向接口的编程。面向接口的编程就意味着&#xff1a;开发系统时&#xff0c;主体构架使用接口&#xff0c;接口…

不仅仅是手机,MWC现全球首例 5G NR 商用部署

近日&#xff0c;MWC大会在在巴塞罗那举行&#xff0c;5G折叠手机和5G部署进度成为这届大会的重点。除了华为与三星发布的折叠手机外&#xff0c;本届大会另一个值得关注的要点是三星和赛灵思宣布推进5G NR 商用部署在韩国落地&#xff0c;这应该是全球首例 5G 新无线电 (NR) 商…

小程序 显示细线_精心设计:高密度显示器上的细线

小程序 显示细线Despite the many benefits of Retina displays, there is one clear drawback that must be considered when designing for high-density screens:尽管Retina显示器具有许多优点&#xff0c;但在设计高密度屏幕时仍必须考虑一个明显的缺点&#xff1a; 必须避…

React 入门手册

大家好&#xff0c;我是若川。推荐这篇可收藏的React入门手册。也推荐之前一篇类似的文章《如何使用 React 和 React Hooks 创建一个天气应用》。点击下方卡片关注我、加个星标React 是目前为止最受欢迎的 JavaScript 框架之一&#xff0c;而且我相信它也是目前最好用的开发工具…

函数04 - 零基础入门学习C语言35

第七章&#xff1a;函数04 让编程改变世界 Change the world by program 上节课的练习简单讲解,给力&#xff01;&#xff01; 1.自己实现pow()函数并尝试验证…… 2.猜想下sqrt()函数的原理并尝试编程……&#xff08;暂时只要求整型数据&#xff09; 3.编写一个用来统…

java数据结构与算法_清华大学出版社-图书详情-《数据结构与算法分析(Java版)》...

前 言数据结构是计算机程序设计重要的理论技术基础&#xff0c;它不仅是计算机学科的核心课程&#xff0c;而且已经成为计算机相关专业必要的选修课。其要求是学会分析、研究计算机加工的数据结构的特性&#xff0c;初步掌握算法的时间和空间分析技术&#xff0c;并能够编写出结…

根号 巴比伦_建立巴比伦卫生设计系统

根号 巴比伦重点 (Top highlight)In this post I’ll explain the first phase of creating our Babylon DNA, the design system for Babylon Health, and how we moved the Babylon design team from Sketch to Figma.在这篇文章中&#xff0c;我将解释创建巴比伦DNA的第一阶…

《Migrating to Cloud-Native Application Architectures》学习笔记之Chapter 2. Changes Needed

2019独角兽企业重金招聘Python工程师标准>>> Cultural Change 文化变革 A great deal of the changes necessary for enterprise IT shops to adopt cloud-native architectures will not be technical at all. They will be cultural and organizational changes t…

前端,你要知道的SEO知识

大家好&#xff0c;我是若川。三天假期总是那么短暂&#xff0c;明天就要上班了。今天推荐一篇相对简单的文章。点击下方卡片关注我、加个星标之前有同学在前端技术分享时提到了SEO&#xff0c;另一同学问我SEO是什么&#xff0c;我当时非常诧异&#xff0c;作为前端应该对SEO很…

编制网站首页的基本原则

编制网站首页的基本原则如下&#xff1a; 1、编制网站首页的超文本文档的组织结构应清晰&#xff0c;条理分明&#xff0c;重点突出&#xff0c;可读性强&#xff0c;尽可能吸引用户的注意力。 2、说明文字应简明扼要&#xff0c;切中要害&#xff0c;每项内容介绍尽可能简单明…

MySQL数据库语句总结

增insert into -- 删 delete from -- 改 update table名字 set -- 查 select * from -- 一&#xff0e;SQL定义 SQL&#xff08;Structure Query Language&#xff09;结构化查询语言&#xff1a; &#xff08;一&#xff09;DDL&#xff08;Data Definition Language&#…

高安全性同态加密算法_坏的同态性教程

高安全性同态加密算法I was going to write at length about the issues I see in neumorphism and why this trend should be avoided. I know any attempt to guide my most impressionable colleagues away from it, will end up being failing because this fad is going t…

前端容易忽略的 debugger 调试技巧

大家好&#xff0c;我是若川。我们日常开发碰到的很多问题&#xff0c;通过 debugger 都能快速定位问题&#xff0c;所以推荐这篇大家容易忽略的调试技巧。会定位问题&#xff0c;可以节省很多时间。也就是我经常说的工欲善其事&#xff0c;必先利其器。也是为什么我经常强调调…

Spring高级程序设计这本书怎么样

关于Spring高级程序设计 评论读后感&#xff1a;这本书需要有一定的spring基础的人看读后感&#xff1a;对于了解Spring 很有用&#xff0c;并且是一本不错的参考书读后感&#xff1a;这本书早就想买了&#xff0c;就是太贵了&#xff5e;&#xff5e;&#xff5e; 啦啦啦&…

java调用arcgis rest服务器_c#调用arcgis地图rest服务示例详解(arcgis地图输出)

using System;using System.Collections.Generic;using System.Linq;using System.Text;using ESRI.ArcGIS.Client;using ESRI.ArcGIS.Client.Geometry;using ESRI.ArcGIS.Client.Tasks;using System.Net;using System.IO;namespace ArcGISDemo{//自定义的Featureclass Feature…

Semantic Element

Semantic Element 1.什么是语义化 根据内容的结构&#xff0c;选择合适的标签&#xff08;代码语义化&#xff09;便于开发者阅读。写出更优雅的代码的同时让浏览器的爬虫和机器很好地解析。 语义&#xff08;semantic&#xff09;  语义化标记&#xff0c;是指每种标记表示一…

玉伯:开源有带给我什么

在2021年527蚂蚁技术日上&#xff0c;蚂蚁内源社区举办了内源专场&#xff0c;在专场上玉伯给大家分享了《开源有带给我什么》&#xff0c;以下为演讲的图文整理。我的开源之路我从2009年到2018年&#xff0c;接近十年时间&#xff0c;一直在做开源的一些事情&#xff0c;在这个…