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.pswp.cn/news/275786.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/275786.shtml
英文地址,請注明出處:http://en.pswp.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;在這個…