SpringMVC---------数据校验

Spring MVC本身没有数据校验的功能,它使用Hibernate的校验框架来完成。

                        

 

 

 

                        

 

 

 

                     

 

 

 

1.导入pom节点

 

 <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.4.1.Final</version>
        </dependency>

 

2.POJO类绑定校验注解

public class Person {
    @Size(min=1,max=20,message = "{item.name.size}")
    private String username;
    private int age;
    @NotNull(message = "{item.birthday.notnull}")
    private Date birthday;
    //省略get/set方法
}

 

3. 新增PersonController方法

@RequestMapping(value = "/validate",method = RequestMethod.POST)
public String validate(@Validated Person person, BindingResult result,Map<String,Object> maps){
    //bindResult作为验证失败的信息,必须和@Validate成对出现
    if(result.hasErrors()){
        List<ObjectError> allErrors = result.getAllErrors();
        for (ObjectError error:allErrors) {
            System.out.println(error.getDefaultMessage());
        }
        maps.put("error",allErrors);
        return "error";
    }
    return "hello";
}

 

 

posted @ 2019-11-12 14:22  流氓大队长  阅读(146)  评论(0编辑  收藏  举报