本文主要是介绍扩展SSM的验证注释,使其能使用资源文件及动态参数返回错误信息,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1/ POM.xml增加两个依赖
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api --><dependency><groupId>javax.validation</groupId><artifactId>validation-api</artifactId><version>2.0.1.Final</version></dependency><!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator --><dependency><groupId>org.hibernate.validator</groupId><artifactId>hibernate-validator</artifactId><version>6.0.16.Final</version></dependency>
2/跟踪Spring MVC的代码发现, 当验证失败后,通过MethodArgumentNotValidException来抛出异常, 那么只要我们拦截这个异常, 然后将里面的错误信息翻译一下即可, 我做的一个拦截器, message里面支持下面几种写法:
a/兼容原先的直接写错误信息
b/支持用{}符号调用资源文件来显示错误信息
c/在b的基础上,带入参数, 参数可以为任何常量, 又或者以#{target和#{self开头的属性. target指的是当前验证的类的实例, self指的是当前的注释
比如:
如果参数类的str="abc123526262356233562",则
返回的错误效果:
拦截器也简单, 就是在原先全局异常处理里面再增加分析MethodArgumentNotValidException:
/***** 全局异常处理:全部以Json格式返回至前端, 并且在日志中打印调用堆栈* * @param e* @return*/@ExceptionHandler(value = Exception.class)public @ResponseBody Object handleException(Exception e) {if (!(e instanceof ModifyDataException || e instanceof MethodArgumentNotValidException)) {e.printStackTrace();}if (e instanceof MethodArgumentNotValidException) {MethodArgumentNotValidException lvExp = (MethodArgumentNotValidException) e;Object lvTarget = lvExp.getBindingResult().getTarget();// Method lvMethod=lvExp.getParameter().getMethod();StringBuilder sbMsg = new StringBuilder();StringBuilder sbRefs = new StringBuilder();for (ObjectError item : lvExp.getBindingResult().getAllErrors()) {FieldError lvError = (FieldError) item;String lvsDefaultMsg = lvError.getDefaultMessage();if (lvsDefaultMsg.startsWith("{")) {if (!lvsDefaultMsg.endsWith("}")) {throw new RuntimeException("miss '}' with error Message pattern:" + lvsDefaultMsg);}String lvsTmp = StringUtils.left(lvsDefaultMsg, lvsDefaultMsg.length() - 1);String[] lvItems = StringUtils.right(lvsTmp, lvsTmp.length() - 1).split(",");if (lvItems.length == 0 || lvItems.length == 1 && lvItems[0].isEmpty()) {throw new RuntimeException("error Message pattern is blank");}String lvsKey = lvItems[0];List<Object> lvParams = new ArrayList<Object>();for (int i = 1; i < lvItems.length; i++) {String lvsParam = lvItems[i];if (lvsParam.startsWith("#{") && lvsParam.endsWith("}")) { // #{target.email}lvsTmp = StringUtils.left(lvsParam, lvsParam.length() - 1);lvsTmp = StringUtils.right(lvsTmp, lvsTmp.length() - 2);String[] lvWd = lvsTmp.split("\\.");String lvsInst = lvWd[0];String lvsField = lvWd[1];Object lvInst = null;if (lvsInst.equals("target")) {lvInst = lvTarget;if (lvInst == null) {throw new RuntimeException("Invalid error message param:'" + lvsParam + "'");}Object lvParamVal = BeanUtil.getFieldValue(lvInst, lvsField, Object.class);lvParams.add(lvParamVal);} else if (lvsInst.equals("self")) {try {Field lvField = lvTarget.getClass().getDeclaredField(lvError.getField());String lvsAnnName = lvError.getCodes()[2];Annotation lvAnn = null;for (Annotation ann : lvField.getAnnotations()) {String lvsClName = ann.annotationType().getSimpleName();if (lvsClName.equals(lvsAnnName)) {lvAnn = ann;break;}}if (lvAnn == null) {throw new RuntimeException("Invalid error message param:'" + lvsParam + "'");}Map<String, Object> lvAttrs = AnnotationUtils.getAnnotationAttributes(lvAnn);Object lvParamVal = lvAttrs.get(lvsField);lvParams.add(lvParamVal);} catch (NoSuchFieldException | SecurityException e1) {throw new RuntimeException(e1);}}} else {lvParams.add(lvsParam);}}sbMsg.append("\n" + MessageSourceHelper.getMessage(lvsKey,lvParams.toArray(new Object[lvParams.size()]), "<" + lvsKey + ">", Locale.CHINA));} else {sbMsg.append("\n" + lvsDefaultMsg);}String lvFieldName = lvError.getField();@SuppressWarnings("rawtypes")Class lvCz = lvExp.getBindingResult().getTarget().getClass();Field lvF;try {lvF = lvCz.getField(lvFieldName);Column lvCol = lvF.getAnnotation(Column.class);if (lvCol != null) {lvFieldName = lvCol.name();}sbRefs.append("," + lvFieldName);} catch (NoSuchFieldException | SecurityException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}if (sbRefs.length() > 0) {sbRefs.delete(0, 1);}if (sbMsg.length() > 0) {sbMsg.delete(0, 1);}e = new ModifyDataException(sbMsg.toString(), sbRefs.toString().split(","));}return new JSONData(-1, e);}
这篇关于扩展SSM的验证注释,使其能使用资源文件及动态参数返回错误信息的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!