2014-06-11 30 views
2

我正在學習如何從提供者的MessageBodyReader方法工作。我看到該方法返回一個對象,我不知道如何從服務訪問該對象。我能否獲得關於如何獲取讀者類返回的對象的解釋?這將幫助我爲所有dto應用閱讀規則。提前致謝!Jax-RS MessageBodyReader

服務:

@POST 
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) 
    @Path("/CreateAccount") 
    @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) 
    public Response createAccount(@Context HttpServletRequest req) { 

     String a = "Reader success? ";//Would to see that string here! 
     return Response.ok().build(); 
    } 

提供者:

@Provider 
public class readerClass implements MessageBodyReader<Object> 
{ 

@Override 
public boolean isReadable(Class<?> paramClass, Type paramType, 
     Annotation[] paramArrayOfAnnotation, MediaType paramMediaType) { 
    // TODO Auto-generated method stub 
    return true; 
} 

@Override 
public Object readFrom(Class<Object> paramClass, Type paramType, 
     Annotation[] paramArrayOfAnnotation, MediaType paramMediaType, 
     MultivaluedMap<String, String> paramMultivaluedMap, 
     InputStream paramInputStream) throws IOException, 
     WebApplicationException { 
    // TODO Auto-generated method stub 

    return "Successfully read from a providers reader method"; 
} 

} 

回答

1

你誤會化MessageBodyReader,它被用於以下目的的宗旨:

合同供應商支持轉換流類型爲 Java類型。要添加MessageBodyReader實現,請使用@Provider註釋 實現類。一化MessageBodyReader 實現可以與消耗進行註釋,以限制媒體 類型,它會被認爲是合適

例如: 如果你有,你得到來自定義格式比XML/JSON的用途的情況下,要提供自己的解組,您可以使用消息體讀者

@Provider 
    @Consumes("customformat") 
    public class CustomUnmarshaller implements MessageBodyReader { 

     @Override 
     public boolean isReadable(Class aClass, Type type, Annotation[] annotations, MediaType mediaType) { 
      return true; 
     } 


     @Override 
     public Object readFrom(Class aClass, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap multivaluedMap, InputStream inputStream) throws IOException, WebApplicationException { 
      Object result = null; 
      try { 
       result = unmarshall(inputStream, aClass); // un marshall custom format to java object here 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

      return result; 


} 
} 

在web服務,你可以使用這個喜歡..

@POST  
    @Path("/CreateAccount") 
    @Consumes("custom format") 
    public Response createAccount(@Context HttpServletRequest req,Account acc) { 

     saveAccount(acc); // here acc object is returned from your custom unmarshaller 
     return Response.ok().build(); 
    } 

更多信息Custom Marshalling/UnMarshalling ExampleJersy Entity Providers Tutorial

相關問題