#每天踩一踩坑# 解决Spring MVC使用@Valid注解校验表单无效

最近在学习Spring MVC的想做一下对表单数据的校验,根据书里的提示,引入了以下依赖:

        
            javax.validation
            validation-api
            2.0.1.Final
        

然后就做如下操作:

package ink.kilig.model;


import javax.validation.constraints.*;
/**
 * @author: Hps
 * @date: 2020/5/24 15:20
 * @description:
 */

public class User {



    @Size(min = 1,max = 3)
    private String name;


    @Max(10L)
    private int age;

    private boolean sex;

    public User() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public User(String name, int age,boolean sex) {
        this.name = name;
        this.age = age;
        this.sex=sex;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex=" + sex +
                '}';
    }

    public void setAge(int age) {
        this.age = age;
    }

    public boolean isSex() {
        return sex;
    }

    public void setSex(boolean sex) {
        this.sex = sex;
    }
}


    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public String processRegistration(@Valid User user,
                                      Errors errors, RedirectAttributes model)  {
        if(errors.hasErrors()){
            System.out.println(errors.getAllErrors());
            return "Error-404";
        }
        model.addFlashAttribute("user",user);
        System.out.println(user.getAge());
        return "redirect:/userinfo";
    }

但是在注册表单时,发现不起作用,经查阅资料知上述依赖并未提供实现,要引入以下依赖:

        <dependency>
            <groupId>org.hibernategroupId>
            <artifactId>hibernate-validatorartifactId>
            <version>5.1.1.Finalversion>
        dependency>

引入该依赖之后,还是发现该注解依然无效,在多次查询网上资料后,猜测可能是没把环境引入到war包内,查看一下导出的lib包,果然,发现没有这个jar包(Project structure):

#每天踩一踩坑# 解决Spring MVC使用@Valid注解校验表单无效_第1张图片

双击右边的jar包移到左边之后,终于起效了!!!

如果这篇文章能够帮到你,请您帮我点个赞,谢谢!

你可能感兴趣的:(一些小坑,Spring)