注意:1 public String save(@ModelAttribute("house") @Valid House entity, BindingResult result,HttpServletRequest request, Model model) BindingResult 必須放在model,request前面
2 validation-api-1.0.0.GA.jar是JDK的接口;hibernate-validator-4.2.0.Final.jar是對上述接口的實現。hibernate-validator-4.2.0.Final可以,但是hibernate-validator-4.3.0.Final報錯
驗證注解 |
驗證的數據類型 |
說明 |
@AssertFalse |
Boolean,boolean |
驗證注解的元素值是false |
@AssertTrue |
Boolean,boolean |
驗證注解的元素值是true |
@NotNull |
任意類型 |
驗證注解的元素值不是null |
@Null |
任意類型 |
驗證注解的元素值是null |
@Min(value=值) |
BigDecimal,BigInteger, byte, short, int, long,等任何Number或CharSequence(存儲的是數字)子類型 |
驗證注解的元素值大於等於@Min指定的value值 |
@Max(value=值) |
和@Min要求一樣 |
驗證注解的元素值小於等於@Max指定的value值 |
@DecimalMin(value=值) |
和@Min要求一樣 |
驗證注解的元素值大於等於@ DecimalMin指定的value值 |
@DecimalMax(value=值) |
和@Min要求一樣 |
驗證注解的元素值小於等於@ DecimalMax指定的value值 |
@Digits(integer=整數位數, fraction=小數位數) |
和@Min要求一樣 |
驗證注解的元素值的整數位數和小數位數上限 |
@Size(min=下限, max=上限) |
字符串、Collection、Map、數組等 |
驗證注解的元素值的在min和max(包含)指定區間之內,如字符長度、集合大小 |
@Past |
java.util.Date, java.util.Calendar; Joda Time類庫的日期類型 |
驗證注解的元素值(日期類型)比當前時間早 |
@Future |
與@Past要求一樣 |
驗證注解的元素值(日期類型)比當前時間晚 |
@NotBlank |
CharSequence子類型 |
驗證注解的元素值不為空(不為null、去除首位空格后長度為0),不同於@NotEmpty,@NotBlank只應用於字符串且在比較時會去除字符串的首位空格 |
@Length(min=下限, max=上限) |
CharSequence子類型 |
驗證注解的元素值長度在min和max區間內 |
@NotEmpty |
CharSequence子類型、Collection、Map、數組 |
驗證注解的元素值不為null且不為空(字符串長度不為0、集合大小不為0) |
@Range(min=最小值, max=最大值) |
BigDecimal,BigInteger,CharSequence, byte, short, int, long等原子類型和包裝類型 |
驗證注解的元素值在最小值和最大值之間 |
@Email(regexp=正則表達式, flag=標志的模式) |
CharSequence子類型(如String) |
驗證注解的元素值是Email,也可以通過regexp和flag指定自定義的email格式 |
@Pattern(regexp=正則表達式, flag=標志的模式) |
String,任何CharSequence的子類型 |
驗證注解的元素值與指定的正則表達式匹配 |
@Valid |
任何非原子類型 |
指定遞歸驗證關聯的對象; 如用戶對象中有個地址對象屬性,如果想在驗證用戶對象時一起驗證地址對象的話,在地址對象上加@Valid注解即可級聯驗證 |
一、准備校驗時使用的JAR
說明:
validation-api-1.0.0.GA.jar是JDK的接口;
hibernate-validator-4.2.0.Final.jar是對上述接口的實現。
------------------------------------------------------------------------------------------------
新增一個測試的pojo bean ,增加jsr 303格式的驗證annotation
- @NotEmpty
- private String userName;
- private String email;
在controller 類中的handler method中,對需要驗證的對象前增加@Valid 標志
- @RequestMapping("/valid")
- public String valid(@ModelAttribute("vm") [color=red]@Valid[/color] ValidModel vm, BindingResult result) {
- if (result.hasErrors()) {
- return "validResult";
- }
- return "helloworld";
- }
增加顯示驗證結果的jsp如下
- <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
- <html>
- <head>
- <title>Reservation Form</title>
- <style>
- .error {
- color: #ff0000;
- font-weight: bold;
- }
- </style>
- </head>
- <body>
- <form:form method="post" modelAttribute="vm">
- <form:errors path="*" cssClass="error" />
- <table>
- <tr>
- <td>Name</td>
- <td><form:input path="userName" />
- </td>
- <td><form:errors path="userName" cssClass="error" />
- </td>
- </tr>
- <tr>
- <td>email</td>
- <td><form:input path="email" />
- </td>
- <td><form:errors path="email" cssClass="error" />
- </td>
- </tr>
- <tr>
- <td colspan="3"><input type="submit" />
- </td>
- </tr>
- </table>
- </form:form>
- </body>
- </html>
訪問 http://localhost:8080/springmvc/valid?userName=winzip&email=winzip
查看驗證結果。
二:自定義jsr 303格式的annotation
參考hibernate validator 4 reference 手冊中3.1節,增加一個自定義要求輸入內容為定長的annotation驗證類
新增annotation類定義
- @Target( { METHOD, FIELD, ANNOTATION_TYPE })
- @Retention(RUNTIME)
- @Constraint(validatedBy = FixLengthImpl.class)
- public @interface FixLength {
- int length();
- String message() default "{net.zhepu.web.valid.fixlength.message}";
- Class<?>[] groups() default {};
- Class<? extends Payload>[] payload() default {};
- }
及具體的驗證實現類如下
- public class FixLengthImpl implements ConstraintValidator<FixLength, String> {
- private int length;
- @Override
- public boolean isValid(String validStr,
- ConstraintValidatorContext constraintContext) {
- if (validStr.length() != length) {
- return false;
- } else {
- return true;
- }
- }
- @Override
- public void initialize(FixLength fixLen) {
- this.length = fixLen.length();
- }
- }
為使自定義驗證標注的message正常顯示,需要修改servlet context配置文件,新增messageSource bean,如下
- <bean id="messageSource"
- class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
- p:fallbackToSystemLocale="true" p:useCodeAsDefaultMessage="false"
- p:defaultEncoding="UTF-8">
- <description>Base message source to handle internationalization
- </description>
- <property name="basenames">
- <list>
- <!-- main resources -->
- <value>classpath:valid/validation</value>
- </list>
- </property>
- </bean>
表示spring 將從路徑valid/validation.properties中查找對於的message。
新增valid bean 引用新增的messageSource bean,表示valid message將從messageSource bean 注入。
- <bean id="validator"
- class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"
- p:validationMessageSource-ref="messageSource">
- <description>Enable the bean validation provider, and configure it to
- use the messageSource when resolving properties</description>
- </bean>
修改 <mvc:annotation-driven> 增加對validator bean的引用
- <mvc:annotation-driven validator="validator" />
最后修改之前新增的pojo bean ,新增一個mobileNO屬性並增加對自定義標注的引用
- @FixLength(length=11)
- private String mobileNO;
在前端jsp中也增加新字段的支持
- <tr>
- <td>mobileno</td>
- <td><form:input path="mobileNO" />
- </td>
- <td><form:errors path="mobileNO" cssClass="error" />
- </td>
- </tr>
可訪問url http://localhost:8080/springmvc/valid?userName=winzip&email=winzip&mobileNO=138188888
來查看修改的結果。
三 json輸入的驗證
Spring mvc 3.0.5中對於json格式的輸入直接使用@valid標注有問題,目前這個bug還未修復 (見 SPR-6709),預計在3.1 m2版本中會修復。
在此之前,可以通過如下幾種方式來對json(或xml)格式的輸入來進行驗證。
1:在handler method中直接對輸入結果進行驗證
- @RequestMapping("/validJson1")
- @ResponseBody
- public JsonResult processSubmitjson(@RequestBody ValidModel vm,
- HttpServletRequest request) {
- JsonResult jsonRst = new JsonResult();
- Set<ConstraintViolation<ValidModel>> set = validator.validate(vm);
- for (ConstraintViolation<ValidModel> violation : set) {
- String propertyPath = violation.getPropertyPath().toString();
- ;
- String message = violation.getMessage();
- log.error("invalid value for: '" + propertyPath + "': "
- + message);
- }
- if (!set.isEmpty()){
- jsonRst.setSuccess(false);
- jsonRst.setMsg("輸入有誤!");
- return jsonRst;
- }
- jsonRst.setSuccess(true);
- jsonRst.setMsg("輸入成功!");
- return jsonRst;
- }
可通過修改后的helloworld.jsp中的json valid test1按鈕進行調用測試。
2:將此驗證邏輯封裝為一個AOP,當需驗證的對象前有@valid標注和@RequestBody標注時開始驗證
新增handler method如下
- @RequestMapping("/validJson2")
- @ResponseBody
- public JsonResult testJson4(@RequestBody @Valid ValidModel vm){
- log.info("handle json for valid");
- return new JsonResult(true,"return ok");
- }
這里沒有對輸入值做任何驗證,所有的驗證都在AOP中完成。
修改pom.xml增加對AOP相關類庫的引用。
- <dependency>
- <groupId>org.aspectj</groupId>
- <artifactId>aspectjweaver</artifactId>
- <version>1.6.11</version>
- </dependency>
- <dependency>
- <groupId>cglib</groupId>
- <artifactId>cglib</artifactId>
- <version>2.2.2</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-aop</artifactId>
- <version>${org.springframework.version}</version>
- </dependency>
修改servet context xml,增加對aop的支持。
- <!-- enable Spring AOP support -->
- <aop:aspectj-autoproxy proxy-target-class="true" />
最后,新增AOP類
- public class CustomerValidatorAOP {
- private Validator validator;
- @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
- private void controllerInvocation() {
- }
- @Around("controllerInvocation()")
- public Object aroundController(ProceedingJoinPoint joinPoint) throws Throwable {
- MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
- Method method = methodSignature.getMethod();
- Annotation[] annotationList = method.getAnnotations();
- /* for(Annotation anno:annotationList){
- System.out.println(ResponseBody.class.isInstance(anno));
- }
- */
- Annotation[][] argAnnotations = method.getParameterAnnotations();
- String[] argNames = methodSignature.getParameterNames();
- Object[] args = joinPoint.getArgs();
- for (int i = 0; i < args.length; i++) {
- if (hasRequestBodyAndValidAnnotations(argAnnotations[i])) {
- Object ret = validateArg(args[i], argNames[i]);
- if(ret != null){
- return ret;
- }
- }
- }
- return joinPoint.proceed(args);
- }
- private boolean hasRequestBodyAndValidAnnotations(Annotation[] annotations) {
- if (annotations.length < 2)
- return false;
- boolean hasValid = false;
- boolean hasRequestBody = false;
- for (Annotation annotation : annotations) {
- if (Valid.class.isInstance(annotation))
- hasValid = true;
- else if (RequestBody.class.isInstance(annotation))
- hasRequestBody = true;
- if (hasValid && hasRequestBody)
- return true;
- }
- return false;
- }
- private JsonResult validateArg(Object arg, String argName) {
- BindingResult result = getBindingResult(arg, argName);
- validator.validate(arg, result);
- if (result.hasErrors()) {
- JsonResult jsonresult = new JsonResult();
- jsonresult.setSuccess(false);
- jsonresult.setMsg("fail");
- return jsonresult;
- }
- return null;
- }
- private BindingResult getBindingResult(Object target, String targetName) {
- return new BeanPropertyBindingResult(target, targetName);
- }
- @Required
- public void setValidator(Validator validator) {
- this.validator = validator;
- }
這里只考慮了輸入為json格式的情況,僅僅作為一種思路供參考,實際使用時需要根據項目具體情況進行調整。
可通過修改后的helloworld.jsp中的json valid test2按鈕進行調用測試。
原文:http://starscream.iteye.com/blog/1068905