springmvc的@Validated/@Valid注解使用和BindingResult bindingResult
关于@Valid和Validated的比较
@Valid是使用hibernate validation的时候使用
@Validated 是只用spring Validator 校验机制使用
一:@Validated 是只用spring Validator 校验机制使用
@Validated和BindingResult bindingResult是配对出现,并且形参顺序是固定的(一前一后)。
例如:
@ModelAttribute("student")是创建的一个new student()类, 用来验证前台提交的数据student是否正确(@Validated Student student)
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("student") @Validated Student student,
BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) {
return "student";
}
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId()); return "student_result";
}
前台提交的数据:
前台commandName="student"绑定了student类
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page isELIgnored="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Spring MVC表单处理</title>
</head>
<style>
.error {
color: #ff0000;
} .errorStyle {
color: #000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
<body> <h2>学生信息</h2>
<form:form method="POST" action="/hello/addStudent" commandName="student">
<form:errors path="*" cssClass="errorStyle" element="div" />
<table>
<tr>
<td><form:label path="name">姓名:</form:label></td>
<td><form:input path="name" /></td>
<td><form:errors path="name" cssClass="error" /></td>
</tr>
<tr>
<td><form:label path="age">年龄:</form:label></td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td><form:label path="id">编号:</form:label></td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="提交" /></td>
</tr>
</table>
</form:form>
</body>
</html>
全代码:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated; @Controller
public class StudentController { @Autowired
@Qualifier("studentValidator")
private Validator validator; @InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
} //前端from数据引用:commandName
@ModelAttribute("student")
public Student createStudentModel() {
return new Student();
} @RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
} @RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("student") @Validated Student student,
BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) {
return "student";
}
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId()); return "student_result";
} }
二:@Valid是使用hibernate validation的时候使用
@Valid
看看下面的依赖就知道,java的JSR303声明了这类接口,然后hibernate-validator对其进行了实现。
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency> <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.1.Final</version>
</dependency>
JSR303定义的校验类型
空检查 @Null 验证对象是否为null @NotNull 验证对象是否不为null, 无法查检长度为0的字符串 @NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格. @NotEmpty 检查约束元素是否为NULL或者是EMPTY. Booelan检查 @AssertTrue 验证 Boolean 对象是否为 true @AssertFalse 验证 Boolean 对象是否为 false 长度检查 @Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内 @Length(min=, max=) Validates that the annotated string is between min and max included. 日期检查 @Past 验证 Date 和 Calendar 对象是否在当前时间之前 @Future 验证 Date 和 Calendar 对象是否在当前时间之后 @Pattern 验证 String 对象是否符合正则表达式的规则 数值检查,建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单值为“”时无法转换为int,但可以转换为Stirng为"",Integer为null @Min 验证 Number 和 String 对象是否大等于指定的值 @Max 验证 Number 和 String 对象是否小等于指定的值 @DecimalMax 被标注的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度 @DecimalMin 被标注的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度 @Digits 验证 Number 和 String 的构成是否合法 @Digits(integer=,fraction=) 验证字符串是否是符合指定格式的数字,interger指定整数精度,fraction指定小数精度。 @Range(min=, max=) Checks whether the annotated value lies between (inclusive) the specified minimum and maximum. @Range(min=10000,max=50000,message="range.bean.wage")
private BigDecimal wage; @Valid 递归的对关联对象进行校验, 如果关联对象是个集合或者数组,那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.(是否进行递归验证) @CreditCardNumber信用卡验证 @Email 验证是否是邮件地址,如果为null,不进行验证,算通过验证。 @ScriptAssert(lang= ,script=, alias=) @URL(protocol=,host=, port=,regexp=, flags=)
例如:
public class user{
@NotNull
@Length(min = 1,max = 5)
private String name;
@Size(min=1,max=5)
private int pasWord
}
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
BlackDisck createUser(@ModelAttribute @Valid User user, BindingResult result) { if (result.hasErrors()) {
List<ObjectError> errorList = result.getAllErrors();
for (ObjectError error : errorList) { System.out.println(error.getCode()+" msg="+ error.getDefaultMessage());
}
return null;
}
.......... }
springmvc的@Validated/@Valid注解使用和BindingResult bindingResult的更多相关文章
- SpringMVC的@Validated校验注解使用方法
validate会对参数进行校验,校验标准为validate后的类中的标准.本例中对User进行校验,User类中设置了校验标准. 在后台开发过程中,对参数的校验成为开发环境不可缺少的一个环节.比如参 ...
- SpringMvc中的校验框架@valid和@validation的概念及相关使用 和BindingResult bindingResult
1.比较 @Valid是使用hibernate validation的时候使用 @Validated 是只用spring Validator 校验机制使用\ 2.实现 其中,@valid,java的 ...
- SpringMVC使用@Valid注解进行数据验证
SpringMVC使用@Valid注解进行数据验证 from:https://blog.csdn.net/zknxx/article/details/52426771 我们在做Form表单提交的时 ...
- SpringMvc数据校验@Valid等注解的使用与工具类抽取
最近在重构老项目的代码,发现校验入参占用了很多代码,之前我对这一块的认识局限于使用StringUtils等工具来多个if块进行判断,代码是没什么问题,但是总写这些令人生烦,毕竟写代码也要讲究优雅的嘛, ...
- @Valid注解的使用springmvc pojo校验
@Valid注解用于校验,所属包为:javax.validation.Valid. ① 首先需要在实体类的相应字段上添加用于充当校验条件的注解,如:@Min,如下代码(age属于User类中的属性): ...
- SpringMVC中使用@Valid和BindingResult进行参数验证
我们知道,后端Controller层一般是第一层被调用,它用来接收参数以及转发,那么参数的校验也就在这一层,例如非空和格式校验等等. 手动验证 public String validPhone(Str ...
- springmvc学习笔记(常用注解)
springmvc学习笔记(常用注解) 1. @Controller @Controller注解用于表示一个类的实例是页面控制器(后面都将称为控制器). 使用@Controller注解定义的控制器有如 ...
- Spring框架的@Valid注解
上一篇文章介绍了springmvc的get请求参数可以是一个自定的对象.那么如何限制这个对象里的参数是否必传呢? 方法一:在代码逻辑里取出对象里的这个值,手动进行判断 方法二:使用@Valid注解,在 ...
- @Valid注解的使用(转)
原文地址:http://blog.csdn.net/xzmeasy/article/details/76098188 @Valid注解用于校验,所属包为:javax.validation.Valid. ...
随机推荐
- cmd 运行jar文件
将java工程打成jar包,但第三方jar包并没有包含在包中,当在命令行中运行jar包时,出现类找不到的异常, 在网上看到解决办法是将第三方jar包放到JDK的扩展类文件夹中(%JAVA_HOME%/ ...
- GC的性能指标和内存容量配置原则
一.GC性能指标吞吐量:应用花在非GC上的时间百分比GC负荷:与吞吐量相反,指应用花在GC上的时间百分比暂停时间:应用花在GC stop-the-world的时间GC频率反应速度:从一个对象变成垃圾到 ...
- UVA10905: Children's Game(排序)
题目:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=68990#problem/A 题目需求:,给n个数字,将它们重新排序得到一个最大的数 ...
- 20165324 Java实验四 Android程序设计
20165324 Java实验四 Android程序设计 一.实验报告封面 课程:Java程序设计 班级:1653班 姓名:何春江 学号:20165324 指导教师:娄嘉鹏 实验日期:2018年5月1 ...
- mysql lock
http://blog.chinaunix.net/uid-21505614-id-289450.html http://bbs.csdn.net/topics/340127237 http://ww ...
- BigInteger和Complex:NET 4新增数据类型
BigInteger和Complex是.NET 4中新增的两种值类型,他们位于System.Numeric命名空间下,需要单独添加引用. BigInteger BigInteger类型是不可变类型,代 ...
- Kattis - bank 【简单DP】
Kattis - bank [简单DP] Description Oliver is a manager of a bank near KTH and wants to close soon. The ...
- JS正则表达式从入门到入土(8)—— REGEXP对象属性
对象属性 常用对象属性主要有以下几种: 1.global: 是否全文搜索,默认false 2.ignore case:是否大小写敏感,默认是false 3.multiline:多行搜索,默认值是fal ...
- Web安全学习笔记之Nmap脚本使用指南
nmap是一个网络连接端扫描软件,用来扫描网上电脑开放的网络连接端.确定哪些服务运行在哪些连接端,并且推断计算机运行哪个操作系统.它是网络管理员必用的软件之一,以及用以评估网络系统安全. —— 来自百 ...
- U盘中了磁碟机病毒怎么办
问题: U盘在中毒了的电脑上使用后,里面的文件夹均消失了,这是因为里面的文件夹属性被改为隐藏属性.通过查看显示隐藏文件夹发现,所有隐藏了的文件夹的隐藏属性被锁定,无法通过鼠标右键查看文件夹属性的方法改 ...