在springmvc中使用requestContextListener获取全部的request对象
RequestContextListener实现了 ServletRequestListener ,在其覆盖的requestInitialized(ServletRequestEvent requestEvent)方法中,将request最终设置到了RequestContextHolder中.
public class RequestContextListener implements ServletRequestListener { private static final String REQUEST_ATTRIBUTES_ATTRIBUTE = RequestContextListener.class.getName() + ".REQUEST_ATTRIBUTES"; @Override public void requestInitialized(ServletRequestEvent requestEvent) { if (!(requestEvent.getServletRequest() instanceof HttpServletRequest)) { throw new IllegalArgumentException( "Request is not an HttpServletRequest: " + requestEvent.getServletRequest()); } HttpServletRequest request = (HttpServletRequest) requestEvent.getServletRequest();//从事件对象中获取request对象 ServletRequestAttributes attributes = new ServletRequestAttributes(request);//将request设置到servletRequestAttributes中 request.setAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE, attributes);//反过来将servletRequestAttributes设置到request中 LocaleContextHolder.setLocale(request.getLocale()); RequestContextHolder.setRequestAttributes(attributes);//再将servletRequestAttributes设置到requestContextHolder中 }
代码中获取该request的步骤:
HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.getRequestAttributes())) .getRequest();// 返回了RequestAttributes接口,将其强转为ServletRequestAttributes实现类
使用上述方法前,需要先配置RequestContextListener监听器:
<listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener>