我正在从提供者那里学习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的用途,它用于以下目的:
范例:
如果您有使用xml/json以外的自定义格式的用例,则要提供自己的UnMarshaller,可以使用messagebody阅读器
@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;
}
}
在webservice中,您可以使用..
@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