Search code examples
jakarta-eejax-rsjava-ee-7

MessageBodyWriter vs. WriterInterceptor


I am a bit confused about the exact intention of the WriterInterceptor Interface of the JAX-RS 2.0 specification.

What I know so far:

  • WriterInterceptor is called before MessageBodyWriter
  • Both Interfaces grant access to the same variables
  • MessageBodyWriter is concerned with translating an object into a stream
  • Arun Gupta states in his Java EE 7 book that Writer/Reader Inteceptors are mainly concerned with marshalling and unmarshalling of HTTP bodies.

My questionis: For which intent should the Reader/Writer Interceptor be used for?


Solution

  • On the server-side you can let the Message Body Writers do the entity marshalling and while the Interceptors can take care of:

    • performing GZIP compression of the marshalled entity,
    • wrapping the marshalled entity in a Digital Signature enveloppe (reader interceptor could verify a signature before further processing),
    • adding Cache control headers

    For example:

    @Override
    void aroundWriteTo(WriterInterceptorContext ctx) ... {
        OutputStream old = ctx.getOutputStream();
        GZIPOutputStream gzipOutputStream = new GZIPOutputStream(old);
        ctx.setOutputStream(gzipOutputStream);
        updateHeaders(ctx);
        try {
            ctx.proceed();
        } finally {
            gzipOutputStream.finish();
            ctx.setOutputStream(old);
        }
    }
    

    (code above comes from the JAX-RS 2.0 spec, section 6.3)

    HTH.