1

I used @Valid in Spring mvc. It seems that it is doing nothing. Here is my programe

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>

Here is the Controller

 @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 Here i have used @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>
M. Deinum
  • 115,695
  • 22
  • 220
  • 224
Shirish Maharjan
  • 502
  • 3
  • 17

2 Answers2

0

Look for a Hibernate version below 6 and try it again, using @ModelAttribute is that you can map a form's inputs to a bean and the 6.0 the api 2.0 may cause some issues about Bean. I recommend you see this topic to clearly more this questions::: Spring annotations @ModelAttribute and @Valid

Community
  • 1
  • 1
mmelotti
  • 336
  • 3
  • 11
0

I added the usual stuff you have done (libraries in pom, @Valid on RequestBody etc)

What the Spring docs (and many blogs) leave it as subtle is that Spring looks for an exit point to throw the error but if that exit doesn't exist, it will reply with 404. After reading a lot especially this blog, adding this class got Spring to recognize @Valid and find an exit point to throw the error

    @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();
    }

    
}
veritas
  • 378
  • 1
  • 6
  • 16