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.
Here is my code snippet .
Controller
@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";
}
}
Validator
@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 Page
<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>
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);
}
which should be
@Override
public boolean supports(Class<?> classz)
{
return User.class.equals(classz);
}
来源:https://stackoverflow.com/questions/21569939/invalid-target-for-validator-in-spring-error