简体   繁体   中英

Validator in spring MVC without configuration message properties file

I have scenario like that.

1. I have jsp file, there are two field: toDate and fromDate:

<form:form id="testForm" modelAttribute="testForm" action="testAction">
    Name: <form:input path="name" />
    From date: <form:input path="fromDate" id="fromDate" />
    <form:errors path="fromDate" class="control-label" />
    To date: <form:input path="toDate" id="toDate" />
    <input id="mySubmitButton" type="submit" value="HELLO">
</form:form>

2. I have a Controller to handle request from my page as below:

@Autowired
   TestFormValidator validator;

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(validator);
}
@RequestMapping(value = "/testAction", method = RequestMethod.POST)
public String doSomeThing(ModelMap model,
        @ModelAttribute @Validated TestForm testForm, BindingResult result,
        RedirectAttributes redirectAttrs) {
    if (result != null && result.hasErrors()) {
        return "hello";
    }

3. I have Validator class to validate the TestForm:

@Component
public class TestFormValidator implements Validator {

@Override
public boolean supports(Class<?> clazz) {
    return TestForm.class.equals(clazz);
}

@Override
public void validate(Object arg0, Errors errors) {
    TestForm testForm = (TestForm) arg0;
    if (testForm.getFromDate() != null
            && testForm.getFromDate().after(testForm.toDate)) {
        errors.rejectValue("fromDate", "From date must not be after to date.");
    }

}

4. Yep, the following code is correct what I want. But I always meet the Exception:

org.springframework.context.NoSuchMessageException: No message found under code 'From date must not be after to date..testForm.fromDate' for locale...

5. I know that I miss declaration the bean: messageSource

My question:

I question whether are there any methods to return an error message without declaring message properties file?

Thanks in advance!!!

You can try Errors.rejectValue(String field, String errorCode, String defaultMessage) method. So your code must change as following.

errors.rejectValue("fromDate", "error.invalidFromDate", "From date must not be after to date.");

This should ideal use the defaultMessage in the scenario where it can't find the error code from message source.

You can also use this alternative.. The error message can be specified in the validation annotation, for example: @NotEmpty(message = "Please enter your email addresss.") private String email;

And for integer values @NotNull(message = "...".) Private Integer contactNumber

By doing this u can display error messages on your jsp page

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM