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

Posted yangzhilong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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普通类中如何获取其他bean例如ServiceDao(转)

SpringBoot中在普通类里面加载Spring容器中的类

springboot项目在普通类中调用maper或者service接口

SpringBoot中普通类无法注入service的解决方案

在SpringBoot用普通类调用Spring管理的Bean

SpringBoot整合MongoDB