本文介绍了弹簧错误中Validator的目标无效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,每当我尝试在春天调用验证器时,都会收到以下错误消息
Hi all I am getting the following error whenever I am trying to invoke validator in my spring
Servlet.service() for servlet spring threw exception: java.lang.IllegalStateException: Invalid target for Validator
请查看一下并帮助我解决此错误,以前我使用登录页面的验证,它可以正常工作,但现在不起作用.
Please have a look and help me out in this error, previously I user the validation for login page and it is working fine but now its not working.
这是我的代码段.
控制器
@Controller
public class NewUserRegistration
{
@Autowired
private UserService userService;
@Autowired
private NewUserValidator newUserValidator;
@InitBinder
public void initBinder(WebDataBinder binder)
{
binder.setValidator(newUserValidator);
}
@RequestMapping(value="/newUserAdd", method=RequestMethod.POST)
public String addUser(@ModelAttribute("user")@Valid User user,BindingResult result, Model model)
{
return "NewUser";
}
}
验证者
@Component
public class NewUserValidator implements Validator
{
@Override
public boolean supports(Class<?> classz)
{
return NewUserRegistration.class.equals(classz);
}
@Override
public void validate(Object obj, Errors error)
{
//Validation login for fields
}
}
JSP页面
<form:form action="newUserAdd" method="POST" modelAttribute="user">
<center>
<table>
<tr><td>User Id:</td><td><input name="userId" type="text" /></td><td><font color="red"><c:out value="${userIdError}" /></font> </td></tr>
<tr><td>Password:</td><td><input name="userPassword" type="password"/></td><td><font color="red"><c:out value="${userPasswordError}" /></font></td></tr>
<tr><td>Confirm Password:</td><td><input name="userConfirmPassword" type="password"/></td><td><font color="red"><c:out value="${userPasswordError}" /></font></td></tr>
<tr><td>Name:</td><td><input name="userName" type="text"/></td><td><font color="red"><c:out value="${userPasswordError}" /></font></td></tr>
<tr><td></td><td><input type="submit" value="Create"/></td></tr>
</table>
</center>
</form:form>
推荐答案
问题实际上出在Validator类中,您正在使用NewUserRegistration的对象,这是错误的,因为您要验证User的对象而不是NewUserRegistration的对象.
The problem is actually in Validator class you are using NewUserRegistration's object which is wrong because you want to validate your User's object not your NewUserRegistration's object.
@Override
public boolean supports(Class<?> classz)
{
return NewUserRegistration.class.equals(classz);
}
应该是
@Override
public boolean supports(Class<?> classz)
{
return User.class.equals(classz);
}
这篇关于弹簧错误中Validator的目标无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!