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

过滤的效果:

过滤前

{
"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 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数据过滤掉了

你可能感兴趣的:(用HttpServletRequestWrapper来修改http请求中的json数据)