springboot 自定义的DispatcherServlet获取的request和response为空

CheGanX 发布于 2019/12/23 14:08
阅读 1K+
收藏 0

NGINX Sprint China 2022--NGINX年度旗舰盛会,已开启免费预约!>>>

@SpringBootApplication
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class);
    }

    @Bean
    public ServletRegistrationBean<DispatcherServlet> dispatcherRegistration() {
        return new ServletRegistrationBean<>(dispatcherServlet());
    }

    @Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
    public DispatcherServlet dispatcherServlet() {
        return new TestFilter();
    }

}
--------------------------------------------------------------------------------------
public class TestFilter extends DispatcherServlet {

    @Override
    protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
        System.out.println("url=" + request.getRequestURI());
        System.out.println("request = " + requestWrapper.getContentAsByteArray().length);
        super.doDispatch(request, response);
    }

}


如上getContent获取的长度为0,springboot版本2.2.1

加载中
0
wgslucky
wgslucky

你是什么业务,需要动这么低层的代码?如果是要添加一个fiter的话,好像不是这样添加的吧

0
炎黄伙哥
炎黄伙哥

ContentCachingRequestWrapper会在第一次获取参数的时候加载原request数据

            ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
            System.out.println("url=" + request.getRequestURI());
            System.out.println("request = " + requestWrapper.getContentAsByteArray().length);
            requestWrapper.getParameter("a");
            System.out.println("request = " + requestWrapper.getContentAsByteArray().length);
            super.doDispatch(request, response);

第二次就有值了

OSCHINA
登录后可查看更多优质内容
返回顶部
顶部