Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring mvc interceptor addObject

I have an interceptor which extends the HandlerInterceptorAdapter.

When I add an object to my ModelAndView it also gets added to my url as a path variable but I don't want that.

@Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    if (null == modelAndView) {
      return;
    }

    log.info("Language in postHandle: {}", LocaleContextHolder.getLocale());
    modelAndView.addObject("selectedLocale", LocaleContextHolder.getLocale());
}

When I add something to my ModelAndView in the controller itself, it doesn't appear in the url.

like image 363
wvp Avatar asked Mar 20 '12 11:03

wvp


2 Answers

My suspicion is that the controller has returned a redirect view. When you add attributes to the model used by RedirectView, Spring will tack the attributes on to the URL.

Try looking inside the ModelAndView object to see if the view is a RedirectView, and if so, then don't add the locale attribute.

like image 122
skaffman Avatar answered Nov 30 '22 23:11

skaffman


Try this

import static org.springframework.web.servlet.view.UrlBasedViewResolver.REDIRECT_URL_PREFIX; 

private boolean isRedirectView(ModelAndView mv) {

    String viewName = mv.getViewName();
    if (viewName.startsWith(REDIRECT_URL_PREFIX)) {
        return true;
    }

    View view = mv.getView();
    return (view != null && view instanceof SmartView
            && ((SmartView) view).isRedirectView());
}
like image 40
karpaczio Avatar answered Nov 30 '22 23:11

karpaczio