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.mzph.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…