How to Disable Spring's "typeMismatch" Exception? - Spring MVC

Red*_*ama 3 java spring spring-mvc

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;
}
Run Code Online (Sandbox Code Playgroud)

and a Controller:

@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";
}
Run Code Online (Sandbox Code Playgroud)

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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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?

Sla*_*hin 5

简短的回答:将支持对象的成员声明为String.

答案很长:typeMismatch在绑定期间和验证之前会发生错误。所有用户的数据都表示为String值(因为这是ServletRequest.getParameter()返回的内容)并且 Spring 尝试将String值转换为支持对象中的字段类型。在您的示例中,Spring 将尝试将参数值转换aNumberint. 当您将字段留空时,Spring 会尝试将空字符串转换为int,当然它会抱怨类型不匹配。

(这个答案仍然不完整,因为 Spring 也尝试使用不同的转换器,但我相信您已经了解了。)