更新时间:2022-03-25 09:29:47 来源:极悦 浏览1987次
SpringMVC获取request的方式有哪些?小编来告诉大家。
@Autowired
private HttpServletRequest request;
(1)在web.xml中配置一个监听
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
(2)之后在程序里可以用
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
原理
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中
}
public String hello(HttpServletRequest request,HttpServletResponse response)
通过以上介绍相信大家对SpringMVC获取request的方式已经有所了解,大家如果想了解更多相关知识,不妨来关注一下极悦的Java极悦在线学习,里面的课程内容丰富,从入门到精通,很适合零基础的小伙伴学习,希望对大家能够有所帮助。
0基础 0学费 15天面授
Java就业班有基础 直达就业
业余时间 高薪转行
Java在职加薪班工作1~3年,加薪神器
工作3~5年,晋升架构
提交申请后,顾问老师会电话与您沟通安排学习