RequestContextHolder获取request和response
首先需要在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(); } } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
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()).g