开发者社区> 黄威的世界> 正文
阿里云
为了无法计算的价值
打开APP
阿里云APP内打开

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

 

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
一文弄懂spring validate(下)
一文弄懂spring validate(下)
34 0
一文弄懂spring validate(上)
一文弄懂spring validate(上)
30 0
springboot使用hibernate validator校验
在做web相关的应用时,经常需要提供接口与用户交互(获取数据、上传数据等),由于这个过程需要用户进行相关的操作,为了避免出现一些错误的数据等,一般需要对数据进行校验,随着接口的增多,校验逻辑的冗余度也越来越大,虽然可以通过抽象出校验的方法来处理,但还是需要每次手动调用校验逻辑,相对来说还是不方便。
3119 0
SSM-SpringMVC-31:SpringMVC中利用hibernate-validator做后台校验
    ------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥-------------     校验有三种:前台页面校验(例如js和h5),后台校验,数据库校验 但是一般能不用数据库校验就不用数据库校验,因为性能损耗严重, 所以,我们用前台和后台俩种,可以说最好,绝大部...
1980 0
SpringMVC之使用Validator接口进行验证
对于任何一个应用而言在客户端做的数据有效性验证都不是安全有效的,这时候就要求我们在开发的时候在服务端也对数据的有效性进行验证。SpringMVC自身对数据在服务端的校验有一个比较好的支持,它能将我们提交到服务端的数据按照我们事先的约定进行数据有效性验证,对于不合格的数据信息SpringMVC会把它保存在错误对象中,这些错误信息我们也可以通过SpringMVC提供的标签在前端JSP页面上进行展示。
1423 0
在springmvc中使用hibernate-validate
在springmvc.xml中加入 1 2 3 4 5 6 classpath:resource/ValidationMessages 7 ...
709 0
SpringMVC 使用验证框架 Bean Validation(下)
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/catoop/article/details/51284638 本文接上一篇《SpringMVC 使用验证框架 Bean Validation(上)》: 四、Controller 普通参数验证与视图错误信息的展示 对于 form 表单提交绑定到对象的验证方式,上面已经介绍了。
985 0
SpringMVC介绍之Validation
SpringMVC介绍之Validation        对于任何一个应用而言在客户端做的数据有效性验证都不是安全有效的,这时候就要求我们在开发的时候在服务端也对数据的有效性进行验证。
1172 0
+关注
黄威的世界
我是一个热衷IT技术的人,希望自己不断地设计开发出对别人非常有用的软件。有近7年的java开发经验(包括2年Android开发经验)和一年左右的linux使用经验。擅长Java Web后台开发 ,喜欢研究新的各种实用技术
667
文章
0
问答
文章排行榜
最热
最新
相关电子书
更多
低代码开发师(初级)实战教程
立即下载
阿里巴巴DevOps 最佳实践手册
立即下载
冬季实战营第三期:MySQL数据库进阶实战
立即下载