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