提到服务器端验证,从最开始的STRUTS1开始就提供了,只要是MVC框架都提供了验证框架;直到最后开源框架直接促使JAVA推出新的JSR Bean Validation 1.0(JSR-303);
http://www.iteye.com/topic/1123007
SPRING MVC 使用Hibernate Validator作为该标准的默认实现;
相关准备工作:
1.使用JSR303相关的JAR包
<!-- JSR 303 with Hibernate Validator -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.1.0.Final</version>
</dependency>
2. 在POJO上使用JSR303的相关注解:
package org.springframework.samples.mvc.form;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import javax.validation.constraints.Min;
import javax.validation.constraints.Past;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import org.springframework.format.annotation.NumberFormat.Style;
import org.springframework.samples.mvc.convert.MaskFormat;
public class FormBean {
@NotEmpty
private String name;
@Min(21)
private int age;
@DateTimeFormat(iso=ISO.DATE)
@Past
private Date birthDate;
@MaskFormat("(###) ###-####")
private String phone;
@NumberFormat(pattern="$###,###.00")
private BigDecimal currency;
@NumberFormat(style=Style.PERCENT)
private BigDecimal percent;
private InquiryType inquiry;
private String inquiryDetails;
private boolean subscribeNewsletter;
private Map<String, String> additionalInfo;
}
//get set方法在博文中省略
3.在controller中使用@Valid
@Valid
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@Valid FormBean formBean, BindingResult result,
@ModelAttribute("ajaxRequest") boolean ajaxRequest, Model model,
RedirectAttributes redirectAttrs) {
if (result.hasErrors()) {
return null;
}
}
4.注意使用<mvc:annotation-driven> 后,不需要显式使用hibernate-validator