SpringMVC returning validation errors with page redirect

2.5k Views Asked by At

I have a form that gets validated from the init binder.setValidatior(). However i have a controller method that returns a redirect once this is done the errors from the validation function do not bind to the errors element on the form. How can i get the errors to bind and still using the redirect.

The redirect is needed since the url has data that is required to reconstruct the page. The controller function is :

Controller

@RequestMapping(value = "monitoringList_save.htm", method = RequestMethod.POST)
    public ModelAndView handleSaveMonitoringRecord(@Valid @ModelAttribute Monitoring monitoring, BindingResult result,ModelMap m,
            HttpServletRequest request,SessionStatus status, HttpSession session,Model model) throws Exception {


        if(result.hasErrors()){

            return new ModelAndView(new RedirectView("monitoringList.htm"),"page",0); 
            //return new ModelAndView("monitoringList");
        }

        return new ModelAndView(new RedirectView("monitoringList.htm"),"page",0); 
    }

If i do return new ModelAndView("monitoringList"); then information in the page is lost.

2

There are 2 best solutions below

1
On
0
On

The solution was to add the old instance of the object back to the view, apparently its the object that binds to the validator results and not the view. The solution was to add:

 if(result.hasErrors()){
            model.addAttribute("monitoring", monitoring);
            return new ModelAndView(new RedirectView("monitoringList.htm"),"page",0); 
            //return new ModelAndView("monitoringList");
        }