由於某種原因,它不起作用。我搜索並嘗試了網絡上找到的所有解決方案。沒有骰子。看起來我錯過了一些東西。@Valid不觸發 - Spring MVC 3.2
我梁:
@Entity
@Table(name="employees")
public class Person {
private Integer person_id;
private String name;
private String name2;
private String email;
private double phone;
private String desc;
@Id
@Max(value=500)
@Column (name="id")
public Integer getPerson_id() {
return person_id;
}
public void setPerson_id(Integer person_id) {
this.person_id = person_id;
}
@NotNull
@NotEmpty
@Column (name="fn")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name="ln")
public String getName2() {
return name2;
}
public void setName2(String name2) {
this.name2 = name2;
}
@Email
@Column (name="em", unique = true)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(name="phone")
public double getPhone() {
return phone;
}
public void setPhone(double phone) {
this.phone = phone;
}
@Column (name="de")
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String toString() {
return getPerson_id() + " - " + getName() + " - " + getName2() + " - " + getEmail();
}
}
控制器的方法來處理POST:
@RequestMapping(value="/register", method = RequestMethod.POST, headers="Accept=*/*")
public String registerUer(@javax.validation.Valid Person registerForm, BindingResult br){
System.out.println("Erros?" + br.hasErrors());
if (br.hasErrors()) {
System.out.println(br.getAllErrors());
}
System.out.println(registerForm);
return "thankyou";
}
回到Home.jsp
<form:form action="register.htm" commandName="registerForm" method="post">
Name1: <form:input path="name"/><br />
Name2: <form:input path="name2"/><br />
Email: <form:input path="email"/><br />
Desc: <form:input path="desc" /><br />
Phone: <form:input path="phone" /><br />
<input type="submit" />
</form:form>
應用程序上下文XML文件:
<mvc:annotation-driven />
<context:component-scan base-package="com.springmvcsample"/>
<context:annotation-config/>
<import resource="hibernate_config.xml"/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<!-- Turn off working out content type based on URL file extension, should fall back
to looking at the Accept headers -->
<property name="favorPathExtension" value="false" />
</bean>
<bean class="org.springframework.context.support.ResourceBundleMessageSource"
id="messageSource">
<property name="basename" value="messages" />
</bean>
我總是得到hasErrors()
return false 我在我的classspath中有hibernate validator(GA jar)文件。我看到這個加載:
INFO [Version] Hibernate Validator 4.2.0.Final
我錯過了什麼嗎?
你可以嘗試使用setter上的驗證註釋嗎? – 2013-04-29 04:51:56
反正會試試。但是在領域vs設置者上有什麼不同? – 2013-04-29 14:59:28
你對你的獲得者有註釋.. – 2013-04-29 15:12:25