0

I am writing a spring application and for every page I return the same view and populate it with content fragments. Does anyone know if and how to set this view name so that I do not have to set it with every controller.

@RequestMapping("/Login")
public ModelAndView login(ModelAndView modelAndView) {
    modelAndView.setViewName("default");
    modelAndView.addObject("view", "login");
    modelAndView.addObject("title", "Login");
    modelAndView.addObject("jsNeeded", true);
    return modelAndView;
}

This is an example of a controller. I would like to not have to repeat the

modelAndView.setViewName("default");
David Carek
  • 1,103
  • 1
  • 12
  • 26
  • 1
    Define injection here. Spring creates a new instance for each method call and is treating it as a model attribute. Basically this isn't the way to do things like that. The simplest solution is to create a factory which constructs a fresh `ModelAndView` with the defaults set, in the places you need it, call this factory. – M. Deinum May 15 '15 at 15:26
  • It is set up so that a ModelAndView object is injected into the method meaning it is passed in. I believe that if the object cannot be found spring essentially creates a new instance but I'm not sure if that's actually how it works. – David Carek May 15 '15 at 18:03
  • As mentioned nothing is actually injected, there is just a new instance of `ModelAndView` for each method invocation. You only save the line `ModelAndView modelAndView = new ModelAndView()`. `ModelAndView` isn't a supported method argument for request handling methods, so it is treated as any arbitrary object and a new instance is being created, this works by the grace of a default no-arg constructor (if that wouldn't have been there it would fail). – M. Deinum May 15 '15 at 18:19

0 Answers0