无法使用spring显示错误<;形式:错误/>;
我无法在jsp页面上显示spring验证错误。这是我的密码。在jsp页面上,当我输入一个空名称时,控制器代码返回一个带有错误的ModelAndView,它只是不在jsp页面上显示它 任何帮助都将不胜感激。谢谢大家!无法使用spring显示错误<;形式:错误/>;,spring,spring-mvc,spring-annotations,Spring,Spring Mvc,Spring Annotations,我无法在jsp页面上显示spring验证错误。这是我的密码。在jsp页面上,当我输入一个空名称时,控制器代码返回一个带有错误的ModelAndView,它只是不在jsp页面上显示它 任何帮助都将不胜感激。谢谢大家! @RequestMapping(value = "/editTag.htm", method = RequestMethod.POST) public ModelAndView editTag(@ModelAttribute("Tag") Tag tag) { Binding
@RequestMapping(value = "/editTag.htm", method = RequestMethod.POST)
public ModelAndView editTag(@ModelAttribute("Tag") Tag tag) {
BindingResult result = new BeanPropertyBindingResult(tag, "tag");
ValidationUtils.rejectIfEmptyOrWhitespace(result, "name", "field.required", "Tag Name is required");
if (result.hasErrors()) {
return new ModelAndView("tag.edit").addObject("tag",tag).addObject("errors", result);
}
tagDao.merge(tag);
return new ModelAndView("redirect:/tags/listTags.htm");
}
<form:form commandName="tag">
<form:errors path="name"/><br />
<form:input path="name" size="30" />
...
</form:form>
@RequestMapping(value=“/editTag.htm”,method=RequestMethod.POST)
公共模型和视图编辑标记(@modeldattribute(“标记”)标记){
BindingResult=新BeanPropertyBindingResult(标记,“标记”);
ValidationUtils.rejectIfEmptyOrWhitespace(结果,“名称”、“字段.必填项”、“标记名为必填项”);
if(result.hasErrors()){
返回新的ModelAndView(“tag.edit”).addObject(“tag”,tag).addObject(“errors”,result);
}
tagDao.merge(tag);
返回新的ModelAndView(“重定向:/tags/listTags.htm”);
}
...
你能试试这个吗
public ModelAndView editTag(@ModelAttribute("Tag") Tag tag,BindingResult result) {
result = new BeanPropertyBindingResult(tag, "tag");
您正在构建一个新的BindingResult,而Spring已经提供了一个(并在后台使用)。只需在@modeldattribute注释参数之后将BindingResult添加到方法中,就可以实现这一点。然后,您可以从结果中获取模型,并使用该结果构建ModelAndView 还要注意ModelAttribute名称(当前标记)与表单中使用的名称(标记)不匹配。那两个应该匹配 像下面这样的方法应该可以奏效
@RequestMapping(value = "/editTag.htm", method = RequestMethod.POST)
public ModelAndView editTag(@ModelAttribute("tag") Tag tag, BindingResult result) {
ValidationUtils.rejectIfEmptyOrWhitespace(result, "name", "field.required", "Tag Name is required");
if (result.hasErrors()) {
return new ModelAndView("tag.edit", result.getModel());
}
tagDao.merge(tag);
return new ModelAndView("redirect:/tags/listTags.htm");
}
我认为,如果使用新实例覆盖参数,错误将不会显示在页面上。尝试按@SREEPRASAD answer执行,但省略实例化行。