【问题标题】:Not showing error message in form(jsp)未在表单中显示错误消息(jsp)
【发布时间】:2023-03-29 10:39:01
【问题描述】:

在我的表单(jsp 表单)中显示错误消息时遇到问题。 我创建了一个验证器,并希望在我的表单中查看错误(如果存在),但没有显示错误,这是什么问题?

部分表格

<form:form method="POST" action="/regStoreSuccessful" commandName="storeForm">
<table>
  <tr>
    <td><form:label path="name">Store name</form:label></td>
    <td><form:input path="name" /></td>
    <td><form:errors path="name" cssclass="error"/></td>
  </tr>

验证器

public class StoreValidator implements Validator {

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

@Override
public void validate(Object target, Errors errors) {
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.empty", "Name field is empty");
}

}

控制器

@Autowired
private StoreValidator storeValidator;

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(storeValidator);
}

//get method
@RequestMapping(value = "/regStore", method = RequestMethod.GET)
public ModelAndView addStore() throws SQLException {
    ModelAndView modelAndView = new ModelAndView("Store/regStore", "storeForm", new Store());
}

//post method
@RequestMapping(value = "/regStoreSuccessful", method = RequestMethod.POST)
public ModelAndView addStorePost(@Valid @ModelAttribute("storeForm") Store storeForm, BindingResult bindingResult, Principal principal) throws SQLException {
    ModelAndView modelAndView = new ModelAndView("redirect:body");

    if(bindingResult.hasErrors()) {
        modelAndView.addObject("errors", bindingResult.getAllErrors());
        return new ModelAndView("redirect:regStore");
    }

    storeService.addStore(storeForm);
    return modelAndView;
}

【问题讨论】:

    标签: spring forms jsp spring-mvc controller


    【解决方案1】:

    重定向后模型属性不可用,您应该使用RedirectAttributes redirectAttrs并将错误存储为flash属性,这样属性将在重定向后可用并在使用后立即删除,因此将您的方法更改为

    //post method
    @RequestMapping(value = "/regStoreSuccessful", method = RequestMethod.POST)
    public ModelAndView addStorePost(@Valid @ModelAttribute("storeForm") Store storeForm, BindingResult bindingResult, Principal principal, , RedirectAttributes redirectAttrs) throws SQLException {
        ModelAndView modelAndView = new ModelAndView("redirect:body");
    
        if(bindingResult.hasErrors()) {
            redirectAttrs.addFlashAttribute("errors", bindingResult.getAllErrors());
            return new ModelAndView("redirect:regStore");
        }
    
        storeService.addStore(storeForm);
        return modelAndView;
    }
    

    【讨论】:

    • 它有效,谢谢)。我有一个问题,如何在不重定向的情况下检查有效字段?
    • np,关于你的问题,你可以简单地返回 ModelAndView 持有包含表单的页面的视图,所以不使用前缀“redirect:”
    猜你喜欢
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    相关资源
    最近更新 更多