我的表单验证存在一些问题。
控制器:
@RequestMapping(value = REGISTER_URL, method = RequestMethod.POST)
public String registerPost(@Valid RegisterForm registerForm,
BindingResult result) {
if (result.hasErrors()) {
return REGISTER_VIEW;
}
System.out.println(registerForm.getPassword());
return LOGIN_VIEW;
}
查看:
<form:form action="register" commandName="registerForm" method="post">
<table>
<tr>
<td>Username:</td>
<td><form:input path='username' /></td>
<td><form:errors path="username"/></td>
</tr>
<tr>
<td>Password:</td>
<td><form:password path='password'/></td>
<td><form:errors path="password"/></td>
</tr>
<tr>
<td>Repeat password:</td>
<td><form:password path='repeatedPassword'/></td>
<td><form:errors path="repeatedPassword"/></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit"> <input name="reset" type="reset"></td>
</tr>
</table>
</form:form>
形式:
public class RegisterForm {
@Size(min = 3, max = 15)
private String username;
@Size(min = 5)
private String password;
@Size(min = 5)
private String repeatedPassword;
// getters and setters omitted
}
当我输入空值(用户名,密码和repeatedPassword)时,没有错误发生(我已使用调试器检查过它)。因此看起来没有执行验证。视图中的绑定值是可以的(使用调试器检查)任何想法可能出错?
答案 0 :(得分:1)
将以下内容添加到您的上下文中:
<mvc:annotation-driven />
<context:component-scan base-package="xxx.xxx.xxx" />
在指南中,他们使用"@SpringBootApplication"
http://spring.io/guides/gs/validating-form-input/
@SpringBootApplication
注释相当于使用@Configuration
,@EnableAutoConfiguration
和@ComponentScan
及其默认属性:
http://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-using-springbootapplication-annotation.html