1.前言
你还在 Controller 传一个 HttpServletRequest 或 HttpServletResponse 到下面好几层以便获取到该对象进行处理吗??
那就 out 咯,曾经我也是这么做的,哈哈哈~
今天写代码想起来要获取这个对象,一下子想不起来叫什么了,只隐隐约约记得叫 HttpRequestContextHolder
来获取,但是,错了,其实是RequestContextHolder
,难怪自动提示来不出来。
于是,我决定还是写个文章记录一下方便以后自己找
2.代码
java
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
HttpServletResponse response = requestAttributes.getResponse();
比如你也可以稍微封装一下,搞一个类静态调用分别获取 Request、Response,随后你就可以在项目的任何位置调用得到这两个对象以便在请求前、返回前做一些别的处理了。
这里,我只是举个例子:
java
public class MyServletContextHolder {
private static ServletRequestAttributes requestAttributes = null;
private static void lazyInit() {
if (null == requestAttributes) {
synchronized (MyServletContextHolder.class) {
if (null == requestAttributes) {
requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
}
}
}
}
public static HttpServletRequest getHttpServletRequest() {
lazyInit();
return requestAttributes.getRequest();
}
public static HttpServletResponse getHttpServletResponse() {
lazyInit();
return requestAttributes.getResponse();
}
}