Spring mvc interceptor addObject

I have an interceptor that extends HandlerInterceptorAdapter .

When I add an object to my ModelAndView , it is also added to my URL as a path variable, but I do not want this.

 @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 does not appear in the url.

+6
source share
4 answers

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

Try searching for a ModelAndView to see if the view is a RedirectView , and if so, do not add the locale attribute.

+11
source

try it

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

I edited the code and added the check if it is RedirectView. If not, I will add 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); } } 
0
source

Instead, I used setAttribute for the request to get around this problem.

 request.setAttribute("jsFiles", children); 
0
source

Source: https://habr.com/ru/post/911189/


All Articles