Search code examples
springspring-mvcsitemesh

Dynamic content in all page in Spring MVC


I am developing my site in Spring MVC with Sitemesh. Here is example

Dynamic content is changed oon every page, Menu and Footer I can include in template definition. But there comes a problem. On every site below the dynamic content there should be a news list with loaded some news from my DB. I created my @Controller and it loads 5 latest news, but how to add this on my template? What request mapping should implement my news controller?


Solution

  • I don't kwow how Sitemesh works, but I solved problems like that by using interceptor:

    create a class that extends : HandlerInterceptorAdapter

    Override the method postHandle and populate the modelAndView Object like this :

    modelAndView.addObject("newslist",myNewsList);
    

    So you will have a variable $newslist injected into all your views.

    Don't forget to declare bean in your mvc-congig.xml :

    <bean id="newsListInterceptor" class="mypackage.NewsListInterceptor"/>
    

    As the interceptor is executed for each request I also use ehcache to store the result and avoid during a select in database for each call.