gene b.
gene b.

Reputation: 11984

BindingResult Not Working in Display Method (Spring MVC)

I have a Display page handler which shows the page. This method is not for form submission, it's just to display the page.

My issue is that, even on Display, there are some global error messages that can occur. Since the only way to show errors is to add them to a BindingResult, I added a Model/BindingResult param pair to my Display method:

public ModelAndView display(final HttpServletRequest request, 
                            @ModelAttribute("model") Model model, 
                            BindingResult bindingResult) {

Then, let's say I add an error to my BindingResult,

bindingResult.addError(new ObjectError("", "message");  

But this doesn't work - the shown JSP doesn't have my message. This approach works on Save, but it doesn't on Display, maybe because I'm not submitting any form and that's why I can't have a BindingResult.

How would I display a general error in a method which doesn't submit a form? Why doesn't BindingResult work in this Display method?

Upvotes: 0

Views: 1018

Answers (2)

ryanp
ryanp

Reputation: 5127

As you've noticed, unfortunately BindingResult parameters only get populated by the framework during binding - i.e. at the point that your command object gets populated with the request parameters.

It's a bit of a kludge, but you can simulate the framework adding a BindingResult parameter to the model by adding the parameter yourself explicitly using the expected key:

public ModelAndView display(MyModel model, BindingResult errors) {
    errors.addError(new ObjectError("", "message"));

    return new ModelAndView("myViewName", new ModelMap()
        .addAttribute("myModelKey", model)
        .addAttribute(BindingResult.MODEL_KEY_PREFIX + "myModelKey", errors));
}

Spring's <form:/> taglib will now treat errors you've added just like it would if they'd occurred on binding.

Note that now the parameters in your method signature will never be populated by the framework (as this is a display-only controller action) so it might make more sense to just define them inside of your method.

Upvotes: 1

Vignesh
Vignesh

Reputation: 531

You may need to use JavaScript for showing errors

Upvotes: 0

Related Questions