1. 程式人生 > >利用Filter和ThreadLocal儲存和獲取常用物件

利用Filter和ThreadLocal儲存和獲取常用物件

場景:在Web專案中,有一些物件是經常用到的,如Session中的使用者、HttpServletRequest等,當然可以通過Spring依賴注入,但是依賴注入不方便的時候,可以通過ThreadLocal儲存每一個請求所用到的資料。

  • Filter解析Session獲得使用者和HttpServletRequest
package com.yjy.filter;

import com.yjy.common.RequestHolder;
import com.yjy.model.SysUser;
import lombok.extern.slf4j.Slf4j;

import
javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Slf4j public class LoginFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws
IOException, ServletException { HttpServletRequest req = (HttpServletRequest) servletRequest; HttpServletResponse resp = (HttpServletResponse) servletResponse; SysUser sysUser = (SysUser) req.getSession().getAttribute("user"); if (sysUser == null) { String path = "/signIn.jsp"
; resp.sendRedirect(path); return; } RequestHolder.add(sysUser); RequestHolder.add(req); filterChain.doFilter(servletRequest, servletResponse); return; } public void destroy() { } }
  • RequestHolder利用ThreadLocal儲存和獲取物件
package com.yjy.common;

import com.yjy.model.SysUser;

import javax.servlet.http.HttpServletRequest;

public class RequestHolder {

    private static final ThreadLocal<SysUser> userHolder = new ThreadLocal<SysUser>();

    private static final ThreadLocal<HttpServletRequest> requestHolder = new ThreadLocal<HttpServletRequest>();

    public static void add(SysUser sysUser) {
        userHolder.set(sysUser);
    }

    public static void add(HttpServletRequest request) {
        requestHolder.set(request);
    }

    public static SysUser getCurrentUser() {
        return userHolder.get();
    }

    public static HttpServletRequest getCurrentRequest() {
        return requestHolder.get();
    }

    public static void remove() {
        userHolder.remove();
        requestHolder.remove();
    }
}
  • 獲取物件
SysUser sysUser = RequestHolder.getCurrentUser();

HttpServletRequest request = RequestHolder.getCurrentRequest();