Reputation: 197
I am writing a custom validator. It should just compare 2 field values in the form and reject if they are same. It successfully rejects, but I can not send my error message to the view.
This is my custom validator class:
public class CheckSameNameValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
// TODO Auto-generated method stub
return FormModel.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
FormModel model = (FormModel) target;
if (model.getPerson1().getName().equals(model.getPerson2().getName())) {
System.out.println("error occurred");
errors.reject("person can not relate to himself!");
}
}
}
This is the FormModel class used in validation:
public class FormModel {
private Person person1;
private Person person2;
public Person getPerson1() {
return person1;
}
public void setPerson1(Person person1) {
this.person1 = person1;
}
public Person getPerson2() {
return person2;
}
public void setPerson2(Person person2) {
this.person2 = person2;
}
}
This is the controller method used:
@RequestMapping(value = "/setRelative", method = RequestMethod.POST)
public ModelAndView setRelative(@Valid @ModelAttribute("people") FormModel people, BindingResult bindingResult,
HttpServletRequest request) {
logger.info("set relative controller");
CheckSameNameValidator validator = new CheckSameNameValidator();
validator.validate(people, bindingResult);
if (bindingResult.hasErrors()) {
ModelAndView model = new ModelAndView();
model.setViewName("index");
model.addObject("people", people);
return model;
} else {
}
}
And this is the form in jsp:
<f:form class="form-inline" action="setRelative"
modelAttribute="people">
<label>Person:</label>
<f:select cssStyle="width:150px" path="person1.name" items="${nameList}"
multiple="false">
</f:select>
<f:errors path="person1.name" class="alert alert-danger"></f:errors>
<f:label path="person2.name">Relative:</f:label>
<f:select cssStyle="width:150px" path="person2.name" items="${nameList}"
multiple="false">
</f:select>
<f:errors path="person2.name" class="alert alert-danger"></f:errors>
<label>Person's Relation to Relative:</label>
<f:select cssStyle="width:150px" path="person2.relations"
items="${relationList}" multiple="false">
</f:select>
<button class="btn btn-primary" type="submit">Set
relative</button>
</f:form>
I expect the error message to be printed to the view, if error occurred. How to achieve it?
Upvotes: 0
Views: 1119
Reputation: 363
You can to add this message in the controller model.addObject("message", "your error message");
and then, put in you jsp ${message}
where you want to show it.
It's another option to print the message in the jsp.I hope to help you.
Upvotes: 1