1.JSR303规范给出的注解
@NotNull 注解元素必须是非空
@Null 注解元素必须是空
@Digits 验证数字构成是否合法
@Future 验证是否在当前系统时间之后
@Past 验证是否在当前系统时间之前
@Max 验证值是否小于等于最大指定整数值
@Min 验证值是否大于等于最小指定整数值
@Pattern 验证字符串是否匹配指定的正则表达式
@Size 验证元素大小是否在指定范围内
@DecimalMax 验证值是否小于等于最大指定小数值
@DecimalMin 验证值是否大于等于最小指定小数值
@AssertTrue 被注释的元素必须为true
@AssertFalse 被注释的元素必须为false
Hibernate validator 在JSR303的基础上对校验注解进行了扩展,扩展注解如下:
@Email 被注释的元素必须是电子邮箱地址
@Length 被注释的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串的必须非空
@Range 被注释的元素必须在合适的范围内
2.使用
假设要完成一笔交易订单:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>validate</title>
</head>
<body>
<form action = "./validate/annotation.do">
<!--
<form action = "./validate/validator.do">
-->
<table>
<tr>
<td>产品编号:</td>
<td><input name="productId" id="productId"/></td>
</tr>
<tr>
<td>用户编号:</td>
<td><input name="userId" id="userId"/></td>
</tr>
<tr>
<td>交易日期:</td>
<td><input name="date" id="date"/></td>
</tr>
<tr>
<td>价格:</td>
<td><input name="price" id="price"/></td>
</tr>
<tr>
<td>数量:</td>
<td><input name="quantity" id="quantity"/> </td>
</tr>
<tr>
<td>交易金额:</td>
<td><input name="amount" id="amount"/></td>
</tr>
<tr>
<td>用户邮件:</td>
<td><input name="email" id="email"/></td>
</tr>
<tr>
<td>备注:</td>
<td><textarea id="note" name="note" cols="20" rows="5"></textarea></td>
</tr>
<tr><td colspan="2" align="right"> <input type="submit" value="提交"/> </tr>
</table>
<form>
</body>
</html>
表单pojo:
package com.ssm.chapter15.pojo;
import java.util.Date;
import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Future;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.springframework.format.annotation.DateTimeFormat;
public class Transaction {
// 产品编号
@NotNull // 不能为空
private Long productId;
// 用户编号
@NotNull // 不能为空
private Long userId;
// 交易日期
@Future // 只能是将来的日期
@DateTimeFormat(pattern = "yyyy-MM-dd") // 日期格式化转换
@NotNull // 不能为空
private Date date;
// 价格
@NotNull // 不能为空
@DecimalMin(value = "0.1") // 最小值0.1元
private Double price;
// 数量
@Min(1) // 最小值为1
@Max(100) // 最大值
@NotNull // 不能为空
private Integer quantity;
// 交易金额
@NotNull // 不能为空
@DecimalMax("500000.00") // 最大金额为5万元
@DecimalMin("1.00") // 最小交易金额1元
private Double amount;
// 邮件
@Pattern(// 正则式
regexp = "^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@"+ "([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$",
// 自定义消息提示
message = "不符合邮件格式")
private String email;
// 备注
@Size(min = 0, max = 256) // 0到255个字符
private String note;
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
用控制器完成表单的验证:
@Controller
@RequestMapping("/validate")
public class ValidateController {
@RequestMapping("/annotation")
public ModelAndView annotationValidate(@Valid Transaction trans, Errors errors)
{
if (errors.hasErrors()) {
List<FieldError> errorList = errors.getFieldErrors();
for (FieldError error : errorList) {
System.out.println("field:"+error.getField()+"/t"+"msg"+error.getDefaultMessage());
}
}
ModelAndView mv = new ModelAndView();
mv.setViewName("show");
return mv;
}
}
使用注解@Valid表明这个Bean会被检验(为要检验的bean的类),而另外一个参数errors是用来保存是否存在错误信息的,也就是采用JSR303规范进行校验后,其会将错误的信息保存在这个参数之中,进入方法hasErrors,来判断其是否存在错误。
这里来检验一下:
打印出来: