我并不是要特别解决任何问题,而是我正在学习运动衫的路径 .
我有一个标记为这样的实体类:
@Entity
@Table(name = "myentity")
@XmlRootElement
public class MyEntity implements serializable {
// lots of methods...
}
以及相应的球衣服务
@Stateless
@Path("entity")
public class EntityFacade {
@GET
@Path("{param}")
@Produces({"application/xml;charset=UTF-8"})
public List<MyEntity> find(@PathParam("param") String param) {
List entities = entityManager.getResultList(); // retrieve list from db
return entities;
}
}
这给出了正确的XML响应 . 假设我想编写一个MessageBodyWriter来复制相同的行为,这会产生XML响应,我怎么能这样做?
@Provider
public class TrasformerMessageBodyWriter implements MessageBodyWriter<Object> {
@Override
public long getSize(Object o, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return 0;
}
@Override
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
// return true or false depending if I want to rewrite the response
}
@Override
public void writeTo(Object o, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException,
WebApplicationException {
// what do I need to write here...
}
}
通过使用@Provider注释进行标记,我可以看到正确调用了消息体编写器 .
当调用writeTo时,Object o是一个Vector,而类型genericType是一个List,但在这一点上,我完全迷失了如何在XML中转换对象 .
最后,如果一切都已经由泽西及其注释提供,那么MessageBodyWriter如何有用呢?
我再次重申,这只是一次学术活动 .
1 回答
通常会使用
MessageBodyWriter
将对象转换为Jersey一无所知的数据格式 . 以下是将TableData
域对象转换为CSV的示例:在您的示例中,您可以通过自己检查对象并将结果提供给_2880426来创建XML,也可以使用JAXB(Jersey内部使用)将对象直接编组到
OutputStream
. 出于练习的目的,JAXB可能更有趣 .