我是Tomcat和Spring Web的新手。我試圖通過遵循this tutorial來使用Spring的表單驗證功能。除了一件事情之外,一切似乎都能順利運行......我的表單沒有進行任何驗證,當我發送表單時,無論提供哪些數據,我都可以進入成功頁面。表單輸入約束沒有被強制執行?
我是否正確使用約束條件?我想強制用戶填寫他們的名字,並且名字至少有兩個字符長。
package net.devmanuals.form;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
public class RegistrationForm {
@NotEmpty(message = "You surely have a name, don't you?")
@Size(min = 2, message = "I'm pretty sure that your name consists of more than one letter.")
private String firstName;
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return this.firstName;
}
}
形態代碼:
<form:form method="post" commandName="regform">
<p><form:input path="firstName" /> <form:errors path="firstName" /></p>
<p><input type="submit" /></p>
</form:form>
控制器:
@Controller
@RequestMapping("/register")
public class RegistrationController {
@RequestMapping(method = RequestMethod.GET)
public String showRegForm(Map model) {
RegistrationForm regForm = new RegistrationForm();
model.put("regform", regForm);
return "regform";
}
@RequestMapping(method = RequestMethod.POST)
public String validateForm(@Valid RegistrationForm regForm, BindingResult result, Map model) {
if (result.hasErrors()) {
return "regform";
}
model.put("regform", regForm);
return "regsuccess";
}
}
我是否施加的約束不正確?
你的配置中是否有' '? –
skaffman
2011-05-04 19:36:52
哎呀。我嘗試將它添加到我的'Dispatcher-servlet.xml'中,但部署後出現此錯誤:*未綁定元素「mvc:annotation-driven」的前綴「mvc」。* – Pieter 2011-05-04 19:56:11
在您的配置中爲mvc添加命名空間,即xmlns:mvc =「http://www.springframework.org/schema/mvc」..... – 2011-05-04 23:50:21