Springboot集成BeanValidation擴展一:錯誤提示信息加公共模板

Bean Validator擴展

1、需求

? 在使用validator時,有個需求就是公用錯誤提示信息,什么意思?

舉個例子:

? @NotEmpty非空判斷,在資源文件中我不想每個非空判斷都寫”不能為空“,只需要寫”###“,然后提示信息自動會變成”###不能為空“

代碼:

public class User{//資源文件中user.name.empty=用戶名@NotEmpty(key={user.name.empty})private String name;'''
}

//加入name為空,則最終的錯誤提示為“用戶名不能為空”(會自動加上“不能為空”信息)

2、實現方式

有兩種實現方式

方式一:手動調用驗證方法
注解
@Target({FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@ReportAsSingleViolation
@Constraint(validatedBy = {})
@NotNull
@Size(min = 1)
public @interface NotEmpty {String message() default "{key}{com.chyjr.hyb.validator.constraints.empty.message}";
?Class<?>[] groups() default { };
?Class<? extends Payload>[] payload() default { };String key() default "";
}
驗證器
//驗證器
public class MyValidator {private static final Logger log = LoggerFactory.getLogger(HybValidator.class);private static Validator validator = null;private static MessageInterpolator msgInterpolator = null;static {if (validator == null) {LocalValidatorFactoryBean factory = (LocalValidatorFactoryBean) ApplicationContextUtil.getBean("validator");validator = factory.getValidator();msgInterpolator = factory.getMessageInterpolator();}}
?public static HybValidatorResult validate(Object object, Class<?>... groups) {HybValidatorResult result = new HybValidatorResult();Set<ConstraintViolation<Object>> violations = validator.validate(object, groups);Map<String, String> map = new HashMap<>();if (CollectionUtils.isEmpty(violations)) {result.setErrors(false);} else {result.setErrors(true);for (ConstraintViolation<Object> violation : violations) {String path = violation.getPropertyPath().toString();String message = violation.getMessage();if (StringUtils.isBlank(path) || StringUtils.isBlank(message) || map.containsKey(path))continue;message = resolveMessage(message);map.put(path, message);}result.setItems(map);}return result;}private static final Pattern elpattern = Pattern.compile("\\{[^{}]+\\}");private static String resolveMessage(String message) {Matcher matcher = elpattern.matcher(message);try {while (matcher.find()) {String el = matcher.group();//用資源文件信息替換message = {key}{my.empty.message}//注解這里的key會替換成注解NotEmpty定義的key,即//message = {user.name.empty}{my.empty.message}String val = msgInterpolator.interpolate(el, null);if (StringUtils.isBlank(val))continue;message = message.replace(el, val);}} catch (Exception e) {log.error("驗證引擎進行數據校驗時出現異常, message:{}", message, e);}return message;}
}
使用
//調用驗證方法獲得驗證結果
 HybValidatorResult bvr = HybValidator.validate(emp, CreateValidator.class);//表示有錯誤if (bvr.isErrors()) {} 
//資源文件內容
//my.empty.message=不能為空
//user.name.empty=用戶名
方式二:用spring自帶的@Validated,無需調用驗證方法

這里有個問題:@Validated注解不認注解@NotEmpty中的key,如何解決呢?

最終的實現方案:自定義驗證器

代碼:

注解
@Documented
@Target({FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@ReportAsSingleViolation
//指定驗證器
@Constraint(validatedBy = NotEmptyValidator.class)
public @interface NotEmpty {String message() default "{my.empty.message}";
?Class<?>[] groups() default { };
?Class<? extends Payload>[] payload() default { };String key() default "";
}
驗證器:自定義
public class NotEmptyValidator extends AbstractValidator<NotEmpty,Object>{
?@Overridepublic void initialize(NotEmpty notEmpty) {
?}
?@Overridepublic boolean doIsValid(Object value, ConstraintValidatorContext cc) {return value != null;}
}
?
/**
* 這里采用模板的設計模式
* @param constraintAnnotation
*/
public abstract class AbstractValidator<A extends Annotation,T> implements ConstraintValidator<A,T>{
?/*** 初始化由具體類實現* @param constraintAnnotation*/@Overridepublic abstract void initialize(A constraintAnnotation);
?/*** 初始化具體由實現類實現* @param value* @param context* @return*/@Overridepublic boolean isValid(T value, ConstraintValidatorContext context){//獲取驗證結果,采用模板方法boolean result = doIsValid(value,context);//當驗證錯誤時修改默認信息if(!result){//改變默認提示信息if(ConstraintValidatorContextImpl.class.isAssignableFrom(context.getClass())){ConstraintValidatorContextImpl constraintValidatorContext = (ConstraintValidatorContextImpl)context;//獲取默認提示信息String defaultConstraintMessageTemplate = context.getDefaultConstraintMessageTemplate();Object key = constraintValidatorContext.getConstraintDescriptor().getAttributes().get("key");//禁用默認提示信息
                context.disableDefaultConstraintViolation();//設置提示語(在message前面加上key)context.buildConstraintViolationWithTemplate(key +                                          defaultConstraintMessageTemplate).addConstraintViolation();}}
?return result;}/*** 真正驗證方法* @param value* @param context* @return*/public abstract boolean doIsValid(T value, ConstraintValidatorContext context);
}
使用:

調用的時候只要在JavaBean前加上@Validated注解即可

總結:上述就是在工作中遇到的問題,并擴展了Validator

轉載于:https://www.cnblogs.com/liruiloveparents/p/9378264.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/388988.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/388988.shtml
英文地址,請注明出處:http://en.pswp.cn/news/388988.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

福大軟工 · 第十次作業 - 項目測評(團隊)

寫在前面 本次作業測試報告鏈接林燊大哥第一部分 調研&#xff0c;評測 一、評測 軟件的bug&#xff0c;功能評測&#xff0c;黑箱測試 1.下載并使用&#xff0c;描述最簡單直觀的個人第一次上手體驗 IOS端 UI界面簡單明了&#xff0c;是我喜歡的極簡風格。課程模塊界面簡潔優雅…

銷貨清單數據_2020年8月數據科學閱讀清單

銷貨清單數據Note: I am not affiliated with any of the writers in this article. These are simply books and essays that I’m excited to share with you. There are no referrals or a cent going in my pocket from the authors or publishers mentioned. Reading is a…

c++運行不出結果_fastjson 不出網利用總結

點擊藍字 關注我們 聲明 本文作者:flashine 本文字數:2382 閱讀時長:20分鐘 附件/鏈接:點擊查看原文下載 聲明:請勿用作違法用途,否則后果自負 本文屬于WgpSec原創獎勵計劃,未經許可禁止轉載 前言 之前做項目在內網測到了一個fastjson反序列化漏洞,使用dnslo…

FocusBI:租房分析可視化(PowerBI網址體驗)

微信公眾號&#xff1a;FocusBI關注可了解更多的商業智能、數據倉庫、數據庫開發、爬蟲知識及滬深股市數據推送。問題或建議&#xff0c;請關注公眾號發送消息留言;如果你覺得FocusBI對你有幫助&#xff0c;歡迎轉發朋友圈或在文章末尾點贊[1] 《商業智能教程》pdf下載地址 …

米其林餐廳 鹽之花_在世界范圍內探索《米其林指南》

米其林餐廳 鹽之花Among the culinary world, there are few greater accolades for a restaurant than being awarded a Michelin star (or three!), or being listed as one of the best in the world by a reputable guide. Foodies and fine dine lovers like myself, see …

require_once的用法

require_once 語句和 require 語句完全相同&#xff0c;唯一區別是 PHP 會檢查該文件是否已經被包含過&#xff0c;如果是則不會再次包含。 參見 include_once 的文檔來理解 _once 的含義&#xff0c;并理解與沒有 _once 時候有什么不同。 有一個文件a.php,里面有一個變量$var1…

差值平方和匹配_純前端實現圖片的模板匹配

基礎介紹模板匹配是指在當前圖像A里尋找與圖像B最相似的部分&#xff0c;本文中將圖像A稱為模板圖像&#xff0c;將圖像B稱為搜索匹配圖像。引言&#xff1a;一般在Opencv里實現此種功能非常方便&#xff1a;直接調用result cv2.matchTemplate(templ, search, method)templ 為…

藍牙耳機音量大解決辦法_長時間使用藍牙耳機的危害這么大?我們到底該選什么藍牙耳機呢?...

藍牙耳機避免了耳機線纏結&#xff0c;使人活動更自由&#xff0c;給人們帶來了更加方便、舒適的聽覺體驗。但近日&#xff0c;英國《每日郵報》刊文表示&#xff0c;藍牙耳機可能會危害人體健康。美國加州大學伯克利分校公共健康教授喬爾莫斯科維茨博士表示&#xff0c;已有研…

JVM基礎系列第10講:垃圾回收的幾種類型

我們經常會聽到許多垃圾回收的術語&#xff0c;例如&#xff1a;Minor GC、Major GC、Young GC、Old GC、Full GC、Stop-The-World 等。但這些 GC 術語到底指的是什么&#xff0c;它們之間的區別到底是什么&#xff1f;今天我們就來詳細說說。 Minor GC 從年輕代空間回收內存被…

模擬退火學習

模擬退火學習 作業部落網上講的不錯的(他好像還有一些其他的東西、、、) 引入 對于一些題目&#xff0c;無法直接算出答案或者想不到正解&#xff0c;想到隨機找答案&#xff0c;那么模擬退火就是一種有系統方法的隨機算法 沒用的不需要了解的來源 百度百科...... 模擬退火算法…

spotify 數據分析_我的Spotify流歷史分析

spotify 數據分析Spotisis /spo-ti-sis/ noun The analysis of one’s Spotify streaming history using Python.Spotisis / spo-ti-sis / 名詞使用Python分析一個人的Spotify流歷史。 I was reading through a lot of data science related guides and project ideas when I …

idea 搜索不到gsonformat_Idea中GsonFormat插件安裝

這個教不的期是范添事大部會基近說小間進圍磚本的程主要是學習IntelliJ IDEA 如何通過GsonFormat插件將JSONObject格式的String 支器事的后功發久這含層請間業在屏有隨些氣和域&#xff0c;實按控幻近持的前時來能過后些的處求也務瀏蔽等機站風滾或默現鈕制燈近持的前時來能過后…

intellig idea中jsp或html數據沒有自動保存和更換字體

主題一:保存數據jsp intellig idea是自動保存數據的,看到沒有保存 解決方案&#xff1a; 成功解決 主題二:更換字體: 或者快捷鍵CtelAlts 成功解決 轉載于:https://www.cnblogs.com/weibanggang/p/9398498.html

java 環境變量

1.確保安裝jrd jdk 2.環境變量配置 (1)新建->變量名"JAVA_HOME"&#xff0c;變量值"C:\Java\jdk1.8.0_05"&#xff08;JDK的安裝路徑&#xff09; (2)編輯->變量名"Path"&#xff0c;在原變量值的最后面加上“;%JAVA_HOME%\bin;%JAVA_HOME…

陸濤喜歡夏琳嗎_夏琳·香布利斯(Charlene Chambliss):從心理學到自然語言處理和應用研究

陸濤喜歡夏琳嗎技術系列中的女性 (WOMEN IN TECHNOLOGY SERIES) Interest in data science has been exponentially increasing over the past decade, and more and more people are working towards making a career switch into the field. In 2020, articles and YouTube v…

【angularJS】簡介

簡介 AngularJS 是一個 JavaScript 框架。它可通過 <script> 標簽添加到 HTML 頁面。 AngularJS 通過 指令 擴展了 HTML&#xff0c;且通過 表達式 綁定數據到 HTML。 AngularJS 是一個 JavaScript 框架。它是一個以 JavaScript 編寫的庫。 AngularJS 是以一個 JavaScrip…

爬取淘寶商品信息selenium+pyquery+mongodb

爬取淘寶商品信息,通過selenium獲得渲染后的源碼,pyquery解析,mongodb存儲 from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import Timeout…

紋個雞兒天才小熊貓_給熊貓用戶的5個提示

紋個雞兒天才小熊貓A popular Python library used by those working with data is pandas, an easy and flexible data manipulation and analysis library. There are a myriad of awesome methods and functions in pandas, some of which are probably less well-known tha…

本人服務器遭受黑客長期攻擊,特把這幾天做的一些有用的安全方面總結出來,以方便以后查閱

消息隊列iis360northrarsql2000 netscren本人服務器遭受黑客長期攻擊&#xff0c;特把這幾天做的一些有用的安全方面總結出來&#xff0c;以方便以后查閱&#xff0c;希望這次徹底解覺黑客的攻擊&#xff0c;特次謝謝“冷雨夜”的一些提示。 windows 2003服務器安全設置方法 0…

用戶與用戶組管理

linux最優秀的地方之一&#xff0c;就在于他的多用用戶、多任務環境。 用戶及用戶組的概念 1、文件所有者 由于linux是一個多用戶、多任務的系統。因此可能常常會有很多人同時使用這臺主機來進行工作的情況發生&#xff0c;為了考慮每個人的隱私權以及每個人的喜好的工作環境&a…