【问题标题】:@Valid not working in Spring java@Valid 在 Spring java 中不起作用
【发布时间】:2017-10-04 19:46:38
【问题描述】:

我在 Spring mvc 中使用了@Valid。似乎它什么也没做。 这是我的程序

spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
        <mvc:annotation-driven/>
        <context:component-scan base-package="com.mvc"></context:component-scan>
        <bean id="viewResolver"
              class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                <property name="prefix">
                        <value>/</value>
                </property>
                <property name="suffix">
                        <value>.jsp</value>
                </property>
        </bean>
</beans>

这是控制器

 @RequestMapping(value="/test2")

public ModelAndView hello2(@Valid @ModelAttribute("person1") Person person1, BindingResult result){

    if(result.hasErrors()){
        ModelAndView model=new ModelAndView("form2");
        return model;
    }

    ModelAndView model = new ModelAndView("test2");

    return model;
}

Person.java 在这里我用过 @NotNull @Size(min=5,max=30,message = "last name should be 5-30 long")

public class Person {
    private String firstName;
    @NotNull
    @Size(min=5,max=30,message = "last name should be 5-30 long")
    private String lastName;
    private int age;

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public int getAge() {
        return age;
    }

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

}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mvc</groupId>
    <artifactId>SpringMvc</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>


    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.0.Alpha2</version>
        </dependency>
    </dependencies>
</project>

【问题讨论】:

  • 能用表单显示jsp页面吗?
  • 你也应该把你的jsp页面放在web-inf文件夹下。
  • 改用休眠验证器 5.4.1 最终版本。版本 6 用于 bean 验证 api 2.0

标签: java spring maven spring-mvc model-view-controller


【解决方案1】:

我添加了你通常做的东西(pom 中的库、RequestBody 上的@Valid 等)

Spring 文档(以及许多博客)留下的微妙之处在于 Spring 寻找一个退出点来抛出错误,但如果该退出不存在,它将回复 404。在阅读了很多之后,尤其是这个 @ 987654321@,添加这个类让Spring识别@Valid并找到退出点抛出错误

    @RestControllerAdvice
    @Order(1) 
    public class RestControllerExceptionHandler {

    @RequestMapping(value = { "error/404" }, method = RequestMethod.GET)
    @ExceptionHandler(Exception.class)
    public String handleUnexpectedException(Exception e) {
        return "views/base/rest-error";         
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public String handlemethodArgumentNotValid(MethodArgumentNotValidException exception) { //
        // TODO you can choose to return your custom object here, which will then get transformed to json/xml etc.
        return "Sorry, that was not quite right: " + exception.getMessage();
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ConstraintViolationException.class)
    public String handleConstraintViolation(ConstraintViolationException exception) { //
        // TODO you can choose to return your custom object here, which will then get transformed to json/xml etc.
        return "Sorry, that was not quite right: " + exception.getMessage();
    }

    
}

【讨论】:

    【解决方案2】:

    寻找6以下的Hibernate版本再试一次,使用@ModelAttribute可以将表单的输入映射到bean,而6.0的api 2.0可能会导致bean的一些问题。我建议您查看此主题以清楚地了解更多此问题::: Spring annotations @ModelAttribute and @Valid

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-16
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 1970-01-01
      • 2013-06-18
      相关资源
      最近更新 更多