springMVC中获取request和response对象的几种方式(RequestContextHolder)
Posted Yan Yang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springMVC中获取request和response对象的几种方式(RequestContextHolder)相关的知识,希望对你有一定的参考价值。
springMVC中获取request和response对象的几种方式
原文链接:https://blog.csdn.net/weixin_43052839/article/details/82426735
1.最简单方式:参数
@RequestMapping("/test")
@ResponseBody
public void saveTest(HttpServletRequest req, HttpServletResponse resp){
}
2.加入监听器,然后在代码里面获取
在Spring API中提供了一个非常便捷的工具类 RequestContextHolder,能够在Controller中获取request对象和response对象,使用方法如下:
public class TestRequest {
public HttpServletRequest getRequest() {
HttpServletRequest request=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
HttpServletResponse response=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
return request;
}
}
tips:需要注意的是如果直接使用这个工具类,则会抛出一个空指针异常。原因是需要先在web.xml配置RequestContextListener监听器:
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
原理
RequestContextListener实现了 ServletRequestListener ,在其覆盖的requestInitialized(ServletRequestEvent requestEvent)方法中,将request最终设置到了RequestContextHolder中
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
public class RequestContextListener implements ServletRequestListener {
private static final String REQUEST_ATTRIBUTES_ATTRIBUTE =
RequestContextListener.class.getName() + ".REQUEST_ATTRIBUTES";
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中
}
public void requestDestroyed(ServletRequestEvent arg0) {
// TODO Auto-generated method stub
}
}
以上是关于springMVC中获取request和response对象的几种方式(RequestContextHolder)的主要内容,如果未能解决你的问题,请参考以下文章
springmvc中获取request对象,加载biz(service)的方法
在springMVC的controller中获取request,response对象的一个方法
Spring mvc HandlerInterceptor 怎样获取 rest 参数值