spring:在每个控制器模型中添加会话属性

时间:2015-07-19 11:56:59

标签: java spring spring-boot velocity

我想在模型中为每个控制器添加常用的属性。

1 个答案:

答案 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"));
    }
}

}