Spring MVC 登錄攔截器以及ThreadLocal

因爲項目用到自定義的登錄而且是前後端分離,接口都需要登錄後才能訪問,同時在做數據的增加、刪除、修改的時候需要傳進當前賬戶ID,因此自定義的一個公共方法和攔截器。代碼如下:

定義公共方法:

它的作用就是在各個地方都可以通過UserContext .getUserSession獲取當前session


public class UserContext implements Serializable {

    /** 
     * @Fields serialVersionUID : TODO(用一句話描述這個變量表示什麼) 
     */

    private static final long serialVersionUID = 1L;

    private static ThreadLocal<SecurityAccountLoginModel> loginEntityThreadLocal = new ThreadLocal<>();

    public static SecurityAccountLoginModel getUserSession() {
        return loginEntityThreadLocal.get();
    }

    public static void setUserSession(SecurityAccountLoginModel entity) {
        loginEntityThreadLocal.set(entity);
    }

    public static void removeUserSession() {
        loginEntityThreadLocal.remove();
    }
}

攔截器:


public class LoginInterceptor implements HandlerInterceptor {

    // 首先會執行的方法
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {

        boolean flag = false;
        // 從session中獲取對象
        SecurityAccountLoginModel model = (SecurityAccountLoginModel) request.getSession().getAttribute("user");

            if (model == null) {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                PrintWriter out = null;
                try {
                    JSONObject res = new JSONObject();
                res.put("code", "error");
                    res.put("message", "用戶未登錄!");
                    out = response.getWriter();
                    out.append(res.toString());
                    return false;
            } catch (Exception e) {
                response.sendError(500);
                return false;
            }
            finally {
                if (out != null) {
                    out.close();
                }
            }
        } else {
            UserContext.setUserSession(model);
            return true;
        }
    }

    // 返回ModelAndView之前執行的方法,面向切面編程中的體現,已經進入了controller
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object, ModelAndView modelAndView) throws Exception {

    }

    // 執行Handle完成之後執行的方法
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object, Exception exceptio) throws Exception {
        UserContext.removeUserSession();
    }

}

spring-mvc.xml配置:

<!-- 配置攔截器 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <!-- 攔截所有mvc控制器 -->
            <mvc:mapping path="/**"/>
            <!-- mvc:exclude-mapping是另外一種攔截,它可以在你後來的測試中對某個頁面進行不攔截,這樣就不用在
                LoginInterceptor的preHandler方法裏面獲取不攔截的請求uri地址了(優選) -->
            <mvc:exclude-mapping path="/oms/login.json" />
            <mvc:exclude-mapping path="/web/**" />
            <bean class="com.lemeida.retrace.commons.interceptor.LoginInterceptor"></bean>            
        </mvc:interceptor>
    </mvc:interceptors>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章