badCoder
badCoder

Reputation: 121

Not showing error message in form(jsp)

I have a problem with showing error message in my form(jsp form). I create a validator, and want to see errors (if exists) in my form, but the errors not showing, what's problem?

Part of form

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

Validator

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

}

Controller

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

Upvotes: 1

Views: 1119

Answers (1)

Master Slave
Master Slave

Reputation: 28569

The model attributes won't be available after redirect, you should use RedirectAttributes redirectAttrs and store errors as flash attributes, that way attributes will be available after the redirect and removed immediately after used, so change your method to

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

Upvotes: 1

Related Questions