gpt4 book ai didi

java - JAX-RS MessageBodyReader

转载 作者:搜寻专家 更新时间:2023-11-01 03:23:00 24 4
gpt4 key购买 nike

我正在从提供者处了解 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";
}

}

最佳答案

你误解了 MessageBodyReader 的用途,它的用途如下:

Contract for a provider that supports the conversion of a stream to a Java type. To add a MessageBodyReader implementation, annotate the implementation class with @Provider. A MessageBodyReader implementation may be annotated with Consumes to restrict the media types for which it will be considered suitable

例子: 如果你有一个用例,你得到了除 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

关于java - JAX-RS MessageBodyReader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24153827/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com