spring MVC validator

简介:

spring mVC提供了很方便的校验,如下:

 

(1)依赖包:

validation-api.jar
hibernate-validator.jar

通过maven引入

Xml代码   收藏代码
  1. <dependency>  
  2.         <groupId>javax.validation</groupId>  
  3.         <artifactId>validation-api</artifactId>  
  4.         <version>1.1.0.Final</version>  
  5.     </dependency>  
  6.     <dependency>  
  7.         <groupId>org.hibernate</groupId>  
  8.         <artifactId>hibernate-validator</artifactId>  
  9.         <version>5.1.2.Final</version>  
  10.     </dependency>  

 

(2)要验证的实体类

Java代码   收藏代码
  1. import javax.validation.constraints.AssertFalse;  
  2. import javax.validation.constraints.AssertTrue;  
  3. import javax.validation.constraints.DecimalMax;  
  4. import javax.validation.constraints.DecimalMin;  
  5. import javax.validation.constraints.Max;  
  6. import javax.validation.constraints.Min;  
  7. import javax.validation.constraints.NotNull;  
  8. import javax.validation.constraints.Pattern;  
  9. public class Person {  
  10.        
  11.      @NotNull(message = "用户名称不能为空")   
  12.      private String name;  
  13.        
  14.      @Max(value = 100, message = "年龄不能大于100岁")   
  15.      @Min(value= 18 ,message= "必须年满18岁!" )    
  16.      private int age;  
  17.        
  18.      //必须是ture     
  19.      @AssertTrue(message = "bln4 must is true")  
  20.      private boolean bln;  
  21.        
  22.         //必须是false  
  23.      @AssertFalse(message = "blnf must is falase")  
  24.      private boolean blnf;  
  25.        
  26.      @DecimalMax(value="100",message="decim最大值是100")  
  27.      private int decimax;  
  28.        
  29.      @DecimalMin(value="100",message="decim最小值是100")  
  30.      private int decimin;  
  31.        
  32.     // @Length(min=1,max=5,message="slen长度必须在1~5个字符之间")  
  33.      private String slen;  
  34.       
  35.      @NotNull(message = "身份证不能为空")   
  36.          @Pattern(regexp="^(\\d{18,18}|\\d{15,15}|(\\d{17,17}[x|X]))$", message="身份证格式错误")  
  37.      private String iDCard;  
  38.        
  39.      @NotNull(message="密码不能为空")  
  40.      private String password;  
  41.      @NotNull(message="验证密码不能为空")  
  42.      private String rpassword;  
  43.       
  44.         get/set方法  
  45. }  

 (3)构建controller如下

Java代码   收藏代码
  1. @Controller  
  2. public class SpringValidatorTest {  
  3.     @RequestMapping("/validator/springtest")  
  4.     public void  springte(@Valid Person person,BindingResult result){  
  5.         if(result.hasErrors()){  
  6.             List<ObjectError>  list = result.getAllErrors();  
  7.             for(ObjectError error: list){  
  8.                 //System.out.println(error.getObjectName());  
  9.                 //System.out.println(error.getArguments()[0]);  
  10.                 System.out.println(error.getDefaultMessage());//验证信息  
  11.             }  
  12.                       
  13.         }  
  14.       
  15.     }  
  16. }  

 

 

(4)使用场景:添加或提交修改时进行字段的校验



 登录:


 

 

注意:BindingResult一定要紧跟在实体类的后面,否则报错:

HTTP Status 400 -


type Status report

message

description The request sent by the client was syntactically incorrect.


Apache Tomcat/7.0.53

 

错误的代码:

Java代码   收藏代码
  1. @RequestMapping(value = "/add",method=RequestMethod.POST)  
  2.     public String addSaveNews(@Valid RoleLevel roleLevel, Model model, BindingResult binding) {  
  3.         if(binding.hasErrors()){  
  4.             model.addAttribute(roleLevel);  
  5.             return jspFolder+"/add";  
  6.         }  
  7.         saveCommon(roleLevel, model);  
  8.         return redirectViewAll;  
  9.     }  

 正确的代码:

Java代码   收藏代码
  1. @RequestMapping(value = "/add",method=RequestMethod.POST)  
  2.     public String addSaveNews(@Valid RoleLevel roleLevel, BindingResult binding, Model model) {  
  3.         if(binding.hasErrors()){  
  4.             model.addAttribute(roleLevel);  
  5.             return jspFolder+"/add";  
  6.         }  
  7.         saveCommon(roleLevel, model);  
  8.         return redirectViewAll;  
  9.     }  

 

官方资料

Declaring bean constraints

Constraints in Bean Validation are expressed via Java annotations. In this section you will learn how to enhance an object model with these annotations. There are the following three types of bean constraints:

  • field constraints

  • property constraints

  • class constraints

Note

Not all constraints can be placed on all of these levels. In fact, none of the default constraints defined by Bean Validation can be placed at class level. TheJava.lang.annotation.Target annotation in the constraint annotation itself determines on which elements a constraint can be placed. See Chapter 6, Creating custom constraints for more information.

2.1.1. Field-level constraints

Constraints can be expressed by annotating a field of a class. Example 2.1, “Field-level constraints”shows a field level configuration example:

Example 2.1. Field-level constraints

package org.hibernate.validator.referenceguide.chapter02.fieldlevel;

public class Car {

    @NotNull
    private String manufacturer;

    @AssertTrue
    private boolean isRegistered;

    public Car(String manufacturer, boolean isRegistered) {
        this.manufacturer = manufacturer;
        this.isRegistered = isRegistered;
    }

    //getters and setters...
}

When using field-level constraints field access strategy is used to access the value to be validated. This means the validation engine directly accesses the instance variable and does not invoke the property accessor method even if such an accessor exists.

Constraints can be applied to fields of any access type (public, private etc.). Constraints on static fields are not supported, though.

Tip

When validating byte code enhanced objects property level constraints should be used, because the byte code enhancing library won't be able to determine a field access via reflection.

2.1.2. Property-level constraints

If your model class adheres to the JavaBeans standard, it is also possible to annotate the properties of a bean class instead of its fields. Example 2.2, “Property-level constraints” uses the same entity as inExample 2.1, “Field-level constraints”, however, property level constraints are used.

Example 2.2. Property-level constraints

package org.hibernate.validator.referenceguide.chapter02.propertylevel;

public class Car {

    private String manufacturer;

    private boolean isRegistered;

    public Car(String manufacturer, boolean isRegistered) {
        this.manufacturer = manufacturer;
        this.isRegistered = isRegistered;
    }

    @NotNull
    public String getManufacturer() {
        return manufacturer;
    }

    public void setManufacturer(String manufacturer) {
        this.manufacturer = manufacturer;
    }

    @AssertTrue
    public boolean isRegistered() {
        return isRegistered;
    }

    public void setRegistered(boolean isRegistered) {
        this.isRegistered = isRegistered;
    }
}

Note

The property's getter method has to be annotated, not its setter. That way also read-only properties can be constrained which have no setter method.

When using property level constraints property access strategy is used to access the value to be validated, i.e. the validation engine accesses the state via the property accessor method.

Tip

It is recommended to stick either to field or property annotations within one class. It is not recommended to annotate a field and the accompanying getter method as this would cause the field to be validated twice.

2.1.3. Class-level constraints

Last but not least, a constraint can also be placed on the class level. In this case not a single property is subject of the validation but the complete object. Class-level constraints are useful if the validation depends on a correlation between several properties of an object.

The Car class in Example 2.3, “Class-level constraint” has the two attributes seatCount and passengersand it should be ensured that the list of passengers has not more entries than seats are available. For that purpose the @ValidPassengerCount constraint is added on the class level. The validator of that constraint has access to the complete Car object, allowing to compare the numbers of seats and passengers.

Refer to Section 6.2, “Class-level constraints” to learn in detail how to implement this custom constraint.

Example 2.3. Class-level constraint

package org.hibernate.validator.referenceguide.chapter02.classlevel;

@ValidPassengerCount
public class Car {

    private int seatCount;

    private List<Person> passengers;

    //...
}

 

 

参考:http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html/

http://www.yunmasoft.com

http://blog.csdn.net/xpsharp/article/details/9366865

 

相关文章
|
21天前
|
缓存 前端开发 Java
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
Soring Boot的起步依赖、启动流程、自动装配、常用的注解、Spring MVC的执行流程、对MVC的理解、RestFull风格、为什么service层要写接口、MyBatis的缓存机制、$和#有什么区别、resultType和resultMap区别、cookie和session的区别是什么?session的工作原理
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
|
9天前
|
XML 缓存 前端开发
springMVC02,restful风格,请求转发和重定向
文章介绍了RESTful风格的基本概念和特点,并展示了如何使用SpringMVC实现RESTful风格的请求处理。同时,文章还讨论了SpringMVC中的请求转发和重定向的实现方式,并通过具体代码示例进行了说明。
springMVC02,restful风格,请求转发和重定向
|
2月前
|
Java 数据库连接 Spring
后端框架入门超详细 三部曲 Spring 、SpringMVC、Mybatis、SSM框架整合案例 【爆肝整理五万字】
文章是关于Spring、SpringMVC、Mybatis三个后端框架的超详细入门教程,包括基础知识讲解、代码案例及SSM框架整合的实战应用,旨在帮助读者全面理解并掌握这些框架的使用。
后端框架入门超详细 三部曲 Spring 、SpringMVC、Mybatis、SSM框架整合案例 【爆肝整理五万字】
|
2月前
|
XML JSON 数据库
SpringMVC入门到实战------七、RESTful的详细介绍和使用 具体代码案例分析(一)
这篇文章详细介绍了RESTful的概念、实现方式,以及如何在SpringMVC中使用HiddenHttpMethodFilter来处理PUT和DELETE请求,并通过具体代码案例分析了RESTful的使用。
SpringMVC入门到实战------七、RESTful的详细介绍和使用 具体代码案例分析(一)
|
2月前
|
前端开发 应用服务中间件 数据库
SpringMVC入门到实战------八、RESTful案例。SpringMVC+thymeleaf+BootStrap+RestFul实现员工信息的增删改查
这篇文章通过一个具体的项目案例,详细讲解了如何使用SpringMVC、Thymeleaf、Bootstrap以及RESTful风格接口来实现员工信息的增删改查功能。文章提供了项目结构、配置文件、控制器、数据访问对象、实体类和前端页面的完整源码,并展示了实现效果的截图。项目的目的是锻炼使用RESTful风格的接口开发,虽然数据是假数据并未连接数据库,但提供了一个很好的实践机会。文章最后强调了这一章节主要是为了练习RESTful,其他方面暂不考虑。
SpringMVC入门到实战------八、RESTful案例。SpringMVC+thymeleaf+BootStrap+RestFul实现员工信息的增删改查
|
2月前
|
JSON 前端开发 Java
Spring MVC返回JSON数据
综上所述,Spring MVC提供了灵活、强大的方式来支持返回JSON数据,从直接使用 `@ResponseBody`及 `@RestController`注解,到通过配置消息转换器和异常处理器,开发人员可以根据具体需求选择合适的实现方式。
97 4
|
2月前
|
XML 前端开发 Java
Spring MVC接收param参数(直接接收、注解接收、集合接收、实体接收)
Spring MVC提供了灵活多样的参数接收方式,可以满足各种不同场景下的需求。了解并熟练运用这些基本的参数接收技巧,可以使得Web应用的开发更加方便、高效。同时,也是提高代码的可读性和维护性的关键所在。在实际开发过程中,根据具体需求选择最合适的参数接收方式,能够有效提升开发效率和应用性能。
91 3
|
2月前
|
XML 前端开发 Java
Spring MVC接收param参数(直接接收、注解接收、集合接收、实体接收)
Spring MVC提供了灵活多样的参数接收方式,可以满足各种不同场景下的需求。了解并熟练运用这些基本的参数接收技巧,可以使得Web应用的开发更加方便、高效。同时,也是提高代码的可读性和维护性的关键所在。在实际开发过程中,根据具体需求选择最合适的参数接收方式,能够有效提升开发效率和应用性能。
92 2
|
2月前
|
前端开发 Java Spring
Java 新手入门:Spring Boot 轻松整合 Spring 和 Spring MVC!
Java 新手入门:Spring Boot 轻松整合 Spring 和 Spring MVC!
49 0
|
3月前
|
JSON 前端开发 Java
Spring Boot中的MVC支持
本节课主要讲解了 Spring Boot 中对 MVC 的支持,分析了 @RestController、 @RequestMapping、@PathVariable、 @RequestParam 和 @RequestBody 四个注解的使用方式,由于 @RestController 中集成了 @ResponseBody 所以对返回 json 的注解不再赘述。以上四个注解是使用频率很高的注解,在所有的实际项目中基本都会遇到,要熟练掌握。
下一篇
无影云桌面