I have a single form for which there are three Pojo, because there are three separate tables one for each Pojo. Two fields in the form are pre populated. Now I want to validate the form using spring validator. I tried to use an abstract class with common fields of all three Pojo in it and each Pojo extending it but spring failed to create Object for abstract class and throws an exception. I prefer not to go with Interface since I have to initialize all the fields.
Below is the reference code.
Controller
@RequestMapping(value="/save",method=RequestMethod.POST)
public String saveData(@ModelAttribute("commonForm")@Valid Foo foo,FooBar fooBar,Test test,BindingResult result){
this.testValidator.validate(foo, result); //which Pojo to provide here
if(result.hasErrors()){
return "redirect:/regPage";
}else{
return "success";
}
}
Validator
public class TestValidator implements Validator{
@Override
public boolean supports(Class<?> clazz) {
return Foo.class.equals(clazz)|| FooBar.class.equals(clazz)|| Test.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
if(target instanceof Foo){
//validate Foo...
}else if(target instanceof FooBar){
//validate FooBar...
}else{
//validate Test...
}
}
}
Also the last Pojo i.e. test seems to be overlapping the other two with error message.
@Validannotation on each model in the wrapper model. similar to this:public class WrapperModel { @Valid private Foo foo; @Valid private Bar bar; // ...}