Issue
Basically I want to be able stop Spring from checking if my fields contain bad data, and instead let me handle all the validation and exceptions manually.
Suppose I have a class:
public class MyClass {
int aNumber;
}
@Controller
public class MyController {
@Autowired
private MyValidator validator;
public MyClass() {}
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
@RequestMapping(value="/postsomething", method=RequestMethod.POST)
public ModelAndView onPost(@ModelAttribute("myObject") MyClass myObject, BindingResult result) {
validator.validate(myObject, result);
if (result.hasErrors()) {
return "postsomething";
}
return "redirect:success";
}
And finally a Validator:
public class MyValidator implements Validator {
@Override
public void validate(Object target, Errors errors) {
MyClass myObject = (MyClass) target;
if (someCondition) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "aNumber", "error.myclass.anumber.null");
}
}
}
The point is that I only want an error message to be displayed once from MY validator if someCondition
is true. But if I leave my port field in my form empty then it also displays Spring's error message for typeMismatch no matter what.
Can I disable the typeMismatch error, or should I go about all of this some other way?
Solution
The short answer: declare members of your backing object as String
.
The long answer: typeMismatch
error occurs during binding and before validation. All user's data represented as String
values (because this is what ServletRequest.getParameter() returns) and Spring tries to convert String
value to the type of the field in your backing object. In your example, Spring will try to convert value of parameter aNumber
to int
. When you left field empty, then Spring tried to convert empty string to the int
and of course it complains about mismatching types.
(This answer is still incomplete, because there is also different converters that Spring also tries to use, but I believe that you got the picture.)
Answered By - Slava Semushin
Answer Checked By - David Marino (JavaFixing Volunteer)