wvp
wvp

Reputation: 1174

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.

Upvotes: 7

Views: 5072

Answers (4)

karpaczio
karpaczio

Reputation: 159

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());
}

Upvotes: 8

Bob Spryn
Bob Spryn

Reputation: 17812

I used setAttribute on the request instead to get around this problem

request.setAttribute("jsFiles", children);

Upvotes: 0

wvp
wvp

Reputation: 1174

I have edited the code and added a check if the is a RedirectView. If not than I will add the additional model objects.

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

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

    if(!(modelAndView.getView() instanceof RedirectView)) {
      addAdditionalModelObjects(request, modelAndView);
    }
  }

Upvotes: 1

skaffman
skaffman

Reputation: 403501

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.

Upvotes: 12

Related Questions