使用HttpServletRequestWrapper来修改post请求中的json数据

文章目录

        • 过滤的效果:
        • 具体的实现代码:

公司里最近在做一个新的项目,项目中所有的请求都是这样的一个格式。
使用HttpServletRequestWrapper来修改post请求中的json数据_第1张图片
因为version版本号在业务里并没有用到,只是一个验证依据,所以就想把它过滤掉。

过滤的效果:

过滤前
{
"version" : "11111111",
"data": {
   "heartbeat_time": 1468471315134
}
}
过滤后
{"heartbeat_time":1468471315134}

具体的实现代码:

1.自定义一个过滤器

@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/north/*", filterName = "httpFilter")//此处的url根据实际情况而定
public class HttpReplaceFilter implements Filter {
    private static final Set<String> ALLOW_PATHS = new HashSet<>(Arrays.asList("/serviceName"));

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        String path = ((HttpServletRequest)request).getRequestURI().substring(((HttpServletRequest) request).getContextPath().length());
        //如果是在ALLOW_PATHS的集合中,那么就允许这种请求直接通过
        if (ALLOW_PATHS.contains(path)){
            filterChain.doFilter(request, response);
        }
        //HttpServletRequest没有提供相关的set方法来修改body,所以需要用修饰类
        ServletRequest requestWrapper = new BodyRequestWrapper((HttpServletRequest) request);

        filterChain.doFilter(requestWrapper, response);
    }

    @Override
    public void destroy() {

    }
}

2.自定义一个Http请求的修饰类

public class BodyRequestWrapper extends HttpServletRequestWrapper {

    private byte[] body;
    public BodyRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        StreamUtil.readBytes(request.getReader(), "utf-8");
        //由于request并没有提供现成的获取json字符串的方法,所以我们需要将body中的流转为字符串
        String json = new String(StreamUtil.readBytes(request.getReader(), "utf-8"));
        body = getData(json).getBytes();
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    /**
     * 在使用@RequestBody注解的时候,其实框架是调用了getInputStream()方法,所以我们要重写这个方法
     * @return
     * @throws IOException
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);

        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() throws IOException {
                return bais.read();
            }
        };
    }

    private String getData(String json){
        if (!json.contains("\"data\"")){
            return "";
        }
        ObjectMapper mapper = new ObjectMapper();
        String data = null;
        try {
            JsonNode jsonNode = mapper.readTree(json);
            data = jsonNode.get("data").toString();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return data;
    }
}

以上代码就可以实现将json数据过滤掉了

框架是springboot,还有用到了joda-io依赖包

你可能感兴趣的:(spring)