我并不是要特别解决任何问题,而是在学习球衣的道路上.
我有一个标记为这样的实体类:
@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,MediaType mediaType) { // return true or false depending if I want to rewrite the response } @Override public void writeTo(Object o,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如何有用呢?
我再次重申,这只是一次学术活动.
通常,人们会使用MessageBodyWriter将对象转换为Jersey一无所知的数据格式.以下是将TableData域对象转换为CSV的示例:
原文链接:https://www.f2er.com/xml/293122.html@Singleton @Produces("text/csv") @Provider public class FederationCsvWriter implements MessageBodyWriter<TableData> { @Override public boolean isWriteable(Class<?> type,MediaType mediaType) { return TableData.class.isAssignableFrom(type); } @Override public long getSize(TableData data,Annotation annotations[],MediaType mediaType) { return -1; } @Override public void writeTo(TableData data,Object> headers,OutputStream out) throws IOException { Writer osWriter = new OutputStreamWriter(out); CSVWriter writer = new CSVWriter(osWriter,','"',"\r\n"); if (data.getResultCount() > 0) { //Write the header writer.writeNext(data.getResult().get(0).keySet().toArray(new String[data.getResult().get(0).keySet().size()])); //Write the data for (ModelData row: data.getResult()) { writer.writeNext(row.values().toArray(new String[row.values().size()])); } } writer.flush(); } }
在您的示例中,您可以通过自己检查对象并将结果提供给OutputStream来创建XML,也可以使用JAXB(Jersey内部使用)将对象直接编组到OutputStream.出于练习的目的,JAXB可能更有趣.