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

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";
    }
}

 

posted @ 2019-08-28 16:57  自行车上的程序员  阅读(4858)  评论(0编辑  收藏  举报