我正在编写一个自定义验证器。它应该只比较表格中的两个字段值,如果相同则拒绝。它成功拒绝,但是我无法将错误消息发送到视图。
这是我的自定义验证器类:
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!");
}
}
}
这是验证中使用的FormModel类:
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;
}
}
这是使用的控制器方法:
@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 {
}
}
这是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>
如果发生错误,我希望将错误消息打印到视图中。如何实现?
答案 0 :(得分:1)
您可以在控制器model.addObject("message", "your error message");
中添加此消息
然后,将jsp ${message}
放在您要显示的位置。
这是在jsp中打印消息的另一种方法。希望对您有所帮助。