SpringBoot通过RequestContextHolder获取HttpRequest和HttpResponse

Mark一下
开发时,有时候会遇到在一些方法中,函数参数并没有给出request,response或者session,那该怎么解决呢
我们可以通过SpringBoot提供的RequestContextHolder获得

ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
HttpServletResponse response = requestAttributes.getResponse();
//从session里面获取对应的值
String myValue = (String) requestAttributes.getAttribute("my_value",RequestAttributes.SCOPE_SESSION);

更多关于RequestContextHolder可以参看这篇博客
RequestContextHolder分析

你可能感兴趣的:(java)