One object, multiple views

992 views Asked by At

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;
}
2

There are 2 answers

7
Piotr Podraza On BEST ANSWER

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

0
petr.kuznetsov On

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