[] ThreadLocal Java Advanced use

Copyright: https://blog.csdn.net/qq_21852449/article/details/84331917

ThreadLocal to hold a thread shared variables: for the same static ThreadLocal, from different threads can only get, set, remove your own variables, variables without affecting other threads.

1, ThreadLocal.get: ThreadLocal to get the value in the current thread shared variable.

2, ThreadLocal.set: Set the value of the current thread shared variables ThreadLocal in.

3, ThreadLocal.remove: remove the current value of the shared variable thread a ThreadLocal.

4, ThreadLocal.initialValue: ThreadLocal or not the current thread after calling the get method call to remove just the current thread assignment method, this method returns a value.

/**
 * 在Javaweb中通过ThreadLocal处理高并发 ,可以理解为ThreadLocal相当于一个map ,其中key是我们当前的进程,这样不同进程之间的数据就进行了分离。
 */
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();
    }
}


/**
 * 校验用户是否登录
 */
@Slf4j
public class LoginFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        String servletPath = req.getServletPath();
        SysUser sysUser = (SysUser) req.getSession().getAttribute("user");
        if (sysUser == null) {
            String path = "/signin.jsp";
            res.sendRedirect(path);
            return;
        }
        RequestHolder.add(sysUser);
        RequestHolder.add(req);
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

    @Override
    public void destroy() {

    }
}

Code can achieve access to the user currently logged on and the current Request from any location of the project.

Guess you like

Origin blog.csdn.net/qq_21852449/article/details/84331917