1
我在Spring mvc中使用了@Valid。它似乎沒有做任何事情。 這裏是我的PROGRAME@Valid不能在Spring中工作java
爲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文件夾下。 –
改用hibernate validator 5.4.1最終版本。版本6用於bean驗證api 2.0 – mhshimul