我成功地开始了一个新的roo项目,但是现在我在验证登录页面时遇到了问题。在将控制传递给我的控制器之前,似乎验证器正在窒息。我从未有机会检查BindingResult。我在这里和网上检查过几个类似的问题,我的代码似乎与他们正在做的事情一致。
首先提交表单时收到的错误(如果我通过验证,则不会收到错误消息)。在这种情况下,我没有达到密码的最小长度:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'loginUser' on field 'password': rejected value [b]; codes [Size.loginUser.password,Size.password,Size.java.lang.String,Size]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [loginUser.password,password]; arguments []; default message [password],50,5]; default message [Password must be between 1 and 50 characters long]
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
我的实体验证设置如下:
public class LoginUser {
@NotNull
@NotEmpty
private String username;
@NotNull
@NotEmpty(message = "Password must not be blank.")
@Size(min = 5, max = 50, message = "Password must be between 1 "
+ " and 50 characters long")
private String password;
}
这是我的标记:
<form:form method="post" commandName="command">
<form:label path="username">Username: </form:label>
<form:input path="username"/>
<form:errors path="username"/>
<form:label path="password">Password: </form:label>
<form:password path="password"/>
<form:errors path="password"/>
<input type="submit"/>
</form:form>
控制器:
@ModelAttribute("command")
public LoginUser fbo(){
LoginUser u = new LoginUser();
u.setUserType(UserType.USER);
return u;
}
@RequestMapping(value="/login.htm", method=RequestMethod.POST)
public String doLogin(@Valid LoginUser command,
HttpServletRequest request, BindingResult result
){
if(result.hasErrors()){
return "login";
}
}
以防万一,webmvc-config.xml中生成的xml:
<!-- The controllers are autodetected POJOs labeled with the @Controller annotation. -->
<context:component-scan base-package="com.tcg.myproject" use-default-filters="false">
<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
<!-- Turns on support for mapping requests to Spring MVC @Controller methods
Also registers default Formatters and Validators for use across all @Controllers -->
<mvc:annotation-driven conversion-service="applicationConversionService"/>
我已经把头发拉了几个小时,我无法弄清楚它可能是什么。谢谢你的阅读!
答案 0 :(得分:13)
在控制器处理程序方法中,尝试移动BindingResult参数,使其紧跟在命令参数之后。 Spring查找命令对象参数和BindingResult参数,以便在处理程序方法签名中配对。