public class CacheRequestFilter implements Filter {
private static Constructor<?> BODY_INPUT_STREAM_CONSTRUCTOR = null;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException, ServletException {
if (request instanceof MultipartHttpServletRequest) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
}
if (request instanceof HttpServletRequest) {
ContentCachingRequestWrapper wrapper = buildWrapper((HttpServletRequest) request);
Map<String, String[]> parameterMap = request.getParameterMap();
IOUtils.copy(wrapper.getInputStream(), new ByteArrayOutputStream());
chain.doFilter(wrapper, response);
} else {
chain.doFilter(request, response);
}
}
public ContentCachingRequestWrapper buildWrapper(HttpServletRequest request) {
return new ContentCachingRequestWrapper(request) {
@Override
public ServletInputStream getInputStream() throws IOException {
ServletInputStream inputStream = super.getInputStream();
if (inputStream.isFinished()) {
try {
return createInstanceStream(this.getContentAsByteArray());
} catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
} else {
return inputStream;
}
}
};
}
public ServletInputStream createInstanceStream(byte[] body) throws InvocationTargetException, InstantiationException, IllegalAccessException {
Object instance = BODY_INPUT_STREAM_CONSTRUCTOR.newInstance(body);
return (ServletInputStream) instance;
}
static {
try {
Class<?> clazz = Class.forName("org.springframework.web.servlet.function.DefaultServerRequestBuilder$BodyInputStream");
Constructor<?> bodyInputStream = clazz.getDeclaredConstructor(byte[].class);
bodyInputStream.setAccessible(true);
BODY_INPUT_STREAM_CONSTRUCTOR = bodyInputStream;
} catch (ClassNotFoundException | NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
}
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean<CacheRequestFilter> loggingFilter() {
FilterRegistrationBean<CacheRequestFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new CacheRequestFilter());
registrationBean.addUrlPatterns("/*");
return registrationBean;
}
}