Spring3-Interceptor
Spring 3 – Interceptor to push Attributes in the Model
When you have a lot of Controllers, you’ll come to the need of a general point to push attributes like locale, login-data, user information to your Model.
There are other ways to do this, but i’ll show the Spring way.
First of all you need this entry in your app-config.xml
1 2 3 | <mvc:interceptors> <bean class="net.mycityscout.www.controller.AddGeneralModelInterceptor"/> </mvc:interceptors> |
AddGeneralModelInterceptor is our custom interceptor class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | public class AddGeneralModelInterceptor implements HandlerInterceptor { protected UserDetailImpl getUser() { Authentication auth = SecurityContextHolder.getContext() .getAuthentication(); if (auth != null && auth.getPrincipal() instanceof UserDetailImpl) { return (UserDetailImpl) auth.getPrincipal(); } else { return null; } } public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { if (modelAndView != null && getUser() != null) { modelAndView.addObject("loggedUser", getUser()); } } } |
That’s it.Now you can put your general attributes in the model on every Request. Spring will execute your interceptor before every Controller-instance.
Posted October 19th, 2010 in General.