2015-02-23 97 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,在這裏你不需要使用註釋。你可以簡單地做一些反思來檢查方法或類。該鏈接有一個例子。

相關問題