简体   繁体   中英

spring: add session attribute in every controller model

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

HandlerInterceptorAdapter can be used to intercept the request. For example, you can override preHandle to validate the session, and add the user to model in 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"));
    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM