我想在模型中为每个控制器添加常用的属性。
答案 0 :(得分:1)
HandlerInterceptorAdapter可用于拦截请求。例如,您可以覆盖preHandle以验证会话,并将用户添加到postHandle中的模型。
public class SessionValidator extends HandlerInterceptorAdapter{
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
if (session == null || session.getAttribute("user") == null) {
return false;
}
return super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
HttpSession session = request.getSession();
if (modelAndView != null) {
modelAndView.getModelMap().addAttribute("user", session.getAttribute("user"));
}
}
}