过滤器 读取http post body
【摘要】 public class HttpServletRequestCheckFilter implements Filter { /** * 默认URL匹配规则 */ private static final Pattern URL_PATTERN = Pattern.compile("/engine/"); private static final Strin...
public class HttpServletRequestCheckFilter implements Filter {
/**
* 默认URL匹配规则
*/
private static final Pattern URL_PATTERN = Pattern.compile("/engine/");
private static final String PARAM_ERROR = "dsType mismatch";
private static final long PARAM_ERROR_CODE = 403;
private static final String SEPARATOR = "/";
private static final String DSTYPE = "dsType";
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
if (servletRequest instanceof HttpServletRequest && servletResponse instanceof HttpServletResponse) {
HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
StandardHttpServletRequestEx httpServletRequestEx = new StandardHttpServletRequestEx(httpRequest);
httpServletRequestEx.setCacheRequest(true);
httpServletRequestEx.getInputStream();
if (URL_PATTERN.matcher(httpServletRequestEx.getPathInfo()).find()) {
try {
getDsType(httpServletRequestEx);
} catch (Exception e) {
// 失败
BaseResponse<String> response = HttpUtil.buildResponse(PARAM_ERROR_CODE, PARAM_ERROR, String.class);
httpResponse.setStatus((int) ErrorCode.RETURN_PARAM_ILLEGAL);
httpResponse.setContentType("application/json");
httpResponse.getWriter().write(JsonMapper.nonNullMapper().toJson(response));
logger.error("check failed!exception:{}", e.getMessage());
return;
}
}
filterChain.doFilter(httpServletRequestEx, servletResponse);
} else {
throw new ServletException("just supports HTTP requests");
}
}
/**
* 校验参数
*
* @param request 请求
*/
private void getDsType(HttpServletRequestEx request) {
// 获取body信息
String body = "";
try {
Buffer buffer = request.getBodyBuffer();
if (Objects.nonNull(buffer)) {
body = buffer.toString();
}
String dsType = JSON.parseObject(body).get(DSTYPE).toString();
String[] urlSplit = request.getRequestURL().toString().split(SEPARATOR);
if (null == dsType || !urlSplit[urlSplit.length - 1].equals(dsType)) {
throw new SignerException(PARAM_ERROR);
}
} catch (Exception e) {
throw new SignerException(PARAM_ERROR);
}
}
}
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)