gpt4 book ai didi

java - 如何在 JSP View 中显示实现的自定义 validator 的错误消息?

转载 作者:行者123 更新时间:2023-12-02 10:05:36 25 4
gpt4 key购买 nike

我正在编写一个自定义 validator 。它应该只比较表单中的 2 个字段值,如果相同则拒绝。它成功拒绝,但我无法将错误消息发送到 View 。

这是我的自定义 validator 类:


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;
}
}

这是使用的 Controller 方法:

@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>

如果发生错误,我希望将错误消息打印到 View 中。如何实现?

最佳答案

您可以在 Controller 中添加此消息model.addObject("message", "your error message");然后,将 jsp ${message} 放入您想要显示的位置。

这是在jsp中打印消息的另一种选择。希望对您有所帮助。

关于java - 如何在 JSP View 中显示实现的自定义 validator 的错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55357211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com