2015-02-23 96 views
1

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

@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 
    } 
} 

回答

2

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,在这里你不需要使用注释。你可以简单地做一些反思来检查方法或类。该链接有一个例子。

相关问题