我正在从提供者那里了解 MessageBodyReader 方法的工作原理。我看到该方法返回一个对象,但我不确定如何从服务访问该对象。我可以获得有关如何从 reader 类返回对象的解释吗?这将帮助我为所有 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();
}
Run Code Online (Sandbox Code Playgroud)
提供商:
@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";
}
}
Run Code Online (Sandbox Code Playgroud)
您误解了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;
}
}
Run Code Online (Sandbox Code Playgroud)
在网络服务中你可以像这样使用它。
@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();
}
Run Code Online (Sandbox Code Playgroud)
更多信息: 自定义编组/解编组示例、 Jersy 实体提供程序教程
| 归档时间: |
|
| 查看次数: |
21301 次 |
| 最近记录: |