zoukankan      html  css  js  c++  java
  • 在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>
  • 相关阅读:
    jmeter实现multipart/form-data类型请求
    jmeter(正则提取器、json提取器)做接口关联
    windows使用ubuntu启动linux服务
    Jmeter+Ant+Jenkins环境搭建
    ubuntu网卡驱动的安装
    Ubuntu 挂载U盘
    Linux下安装jdk8步骤详述(转载)
    springboot项目:项目部署
    springboot项目:Redis缓存使用
    springboot项目:Redis分布式锁的使用(模拟秒杀系统)
  • 原文地址:https://www.cnblogs.com/tabchanj/p/5716119.html
Copyright © 2011-2022 走看看