Question

What is the most elegant/effective way, how to handle Model between Controllers in Spring MVC 3.2. For redirecting to another Controller I use forward method, so there is not necessary new instance of request and Model data should be accessible (if I am not wrong). Is there any way how to catch Model, which was added in first Controller?

(I know about RedirectAttributes, but may be is better/easier method)

Example:

@Controller
public class WebpageController{

        @RequestMapping( value = { "/{code}" } )
        public String handleFirstLevel(@PathVariable String code, ModelMap modelMap) throws PageNotFoundEception{
            final Webpage webpage = getWebpage(code);
            modelMap.put(WEBPAGE_MODEL_KEY, prepareModel(webpage));

            return "forward:some-url";
        }

        private Map<String, Object> prepareModel(Webpage webpage){
            Map<String, Object> model = new HashMap<String, Object>();
            model.put("webpage", webpage);
            return model;
        }

        // some other code
    }

    @Controller
    public class SpecialWebpageController{

        @RequestMapping( value = { "/some-url" } )
        public String handleFirstLevel(@PathVariable String code, ModelMap modelMap) throws PageNotFoundEception{
            // need access to previously appended model to add some other data
            return "specialViewName";
        }

    }

Thank you

Was it helpful?

Solution

When you have a handler method that simply returns a String, that String is considered a view name. With a prefix of forward, Spring will get a RequestDispatcher for the specified path and forward to it. Part of that process will include taking the Model from the ModelAndView created for that request handling cycle and putting all its attributes into the HttpServletRequest attributes.

The Servlet container will take the RequestDispatcher#forward(..) and again use your DispatcherServlet to handle it. Your DispatcherServlet will create a new ModelAndView with a new Model for this handling cycle. Therefore this Model doesn't contain any of the attributes from before but the HttpServletRequest attributes do.

In your case, this

modelMap.put(WEBPAGE_MODEL_KEY, prepareModel(webpage));

will end up being in

HttpServletRequest request = ...;
request.getAttribute(WEBPAGE_MODEL_KEY);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top