0

I have multiple views that need one and the same object. Does spring support something for it?

Example:

private LanguageDao dao;

At this point, in every method i need to pass the variable to my view. Every single time...

@GetMapping("/cart")
public ModelAndView showCart() {
    ModelAndView modelAndView = new ModelAndView();

    modelAndView.setViewName("show_cart");
    modelAndView.addObject("dao", dao); // Get rid of this...

    return modelAndView;
}
yooouuri
  • 2,578
  • 10
  • 32
  • 54

2 Answers2

1

You can create an interceptor using HandlerInterceptorAdapter and override postHandle method in which you'll add needed object to the model. Example below.

@Component
public class ExampleInterceptor extends HandlerInterceptorAdapter {

    @Override
    public void postHandle(
            HttpServletRequest request, 
            HttpServletResponse response, 
            Object handler, 
            ModelAndView modelAndView) throws Exception {

        modelAndView.addObject("object", new Object());
    }

}

Then you need to add it into registry and specify path pattern(s). If you use WebMvcConfigurerAdapter you can do it by overriding addInterceptors method.

@Bean
public ExampleInterceptor exampleInterceptor() {
   return new ExampleInterceptor();
}

@Override
public void addInterceptors(InterceptorRegistry registry) {                
   registry.addInterceptor(exampleInterceptor()).addPathPatterns("/*");
}

More on the subject you can find here: http://www.journaldev.com/2676/spring-mvc-interceptor-example-handlerinterceptor-handlerinterceptoradapter

Piotr Podraza
  • 1,941
  • 1
  • 15
  • 26
  • Sometimes, ```modelAndView``` in ```postHandle``` is null. In the both methods i return an ```ModelAndView```... – yooouuri Dec 21 '16 at 16:32
  • Are you sure about interceptor's mapping? If your controller method is mapped, for example, to `/test` and the same with your interceptor path pattern, there shouldn't be a problem. – Piotr Podraza Dec 21 '16 at 16:45
  • ```DefaultRequestToViewNameTranslator.getViewName(request)``` returns 'error' and modelAndView is null... – yooouuri Dec 21 '16 at 16:48
  • ```@GetMapping("/product/{id}")``` is mapped to ```"/*"``` ?? – yooouuri Dec 21 '16 at 16:49
  • When i do: ```.addPathPatterns("/*", "/*/*");``` it works! – yooouuri Dec 21 '16 at 16:52
  • `/*` was just an example to show you how to set pat patterns for your interceptor. If you want to use the interceptor for every request you don't have to specify path patterns - `registry.addInterceptor(exampleInterceptor())` will be enough. – Piotr Podraza Dec 21 '16 at 16:58
  • Thanks for helping. – yooouuri Dec 21 '16 at 17:10
1

You could use @ModelAttribute on target controller

private LanguageDao dao;

@ModelAttribute("dao")
public LanguageDao geDao(){
    return dao;
}

See http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ModelAttribute.html