废话不多说,直接进入正题:如何使用JSR303的validate,进行数据校验,失败后直接抛出异常加入流转信息中,并在form页面提示出来。

首先我们为了启用验证,需要向

项目中添加Bean验证的实现。本列选择Hibernate Validator框架来提供验证功能。可以像下面的示例那样将该项目作为一个Maven依赖添加到当前项目中。此外,Hibernate Validator会将Bean Validation API作为一个船只依赖添加到项目中。

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.1.Final</version>
</dependency>

  

在表单页面引入如下标签:

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

然后使用该标签下的form:form进行数据验证的绑定

<form:form id="inputForm" modelAttribute="article" action="${ctx}/cms/article/save" method="post" class="form-horizontal">

		<div class="control-group">
<label class="control-label">摘要:</label>
<div class="controls">
<form:textarea path="description" htmlEscape="false" rows="4" maxlength="200" class="input-xxlarge"/>
</div>
</div>
<div class="form-actions">
<shiro:hasPermission name="cms:article:edit"><input id="btnSubmit" class="btn btn-primary" type="submit" value="保 存"/> </shiro:hasPermission>
<input id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)"/>
</div>
</form:form>

  如上我只是简单举了一个字段为description(简介/描述)的数据验证例子 其实这里的maxlength="200",我们完全可以忽略它,因为前段的验证始终是不安全的,而且我们在后台进行的验证因为整合了jsr303变的异常的简洁,我们只需要在需要验证的

表单实体的get方法上加上一行注解:

@Length(min=0, max=5)
public String getDescription() {
return description;
}

  //这行注解的意思是最小长度是0,最大长度是5

然后在控制层写上验证失败加入流转信息并返回form页的代码:

	@RequestMapping(value = "save")
public String save(Article article, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, article)){
return form(article, model);
}
articleService.save(article);
addMessage(redirectAttributes, "保存文章'" + StringUtils.abbr(article.getTitle(),50) + "'成功");
String categoryId = article.getCategory()!=null?article.getCategory().getId():null;
return "redirect:" + adminPath + "/cms/article/?repage&category.id="+(categoryId!=null?categoryId:"");
}

  我们进入beanValidator(model,article)这个方法一探究竟:

/**
* 服务端参数有效性验证
* @param object 验证的实体对象
* @param groups 验证组
* @return 验证成功:返回true;严重失败:将错误信息添加到 message 中
*/
protected boolean beanValidator(Model model, Object object, Class<?>... groups) {
try{
BeanValidators.validateWithException(validator, object, groups);
}catch(ConstraintViolationException ex){
List<String> list = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
list.add(0, "数据验证失败:");
addMessage(model, list.toArray(new String[]{}));
return false;
}
return true;
}

  

/**
* JSR303 Validator(Hibernate Validator)工具类.
*
* ConstraintViolation中包含propertyPath, message 和invalidValue等信息.
* 提供了各种convert方法,适合不同的i18n需求:
* 1. List<String>, String内容为message
* 2. List<String>, String内容为propertyPath + separator + message
* 3. Map<propertyPath, message>
*
* 详情见wiki: https://github.com/springside/springside4/wiki/HibernateValidator
* @author calvin
* @version 2013-01-15
*/
public class BeanValidators { /**
* 调用JSR303的validate方法, 验证失败时抛出ConstraintViolationException.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void validateWithException(Validator validator, Object object, Class<?>... groups)
throws ConstraintViolationException {
Set constraintViolations = validator.validate(object, groups);
if (!constraintViolations.isEmpty()) {
throw new ConstraintViolationException(constraintViolations);
}
} /**
* 辅助方法, 转换ConstraintViolationException中的Set<ConstraintViolations>为List<propertyPath +separator+ message>.
*/
public static List<String> extractPropertyAndMessageAsList(ConstraintViolationException e, String separator) {
return extractPropertyAndMessageAsList(e.getConstraintViolations(), separator);
} }

  

  

/**
* 添加Model消息
* @param message
*/
protected void addMessage(Model model, String... messages) {
StringBuilder sb = new StringBuilder();
for (String message : messages){
sb.append(message).append(messages.length>1?"<br/>":"");
}
model.addAttribute("message", sb.toString());
}

  

最后我们要做的就是在form页面把model中的错误信息展示出来就行了:

<script type="text/javascript">top.$.jBox.closeTip();</script>
<c:if test="${not empty content}">
<c:if test="${not empty type}"><c:set var="ctype" value="${type}"/></c:if><c:if test="${empty type}"><c:set var="ctype" value="${fn:indexOf(content,'失败') eq -1?'success':'error'}"/></c:if>
<div id="messageBox" class="alert alert-${ctype} hide"><button data-dismiss="alert" class="close">×</button>${content}</div>
<script type="text/javascript">if(!top.$.jBox.tip.mess){top.$.jBox.tip.mess=1;top.$.jBox.tip("${content}","${ctype}",{persistent:true,opacity:0});$("#messageBox").show();}</script>
</c:if>

  例子展示如下:

  

这种验证方法是每次都会向服务器发送一次请求,如果一些简单的验证不需要向后台区请求,我们可以使用自定义的validate在前端完成简单的数据验证:

$("#inputForm").validate({
submitHandler: function(form){
if ($("#categoryId").val()==""){
$("#categoryName").focus();
top.$.jBox.tip('请选择归属栏目','warning');
}else if (CKEDITOR.instances.content.getData()=="" && $("#link").val().trim()==""){
top.$.jBox.tip('请填写正文','warning');
}else{
loading('正在提交,请稍等...');
form.submit();
}
},
errorContainer: "#messageBox",
errorPlacement: function(error, element) {
$("#messageBox").text("输入有误,请先更正。");
if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){
error.appendTo(element.parent().parent());
} else {
error.insertAfter(element);
}
}
});

  

浅析调用JSR303的validate方法, 验证失败时抛出ConstraintViolationException的更多相关文章

  1. List 调用 remove 方法时抛出 java.lang.UnsupportedOperationException 异常原因

    原因 使用 Arrays.asList(arr) 转换的 List 并不能进行 add 和 remove 操作.       Arrays.asList(arr) 返回的类型是 Aarrays$Arr ...

  2. java异常处理:建立exception包,建立Bank类,类中有变量double balance表示存款,Bank类的构造方法能增加存款,Bank类中有取款的发方法withDrawal(double dAmount),当取款的数额大于存款时,抛出InsufficientFundsException,取款数额为负数,抛出NagativeFundsException,如new Bank(100),

    建立exception包,建立Bank类,类中有变量double  balance表示存款,Bank类的构造方法能增加存款,Bank类中有取款的发方法withDrawal(double dAmount ...

  3. 为 jquery validate 添加验证失败回调

    转载自:https://blog.csdn.net/huang100qi/article/details/52619227 1. jquery Validation Plugin - v1.15.1 ...

  4. Struts(二十四):短路验证&重写实现转换验证失败时短路&非字段验证

    短路验证: 若对一个字段使用多个验证器,默认情况下会执行所有的验证.若希望前面的验证器没有通过,后面的验证器就不再执行,可以使用短路验证. 1.如下拦截器,如果输入字符串,提交表单后,默认是会出现三个 ...

  5. 调用远程主机上的 RMI 服务时抛出 java.rmi.ConnectException: Connection refused to host: 127.0.0.1 异常原因及解决方案

    最近使用 jmx 遇到一个问题,client/server 同在一台机器上,jmx client能够成功连接 server,如果把 server 移植到另一台机器上192.168.134.128,抛出 ...

  6. 在自定义的js验证规则中调用magento的VarienForm方法验证表单

    js部分<script type="text/javascript"> //<![CDATA[ var loginForm = new VarienForm('l ...

  7. mixare的measureText方法在频繁调用时抛出“referencetable overflow max 1024”的解决方式

    这几天在搞基于位置的AR应用,採用了github上两款开源项目: mixare android-argument-reality-framework 这两个项目实现机制大致同样.我选取的是androi ...

  8. Redis出现多线程调用时抛出 [B cannot be cast to java.lang.Long] 异常

    原因分析: 多个线程同时调用了同一个jedis对象,导致内存数据被多个线程竞争,产生数据混乱 (或者大家都用通一个redis获取同一个实例,登录同一个账号使用缓存时报错) 解决方案:每个线程都new出 ...

  9. CAD调试时抛出“正试图在 os 加载程序锁内执行托管代码。不要尝试在 DllMain 或映像初始化函数内运行托管代码”异常的解决方法

    这些天重装了电脑Win10系统,安装了CAD2012和VS2012,准备进行软件开发.在调试程序的时候,CAD没有进入界面就抛出 “正试图在 os 加载程序锁内执行托管代码.不要尝试在 DllMain ...

随机推荐

  1. 13、ABPZero系列教程之拼多多卖家工具 微信公众号开发前的准备

    因为是开发阶段,我需要在本地调试,而微信开发需要配置域名,这样natapp.cn就有了用武之地,应该说natapp就是为此而生的. natapp.cn是什么 这是一个内网映射的网站,支持微信公众号.小 ...

  2. Django_ajax

    AJAX(Asynchronous Javascript And XML)翻译成中文就是"异步Javascript和XML".即使用Javascript语言与服务器进行异步交互,传 ...

  3. SpringBoot(二)Web整合开发

    Spring Boot (二):Web 综合开发 本篇文章接着上篇内容继续为大家介绍spring boot的其它特性(有些未必是spring boot体系桟的功能,但是是spring特别推荐的一些开源 ...

  4. 洛谷 P1219 八皇后【经典DFS,温习搜索】

    P1219 八皇后 题目描述 检查一个如下的6 x 6的跳棋棋盘,有六个棋子被放置在棋盘上,使得每行.每列有且只有一个,每条对角线(包括两条主对角线的所有平行线)上至多有一个棋子. 上面的布局可以用序 ...

  5. Spring框架学习笔记(9)——Spring对JDBC的支持

    一.使用JdbcTemplate和JdbcDaoSupport 1.配置并连接数据库 ①创建项目并添加jar包,要比之前Spring项目多添加两个jar包c3p0-0.9.1.2.jar和mysql- ...

  6. 解决jsp中编辑和删除时候弹出框闪退的问题。

    ---恢复内容开始--- /* 火箭设备特殊记载</li> <!-- yw4 --> */ function getYw4DL(){ var controlparm={&quo ...

  7. UEP-时间

    时间戳转化为Date(or String) SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ...

  8. C#面试题整理(1)

    最近在看CLR VIA C#,发现了一些案例很适合来做面试题.特此整理: 1,System.Object里的GetType方法是否为虚函数?说出理由. 答案:不是,因为C#是一种类型安全的语言,如果覆 ...

  9. kafka和strom集群的环境安装

    前言 storm和kafka集群安装是没有必然联系的,我将这两个写在一起,是因为他们都是由zookeeper进行管理的,也都依赖于JDK的环境,为了不重复再写一遍配置,所以我将这两个写在一起.若只需一 ...

  10. Weblogic jsp页面编译出错,Weblogic jsp编译异常

    Weblogic jsp页面编译出错,Weblogic jsp编译异常 ======================== 蕃薯耀 2018年1月29日 http://www.cnblogs.com/f ...