JSR303数据有效性验证

JSR介绍
JSR是Java Specification Requests的缩写,意思是Java 规范提案。是指向JCP(Java Community Process)提出新增一个标准化技术规范的正式请求。任何人都可以提交JSR,以向Java平台增添新的API和服务。JSR已成为Java界的一个重要标准。

JSR-303 是JAVA EE 6 中的一项子规范,叫做Bean Validation,Hibernate Validator 是 Bean Validation 的参考实现 . Hibernate Validator 提供了 JSR 303 规范中所有内置 constraint 的实现,除此之外还有一些附加的 constraint。

Hibernate Validator 是 Bean Validation 的参考实现 . Hibernate Validator 提供了 JSR 303 规范中所有内置 constraint 的实现,除此之外还有一些附加的 constraint。

注解详解

@Valid

被注释的元素是一个对象,需要检查此对象的所有字段值

@Null

被注释的元素必须为 null

@NotNull

被注释的元素必须不为 null

@AssertTrue

被注释的元素必须为 true

@AssertFalse

被注释的元素必须为 false

@Min(value)

被注释的元素必须是一个数字,其值必须大于等于指定的最小值

@Max(value)

被注释的元素必须是一个数字,其值必须小于等于指定的最大值

@DecimalMin(value)

被注释的元素必须是一个数字,其值必须大于等于指定的最小值

@DecimalMax(value)

被注释的元素必须是一个数字,其值必须小于等于指定的最大值

@Size(max, min)

被注释的元素的大小必须在指定的范围内

@Digits (integer, fraction)

被注释的元素必须是一个数字,其值必须在可接受的范围内

@Past

被注释的元素必须是一个过去的日期

@Future

被注释的元素必须是一个将来的日期

@Pattern(value)

被注释的元素必须符合指定的正则表达式

 Hibernate Validator 附加的 constraint

注解

作用

@Email

被注释的元素必须是电子邮箱地址

@Length(min=, max=)

被注释的字符串的大小必须在指定的范围内

@NotEmpty

被注释的字符串的必须非空

@Range(min=, max=)

被注释的元素必须在合适的范围内

@NotBlank

被注释的字符串的必须非空

@URL(protocol=,
host=,    port=, 
regexp=, flags=)

被注释的字符串必须是一个有效的url

@CreditCardNumber

被注释的字符串必须通过Luhn校验算法,
银行卡,信用卡等号码一般都用Luhn
计算合法性

@ScriptAssert
(lang=, script=, alias=)

要有Java Scripting API JSR 223 
("Scripting for the JavaTM Platform")
的实现

@SafeHtml
(whitelistType=, 
additionalTags=)

classpath中要有jsoup

hibernate补充的注解中,最后3个不常用,可忽略。

主要区分下@NotNull  @NotEmpty  @NotBlank 3个注解的区别:

@NotNull           任何对象的value不能为null

@NotEmpty       集合对象的元素不为0,即集合不为空,也可以用于字符串不为null

@NotBlank        只能用于字符串不为null,并且字符串trim()以后length要大于0

举个使用的例子:

    public class User {  
          
        @NotBlank  
        private String name;  
          
        //年龄要大于18岁  
        @Min(18)  
        private int age;  
      
        @Email  
        private String email;  
          
        //嵌套验证  
        @Valid  
        private Product products;  
          
        ... //省略getter,setter  
    }  
      
    public class Product {  
          
        @NotBlank  
        private String name;  
          
        //价格在10元-50元之间  
        @Range(min=10,max=50)  
        private int price;  
          
        ... //省略getter,setter  
    }  

布属运用步骤如下:

  1. pom.xml中引入相关依赖
    <!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
    		<dependency>
    			<groupId>org.hibernate.validator</groupId>
    			<artifactId>hibernate-validator</artifactId>
    			<version>6.2.5.Final</version>
    		</dependency>
    		<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator-annotation-processor -->
    		<dependency>
    			<groupId>org.hibernate.validator</groupId>
    			<artifactId>hibernate-validator-annotation-processor</artifactId>
    			<version>6.2.5.Final</version>
    		</dependency>

  2. 对类中需要数据验证的属性加入相应的注解
     

    public class User {
    	private int id;
    	@NotEmpty
    	private String name;
    	@Min(value =1) 
    	@Max(value =200) 
    	private int age;
    	@NotEmpty
    	private String pwd;
    	@Past
    	private Date birthday;
    	@NotNull
    	private Department dpt;
    	@DecimalMin(value = "1")
    	@DecimalMax(value = "3")
    	private Double height;
    	@Email
    	private String email;
    setter,getter略............
    
    }

  3. 在需要进行验证的controller中加入@Valid注解,紧跟在对象的后面添加 Errors 或BindingResult对像,注意model在注入不能再用commad 与对像绑定,需重命名绑定,同时展示视图中要用modelAttribute="重命名",否则会报错
    controller中:
     

    @RequestMapping(value = "/user", method = RequestMethod.POST)
        /*对像User、Errors必须按顺序紧挨在一下起*/
    	public String addUser(@Valid User user,Errors err,Model model) {
    		if (err.getErrorCount()>0) {
    			System.out.println("有不相符数据提交");
                /*打印不相符的信息*/
    			for(FieldError fe:err.getFieldErrors()) {
    				System.out.println("======="+fe.getField()+":"+fe.getDefaultMessage());
    			}
    			model.addAttribute("user", user);
    			model.addAttribute("dpts", departmentService.getAllDepartments());
    			return "addUserView";
    		}
    		userService.add(user);
    		return "redirect:/users";
    	}

    JSP视图中:
     

    <form:form action="${path}/user" method="post" modelAttribute="user">  
        用户名:<form:input path="name" /><form:errors path="name"/>
        年齡:<form:input path="age" /><form:errors path="age"/>
        密码:<form:input path="pwd" /><form:errors path="pwd"/>
        生日:<form:input path="birthday" /><form:errors path="birthday"/>
        身高:<form:input path="height" /><form:errors path="height"/>
        邮箱:<form:input path="email" /><form:errors path="email"/>
        部门:<form:select path="dpt.id" items="${dpts}" itemValue="id"
    			itemLabel="name"></form:select>
    		<input type="submit" value="添加" />
    	</form:form>

  4. 验证结果

     

  5. 出现长中的错误代码提示,需使用国际化配置文件i18n.properties进行个性配置,详见以下链接:i18n国际化配置文件配置步骤_jingde528的博客-CSDN博客
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值