SpringMVC数据校验(三)

来源:互联网 发布:2014年网络作家富豪榜 编辑:程序博客网 时间:2024/06/04 21:12

GitHub地址:

springMVC:

https://github.com/asd821300801/springMVC.git

Maven管理的springMVC:

https://github.com/asd821300801/MVC.git


SpringMVC—-数据校验

  • 1、导入相关jar包,springmvc配置<mvc:annotation-driven>
  • 2、相关POJO加上约束的注解,配置到get方法或者属性中
  • 3、Controller 中加上 @Valid 并紧跟 BindingResult


JSR 303是JAVA EE 6中的一项子规范(2009年11月确定),叫做Bean Validation官方参考实现是Hibernate Validator


Maven下载地址

<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator --><dependency>    <groupId>org.hibernate</groupId>    <artifactId>hibernate-validator</artifactId>    <version>5.2.4.Final</version></dependency>


Bean Validation 中内置的 constraint

 @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(regex=,flag=)  //被注释的元素必须符合指定的正则表达式       


Hibernate Validator 附加的 constraint

 @NotBlank(message =)   //验证字符串非null,且长度必须大于0        @Email  //被注释的元素必须是电子邮箱地址        @Length(min=,max=)  //被注释的字符串的大小必须在指定的范围内        @NotEmpty   //被注释的字符串的必须非空        @Range(min=,max=,message=)  //被注释的元素必须在合适的范围内 


1、实体类标记注解:

@NotNull(message="帐号不允许为空!")

1



2、方法参数中进行校验:

//标记验证级联的属性、方法参数或方法返回类型。//当属性、方法参数或方法返回类型被验证时,对对象及其属性定义的约束进行验证。@Valid  //需要校验的参数前面加上@Valid注解即可


绑定结果:BindingResult

2



获取单条错误

@RequestMapping("/add")public String addUser(@Valid User user,BindingResult rs,ModelMap map){    if(rs.hasErrors()){        //rs.getFieldErrors();//获取所有错误        map.addAttribute("msg", rs.getFieldError().getDefaultMessage());//获取第一条错误信息    }else{        // 调用service        System.out.println(user.getId());       }    map.addAttribute("user", user);    return "user/view";}


获取所有的错误

@RequestMapping("/add")    public String addUser(@Valid User user,BindingResult rs,ModelMap map,HttpServletRequest request){        //判断是否有错误        if(rs.hasErrors()){             map.addAttribute("msg",rs.getAllErrors());//获取所有的错误保存在msg        }else{            // 在没有错误的情况下才调用service            System.out.println(user.getId());        }        return "user/view";     }


打印所有的错误:


后台:

map.addAttribute("msg",rs.getAllErrors());

前台(jstl遍历):

<c:forEach var="item" items="${msg}">        错误信息:<c:out value="${item.defaultMessage}" /> <br /></c:forEach>

访问时不加参数:http://localhost:8080/springmvc/user/add?

3

访问时加上参数:http://localhost:8080/springmvc/user/add?name=lingdu&id=1

4

1 0
原创粉丝点击