获取用户登录信息和request对象的工具类RequestHolder

在Web开发中,service层或者某个工具类中需要获取到HttpServletRequest对象还是比较常见的。一种方式是将HttpServletRequest作为方法的参数从controller层一直放下传递,不过这种有点费;还有另一种则是写一个RequestHolder,代码如下:

package com.kang.common;

import com.kang.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();
    }
}

写完工具类后,要让用户登录的时候将用户信息存入RequestHolder中,此时写一个过滤器来实现:

package com.kang.filter;

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

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
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;
        }
        
		//将用户信息和request都放到RequestHolder中
        RequestHolder.add(sysUser);
        RequestHolder.add(req);
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

    public void destroy() {
     

    }
}

最后需要在web.xml中配置:

 
    <filter>
        <filter-name>loginFilterfilter-name>
        <filter-class>com.kang.filter.LoginFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>loginFilterfilter-name>
        <url-pattern>/sys/*url-pattern>
        <url-pattern>/admin/*url-pattern>
    filter-mapping>

你可能感兴趣的:(工具类)