@Slf4j
public class ParameterCheckServletRequestWrapper extends HttpServletRequestWrapper {
private byte[] requestBody;
private Charset charSet;
public ParameterCheckServletRequestWrapper(HttpServletRequest request) {
super(request);
try {
String requestBodyStr = getRequestPostStr(request);
if (StringUtils.isNotBlank(requestBodyStr)) {
JSONObject resultJson = JSONObject.fromObject(requestBodyStr.replace("\"", "'"));
Object[] obj = resultJson.keySet().toArray();
for (Object o : obj) {
resultJson.put(o, StringUtils.trimToNull(resultJson.get(o).toString()));
}
requestBody = resultJson.toString().getBytes(charSet);
} else {
requestBody = new byte[0];
}
} catch (IOException e) {
log.error("", e);
}
}
public String getRequestPostStr(HttpServletRequest request)
throws IOException {
String charSetStr = request.getCharacterEncoding();
if (charSetStr == null) {
charSetStr = "UTF-8";
}
charSet = Charset.forName(charSetStr);
return StreamUtils.copyToString(request.getInputStream(), charSet);
}
@Override
public ServletInputStream getInputStream() {
if (requestBody == null) {
requestBody = new byte[0];
}
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(requestBody);
return new ServletInputStream() {
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
@Override
public int read() {
return byteArrayInputStream.read();
}
};
}
@Override
public BufferedReader getReader() {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
}
public class ParameterCheckFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
ParameterCheckServletRequestWrapper myWrapper = new ParameterCheckServletRequestWrapper((HttpServletRequest) servletRequest);
filterChain.doFilter(myWrapper, servletResponse);
}
@Override
public void destroy() {
}
}
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean authFilterRegistrationBean() {
FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setName("parameterCheckFilter");
registrationBean.setFilter(new ParameterCheckFilter());
registrationBean.setOrder(1);
registrationBean.addUrlPatterns("/*");
return registrationBean;
}
}