2

I want to do some encryption/decryption for both JSON request and response.For that i choosed servlet filter.But,i dont know how to modify and set the json request body. Any solutions are highly appreciable.

2
  • are you using jersey or any other jax-rs implementation? Commented Jul 23, 2018 at 11:29
  • No ,i am using springBoot Commented Jul 23, 2018 at 12:06

1 Answer 1

1

You must use wrappers:

private static class MyRequestWrapper extends HttpServletRequestWrapper {
    private ServletInputStream input;

    public MyRequestWrapper(ServletRequest request) {
        super((HttpServletRequest)request);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (input == null) {
            input = new InputStreamDecoder(super.getInputStream());
        }
        return input;
    }
}

private static class MyResponseWrapper extends HttpServletResponseWrapper {
    private ServletOutputStream output;

    public MyResponseWrapper(ServletResponse response) {
        super((HttpServletResponse)response);
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        if (output == null) {
            output = new OutputStreamEncoder(super.getOutputStream());
        }
        return output;
    }

    public void close() throws IOException {
        if (output != null) {
            output.flush();
        }
    }
}

@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain)
        throws IOException, ServletException {
    MyRequestWrapper req = new MyRequestWrapper(request);
    MyResponseWrapper res = new MyResponseWrapper(response);
    chain.doFilter(req, res);
    res.close();
}
2
  • Thank you @Maurice .For OutputStreamEncoder and InputStreamDecoder which jar i need to import. Commented Jul 23, 2018 at 12:06
  • @RathanaKumar it's the standard servlet API Commented Jul 23, 2018 at 13:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.