栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

为什么我的请求实体InputStream在ContainerRequestFilter(Spring + Jersey)中始终为空

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

为什么我的请求实体InputStream在ContainerRequestFilter(Spring + Jersey)中始终为空

这是“解决方案”

在SpringBoot中,如果添加了starter-
web模块,它将添加spring:webmvc,这似乎与JaxRS和Servlet过滤器不兼容。如果使用SpringBoot和Jersey,请确保webmvcjar不在类路径中。

Spring堆栈将使用Servlet的Request InputStream,并且管道中的每个向下拦截器/过滤器将一无所有。

这是一段有效的代码片段,可在Servlet过滤器中获取请求的有效负载

public MyFilter implements Filter{    @Override    public final void doFilter(        final ServletRequest request,        final ServletResponse response,        final FilterChain chain)        throws IOException,        ServletException {        getRawFormPayload((HttpServletRequest) request);        chain.doFilter(request, response);    }     protected String getRawFormPayload(HttpServletRequest request) {        final int contentLength = request.getContentLength();        final StringBuilder payloadBuilder = new StringBuilder(contentLength);        try { final InputStream inputStream = request.getInputStream(); final BufferedReader reader =     new BufferedReader(new InputStreamReader(inputStream, request.getCharacterEncoding())); // Buffer should not be higher than the content-length of the request reader.mark(contentLength + 1); final char[] charBuffer = new char[contentLength + 1]; int bytesRead = -1; while ((bytesRead = reader.read(charBuffer)) > 0) {     payloadBuilder.append(charBuffer, 0, bytesRead); } // Reset the buffer so the next Filter/Interceptor have unaltered InputStream reader.reset();        } catch (final IOException e) { this.LOG.error(e.getMessage(), e);        }        return payloadBuilder.toString();    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/443291.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号