zoukankan      html  css  js  c++  java
  • 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";
    }
  • 相关阅读:
    [CF1263E] Editor
    [CF1288D] Minimax Problem
    [CF1294E] Obtain a Permutation
    [CF770C] Online Courses In BSU
    [CF832D] Misha, Grisha and Underground
    [CF917B] MADMAX
    [CF938D] Buy a Ticket
    [CF959E] Mahmoud and Ehab and the xor-MST
    [CF999E] Reachability from the Capital
    [CF960F] Pathwalks
  • 原文地址:https://www.cnblogs.com/lowerma/p/11841589.html
Copyright © 2011-2022 走看看