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.
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.
Here is how my code looks like:
@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);
}
}
And in Controller:
@PostMapping(
value = Endpoints.Janus.INIT,
produces = MediaType.TEXT_HTML_VALUE
)
public ModelAndView controller(
@RequestParam LinkedCaseInsensitiveMap<String> params,
HttpServletRequest servletRequest
) {
....
}
In the controller the params Map is always empty. If I don't call servletRequest.getInputStream() in my filter, the params Map is filled.
I am working with Spring Boot 1.5.6 with Jetty as Application Server
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!!
Hope this helps.