Issue
I am trying to validate some information, so I added a validator and used @Valid in the parameter of the post method:
@Controller
@RequestMapping("/user.htm")
public class UserController {
@Autowired
private IUserService userService;
@RequestMapping(method = RequestMethod.GET)
public String userInfo(Model model) {
....
return "user";
}
@RequestMapping(method = RequestMethod.POST)
public String userInfoResult(@Valid @ModelAttribute UserForm userForm, BindingResult result, Model model ) {
UserInfo stat = userService.getStatitisque(userForm.getSearchCritera());
userForm.setListeExpediteur(listeExpediteur);
userForm.setUserInfo(stat);
model.addAttribute("userForm", userForm);
}
}
public class UserFormValidator implements Validator {
@Override
public boolean supports(Class<?> type) {
return UserForm.class.equals(type);
}
@Override
public void validate(Object o, Errors errors) {
UserForm userForm = (User) o;
...
}
}
When I debug, I never go in the UserFormValidator class.
Do I need to add something in these files?
web.xml
applicationContext.xml
dispatcher-servlet.xml
Solution
You need to add the validator in an @InitBinder
method:
@InitBinder(value="YourFormObjectName")
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new FooValidator());
}
or globally via XML:
<mvc:annotation-driven validator="globalValidator"/>
Reference:
Answered By - Sean Patrick Floyd
Answer Checked By - Pedro (JavaFixing Volunteer)