【发布时间】:2011-05-04 19:23:20
【问题描述】:
我是 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";
}
}
我是否错误地应用了约束?
【问题讨论】:
-
你的配置中有
<mvc:annotation-driven/>吗? -
哎呀。我尝试将其添加到我的
Dispatcher-servlet.xml,但部署后出现此错误:元素“mvc:annotation-driven”的前缀“mvc”未绑定。 -
在你的配置中为 mvc 添加命名空间,即 xmlns:mvc="springframework.org/schema/mvc" .....
标签: spring tomcat spring-mvc