1.最简单方式:参数
例如:
@RequestMapping("/test") @ResponseBody public void saveTest(HttpServletRequest req, HttpServletResponse resp){ }
2.加入监听器,然后在代码里面获取
HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
HttpServletResponse resp = ((ServletWebRequest)RequestContextHolder.getRequestAttributes()).getResponse();
使用上述方法前,需要先在web.xml配置RequestContextListener监听器:
<listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener>
原理
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中 }