使用ContentCachingRequestWrapper会导致参数表为空 [英] Using ContentCachingRequestWrapper causes Empty Parameters Map

查看:2216
本文介绍了使用ContentCachingRequestWrapper会导致参数表为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了一个过滤器,在该过滤器中,我想先读取请求的内容以进行一些检查,然后再继续。

I have implemented a Filter, in which I want to read the content of request first for some checks and then I would like to go on.

但是问题是也就是说,在以下来自过滤器链的过滤器中,类请求(org.eclipse.jetty.server.Request)中的 getParameters()方法而不是类ContentCachingRequestWrapper 中的 getParameters()方法被调用。因此 parametersMap 不会填充,并且始终为空。

But the problem is, that in the following filter from the filter chain the getParameters() Method from class Request (org.eclipse.jetty.server.Request) is called and not the getParameters() method from class ContentCachingRequestWrapper. So the parametersMap are not filled and is always empty.

这是我的代码:

@Component
@Order(1)
public class EncodingFilter extends GenericFilterBean {

private static final Logger LOG = 
LoggerFactory.getLogger(EncodingFilter.class);

@Override
public void doFilter(ServletRequest request, ServletResponse response, 
FilterChain chain) throws IOException, ServletException {

final HttpServletRequest req = (HttpServletRequest) request;
HttpServletRequest servletRequest = new ContentCachingRequestWrapper(req);

String read = ByteSource.wrap(ByteStreams.toByteArray(servletRequest.getInputStream()))
        .asCharSource(StandardCharsets.UTF_8).read();
// Doing analysis .....
// last step call filter chain
chain.doFilter(servletRequest, response);
}
}

在控制器中:

@PostMapping(
    value = Endpoints.Janus.INIT,
    produces = MediaType.TEXT_HTML_VALUE
)
public ModelAndView controller(
    @RequestParam LinkedCaseInsensitiveMap<String> params,
    HttpServletRequest servletRequest
) {
 ....  
}

在控制器中,参数映射始终为空。
如果我没有在过滤器中调用servletRequest.getInputStream(),则将填充参数Map。

In the controller the params Map is always empty. If I don't call servletRequest.getInputStream() in my filter, the params Map is filled.

我正在使用Jetty作为应用程序服务器的Spring Boot 1.5.6

I am working with Spring Boot 1.5.6 with Jetty as Application Server

推荐答案

ContentCachingRequestWrapper 不能那样工作,并且有一些限制。据我所知,只有POST请求和内容类型应为 application / x-www-form-urlencoded 。如果这适合您,则应该执行以下操作:

ContentCachingRequestWrapper doesnt work that way and has some limitations. Only POST request and content type should be application/x-www-form-urlencoded as far as I remember. If this fits for you, here's what you should do:

final HttpServletRequest req = (HttpServletRequest) request;
HttpServletRequest servletRequest = new ContentCachingRequestWrapper(req);
servletRequest.getParameterMap(); // needed for caching!!

String read = ByteSource.wrap(servletRequest.getContentAsByteArray())
    .asCharSource(StandardCharsets.UTF_8).read(); // Please note that we're not touching input stream!!

希望这会有所帮助。

这篇关于使用ContentCachingRequestWrapper会导致参数表为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆