Jax-RS MessageBodyReader

时间:2014-06-11 02:41:51

标签: java jax-rs

我正在学习MessageBodyReader方法如何从提供程序中工作。我看到该方法返回一个对象,我不知道如何从服务访问该对象。我可以获得如何从读者类返回对象的解释吗?这将有助于我为所有dto应用阅读规则。提前谢谢!

服务:

    @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 个答案:

答案 0 :(得分:2)

您误解了MessageBodyReader的用途,它用于以下目的:

  

支持将流转换为的提供商的合同   Java类型。要添加MessageBodyReader实现,请注释   使用@Provider实现类。 MessageBodyReader   可以使用Consumes注释实现来限制媒体   适合的类型

示例:           如果你有一个用例来自xml / json以外的自定义格式,你想提供自己的UnMarshaller,你可以使用messagebody reader

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


}
}

在网络服务中,你可以使用它......

    @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 Example,     Jersy Entity Providers Tutorial

相关问题