SpringBoot项目中普通类获取http相关的类(request/response/sesion)

2019-08-28

SpringBoot项目中普通类获取http相关的类(request/response/sesion)

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author yangzhilong
 * @date 6/19/2019
 */
public class SessionUtils {
    private SessionUtils() {}
    
    /**
     * get current login username
     * @return
     */
    public static String getLoginUserName() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if(null != requestAttributes) {
            HttpServletResponse response = requestAttributes.getResponse();
            HttpServletRequest request = requestAttributes.getRequest();
            HttpSession session = request.getSession();
            
            String username = request.getHeader("username");
            if (StringUtils.isNotEmpty(username)) {
                return username;
            }
        }
        return "default";
    }
}

 

SpringBoot项目中普通类获取http相关的类(request/response/sesion)

SpringBoot项目中普通类获取http相关的类(request/response/sesion)

原文地址:https://www.cnblogs.com/yangzhilong/p/11425072.html