Search code examples
javaspringjspmodel-view-controllerjsp-fragments

What is the best practice for layout of jsp page?


Simple example: i have a page with header, footer and left menu. This modules viewing always. In header i am use dynamic information for count of users. I am create jspf files for header, for footer and left menu and include it to main page. I have Spring controllers and always need include to model variable for calculation of users. Maybe you know how it's do more grateful?


Solution

  • If you need to include a model among multiple controllers, then use a @ControllerAdvice with a @ModelAttribute method

    @ControllerAdvice
    public class GlobalDataAdvice {
    
      @Autowired
      private FooService fooService;
    
      @ModelAttribute("foo")
      Foo getFoo(){
            return fooService.find(...);
      }  
    }
    

    I like SiteMesh for my layouts. It's pretty easy to use. http://wiki.sitemesh.org/wiki/display/sitemesh/Start+Using+SiteMesh+in+10+Minutes

    You can also use JSP Tag Files. JSP tricks to make templating easier?