获取request,获取response,获取session,获取ServletRequestAttributes,的工具类
在Spring框架中,你可以使用RequestContextHolder
来获取当前的HttpServletRequest
, HttpServletResponse
和 ServletRequestAttributes
。以下是一个工具类的示例代码:
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class WebUtils {
public static HttpServletRequest getCurrentRequest() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
return attributes == null ? null : attributes.getRequest();
}
public static HttpServletResponse getCurrentResponse() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
return attributes == null ? null : attributes.getResponse();
}
public static HttpSession getCurrentSession() {
return getCurrentRequest().getSession();
}
public static ServletRequestAttributes getServletRequestAttributes() {
return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
}
}
使用这个工具类,你可以在任何需要的地方获取到当前请求的HttpServletRequest
, HttpServletResponse
和 HttpSession
。注意,在非web请求的线程中(例如定时任务)使用这些方法可能返回null
。
评论已关闭