@Produces/provider media type matching

后端 未结 1 1443
不思量自难忘°
不思量自难忘° 2021-01-16 22:26

I am experimenting with api verioning and have a very peculiar requirement to work against. We are going to use content-negotiation i.e @Produces annotation for this and I w

相关标签:
1条回答
  • 2021-01-16 22:54

    You probabily should have to use a custom response mapper.

    1.- Create a class implementing MessageBodyWriter in charge of writing the response

    @Provider
    public class MyResponseTypeMapper 
      implements MessageBodyWriter<MyResponseObjectType> {
         @Override
         public boolean isWriteable(final Class<?> type,final Type genericType,
                    final Annotation[] annotations,
                    final MediaType mediaType) {
           ... use one of the arguments (either the type, an annotation or the MediaType)
               to guess if the object shoud be written with this class
         }
         @Override
         public long getSize(final MyResponseObjectType myObjectTypeInstance,
                         final Class<?> type,final Type genericType,
                             final Annotation[] annotations,
                         final MediaType mediaType) {
            // return the exact response length if you know it... -1 otherwise
            return -1;
        }
        @Override
        public void writeTo(final MyResponseObjectType myObjectTypeInstance,
                        final Class<?> type,final Type genericType,
                        final Annotation[] annotations, 
                        final MediaType mediaType,
                        final MultivaluedMap<String,Object> httpHeaders,
                        final OutputStream entityStream) throws IOException,                                                                 WebApplicationException {
            ... serialize / marshall the MyResponseObjectType instance using
                whatever you like (jaxb, etC)
            entityStream.write(serializedObj.getBytes());
        }
    }
    

    2.- Register the Mappers in your app

    public class MyRESTApp 
         extends Application  {
        @Override
    public Set<Class<?>> getClasses() {
            Set<Class<?>> s = new HashSet<Class<?>>();
            s.add(MyResponseTypeMapper.class);
            return s;
        }
    }
    

    Jersey will scan all registered Mappers calling their isWriteable() method until one returns true... if so, this MessageBodyWriter instance will be used to serialize the content to the client

    0 讨论(0)
提交回复
热议问题