如果你想把一些数据放到每个页面上,使用拦截器很容易:
public class PagePopulationInterceptor extends HandlerInterceptorAdapter {
@Autowired
private UserService userService;
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if(modelAndView != null) {
User user = userService.findOne(request);
modelAndView.addObject("myUserProfile", user);
}
}
}
为了完成这项工作,还要在 webmvc-config.xml 中声明拦截器(webapp 的弹簧配置):
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.yourcompany.yourapp.util.PagePopulationInterceptor" />
</mvc:interceptor>
<!-- other interceptors (locale, theme and so on) -->
</mvc:interceptors>