Add attributes to the model of all controllers in Spring 3 Add attributes to the model of all controllers in Spring 3 java java

Add attributes to the model of all controllers in Spring 3


You could write an org.springframework.web.servlet.HandlerInterceptor. (or its convenience subclass HandlerInterceptorAdapter)

@See: Spring Reference chapter:15.4.1 Intercepting requests - the HandlerInterceptor interface

It has the method:

void postHandle(HttpServletRequest request,                HttpServletResponse response,                Object handler,                ModelAndView modelAndView) throws Exception;

This method is invoked after the controller is done and before the view is rendered. So you can use it, to add some properties to the ModelMap

An example:

/** * Add the current version under name {@link #VERSION_MODEL_ATTRIBUTE_NAME} * to each model.  * @author Ralph */public class VersionAddingHandlerInterceptor extends HandlerInterceptorAdapter {    /**     * The name under which the version is added to the model map.     */    public static final String VERSION_MODEL_ATTRIBUTE_NAME =                "VersionAddingHandlerInterceptor_version";    /**             *  it is my personal implmentation      *  I wanted to demonstrate something usefull     */    private VersionService versionService;    public VersionAddingHandlerInterceptor(final VersionService versionService) {        this.versionService = versionService;    }    @Override    public void postHandle(final HttpServletRequest request,            final HttpServletResponse response, final Object handler,            final ModelAndView modelAndView) throws Exception {        if (modelAndView != null) {            modelAndView.getModelMap().                  addAttribute(VERSION_MODEL_ATTRIBUTE_NAME,                               versionService.getVersion());        }    }}

webmvc-config.xml

<mvc:interceptors>    <bean class="demo.VersionAddingHandlerInterceptor" autowire="constructor" /></mvc:interceptors>


You can also use @ModelAttribute on methods e.g.

@ModelAttribute("version")public String getVersion() {   return versionService.getVersion();}

This will add it for all request mappings in a controller. If you put this in a super class then it could be available to all controllers that extend it.


You could use a Controller Class annotated with @ControllerAdvice

"@ControllerAdvice was introduced in 3.2 for @ExceptionHandler, @ModelAttribute, and @InitBinder methods shared across all or a subset of controllers."

for some info about it have a look at this part of the video recorded during SpringOne2GX 2014http://www.youtube.com/watch?v=yxKJsgNYDQI&t=6m33s