SpringMVC的RequestContextHolder分析
程序员文章站
2024-02-08 14:42:28
...
为什么要分析这个RequestContextHolder?
首先,我们一般获取request和response都是在过滤器Filter,或者拦截器,或者controller层获取
但如果在service获取request和response,正常来说在service层是没有request的,当我们需要在service层获取request和response时,我们可以在RequestContextHolder中获取。
//两个方法在没有使用JSF的项目中是没有区别的
RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
// RequestContextHolder.getRequestAttributes();
//从session里面获取对应的值
String str = (String) requestAttributes.getAttribute("name",RequestAttributes.SCOPE_SESSION);
HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
HttpServletResponse response = ((ServletRequestAttributes)requestAttributes).getResponse();
一般封装工具类
/**
* 获取request
*/
public static HttpServletRequest getRequest() {
return getRequestAttributes().getRequest();
}
/**
* 获取response
*/
public static HttpServletResponse getResponse() {
return getRequestAttributes().getResponse();
}
/**
* 获取session
*/
public static HttpSession getSession() {
return getRequest().getSession();
}
public static ServletRequestAttributes getRequestAttributes() {
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
return (ServletRequestAttributes) attributes;
}
可参考文章:https://blog.csdn.net/u012706811/article/details/53432032