转自:https://www.cnblogs.com/wenhulu/p/5555457.html
当使用Spring MVC @Valid对输入框进行验证的时候,可能会遇到以下的异常:
Neither BindingResult nor plain target object for bean name ‘mybean’ available as request attribute
先看下controller:
@RequestMapping(value="/{userId}/updateUser",method=RequestMethod.POST) public String updateUser(@PathVariable int userId,@Valid SysUser user,BindingResult br) { if(br.hasErrors()) { return "updateUser"; } userServiceInter.update(user); return "redirect:/user/users"; }
上面代码对user的输入进行验证,报以上错误,为了解决这个问题,我们需要在@Valid之后添加一个注解@ModelAttribute("user") SysUser user,然后在jsp页面的添加
<form modelAttribute="user"></form>,解决问题。
contriller:
@RequestMapping(value="/{userId}/updateUser",method=RequestMethod.POST) public String updateUser(@PathVariable int userId,@Valid @ModelAttribute("user")SysUser user,BindingResult br) { if(br.hasErrors()) { return "updateUser"; } userServiceInter.update(user); return "redirect:/user/users"; }
update.jsp:
<sf:form method="post" modelAttribute="user"> <tr><td>userName:</td><td><sf:input path="userName"/><sf:errors path="userName"/></td></tr> <tr><td>userPwd:</td><td><sf:input path="userPwd"/><sf:errors path="userPwd"/></td></tr> <tr><td>email:</td><td><sf:input path="email"/><sf:errors path="email"/></td></tr> <tr><td>userStatus:</td><td><sf:input path="userStatus"/><sf:errors path="userStatus"/></td></tr> <tr><td>accountNonLocked:</td><td><sf:input path="accountNonLocked"/><sf:errors path="accountNonLocked"/></td></tr> <tr><td></td><td><input type="submit" value="update" onclick="javascript:return window.confirm('Are you sure to update')"/></td></tr> </sf:form>
另一补充一下:
org.springframework.validation.annotation是放在spring-context-4.0.0RELEASE.jar下。
转自:http://www.cnblogs.com/wenhulu/p/5555457.html