首先需要在web.xml中配置监听器,这个监听器源码如下,实现了ServletRequestListener,则每个请求进来都会被监听
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.web.context.request;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.i18n.LocaleContextHolder;
public class RequestContextListener implements ServletRequestListener {
private static final String REQUEST_ATTRIBUTES_ATTRIBUTE = RequestContextListener.class.getName() + ".REQUEST_ATTRIBUTES";
public RequestContextListener() {
}
public void requestInitialized(ServletRequestEvent requestEvent) {
if (!(requestEvent.getServletRequest() instanceof HttpServletRequest)) {
throw new IllegalArgumentException("Request is not an HttpServletRequest: " + requestEvent.getServletRequest());
} else {
HttpServletRequest request = (HttpServletRequest)requestEvent.getServletRequest();
ServletRequestAttributes attributes = new ServletRequestAttributes(request);
request.setAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE, attributes);
LocaleContextHolder.setLocale(request.getLocale());
RequestContextHolder.setRequestAttributes(attributes);//将request包装的ServletRequestAttributes放入RequestContextHolder
}
}
public void requestDestroyed(ServletRequestEvent requestEvent) {
ServletRequestAttributes attributes = (ServletRequestAttributes)requestEvent.getServletRequest().getAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE);
ServletRequestAttributes threadAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
if (threadAttributes != null) {
if (attributes == null) {
attributes = threadAttributes;
}
LocaleContextHolder.resetLocaleContext();
RequestContextHolder.resetRequestAttributes(); //将ServletRequestAttributes等资源清除掉
}
if (attributes != null) {
attributes.requestCompleted();
}
}
}
web.xml中配置如下
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
spring中获取request 和 response代码
HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
HttpServletResponse resp = ((ServletWebRequest)RequestContextHolder.getRequestAttributes()).getResponse();