【问题标题】:Jersey Update Entity Property MessageBodyWriterJersey 更新实体属性 MessageBodyWriter
【发布时间】:2015-02-23 17:16:08
【问题描述】:

我想创建一个 Jersey 提供程序 (MessageBodyWriter) 来更新 dto 对象属性并继续链接到 Jersey-json 默认提供程序并返回 json 对象。 问题是看起来默认提供者没有被调用,所以我注册新提供者后,我的休息服务的输出就变成了空的。

@Provider
public class TestProvider implements MessageBodyWriter<MyDTO>
{
    @Override
    public long getSize(
        MyDTO arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4)
    {
        return 0;
    }

    @Override
    public boolean isWriteable(Class<?> clazz, Type type, Annotation[] arg2, MediaType arg3)
    {
        return type == MyDTO.class;
    }


    @Override
    public void writeTo(
        MyDTO dto,
        Class<?> paramClass,
        Type paramType, Annotation[] paramArrayOfAnnotation,
        MediaType mt,
        MultivaluedMap<String, Object> paramMultivaluedMap,
        OutputStream entityStream) //NOPMD
    throws IOException, WebApplicationException
    {
        dto.setDescription("text Description");
        // CONTINUE THE DEFAULT SERIALIZATION PROCESS
    }
}

【问题讨论】:

    标签: java rest jersey jax-rs jersey-2.0


    【解决方案1】:

    MessageBodyWriter 不需要执行逻辑来操作实体。它的职责只是编组/序列化。

    您正在寻找的是WriterIntercptor,其目的是完全按照您的意愿去做,在被序列化之前操纵实体。

    都解释了here in the Jersey Doc for Inteceptors

    这是一个例子

    @Provider
    public class MyDTOWriterInterceptor implements WriterInterceptor {
    
        @Override
        public void aroundWriteTo(WriterInterceptorContext context) 
                throws IOException, WebApplicationException {
            Object entity = context.getEntity();
            if (entity instanceof MyDTO) {
                ((MyDTO)entity).setDescription("Some Description");
            }
            context.proceed();
        }  
    }
    

    您可以添加注释,以便只有某些资源方法/类使用此拦截器,例如

    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    import javax.ws.rs.NameBinding;
    
    @NameBinding
    @Target({ElementType.TYPE, ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface AddDescription {
    
    }
    ...
    
    @AddDescription
    @Provider
    public class MyDTOWriterInterceptor implements WriterInterceptor {
    ...
    
    @Path("dto")
    public class MyDTOResource {
    
        @GET
        @AddDescription
        @Produces(MediaType.APPLICATION_JSON)
        public Response getDto() {
            return Response.ok(new MyDTO()).build();
        }
    }
    

    如果由于某种原因您无法更改类(也许这就是您需要在此处设置描述的原因,谁知道),那么您可以使用Dynamic Binding,您不需要使用注释。您可以简单地做一些反射来检查方法或类。该链接有一个示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-24
      相关资源
      最近更新 更多