Search code examples
springmodel-view-controllermodelattributecontroller-advice

spring mvc: applying @ModelAttribute on non-@Controller endpoints


I've read this suggestion on using @ModelAttribute for injecting parameters to the model globally. Is my understading correct, that such an approach will not cover views rendered by, e.g. <mvc:view-controller>, or a form-login custom login page?

If so, is there a way to extend such a mechanism to include all views?

Thanks


Solution

  • Ended-up using an Interceptor, as laid-out in this reply. Registered interceptor to intercept all non-resource endpoints (using mvc:exclude-mapping).

    public class HandlerInterceptor extends HandlerInterceptorAdapter {
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView modelAndView) throws Exception {
        if (modelAndView == null)
            return;
        modelAndView.addObject("foo", "bar");
    }