我并不是要特别解决任何问题,而是要努力学习球衣。
我有一个标记为这样的实体类:
@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时,对象o是一个Vector,类型GenericType是一个List,但是到那时,我完全迷失了如何用XML转换对象。
最后,如果球衣及其注释已经提供了所有内容,那么MessageBodyWriter怎么有用?
我再次重申,这只是一个学术练习。
通常,人们会使用MessageBodyWriter来将对象转换为Jersey对其一无所知的数据格式。这是将TableData域对象转换为CSV 的示例:
MessageBodyWriter
TableData
@Singleton @Produces("text/csv") @Provider public class FederationCsvWriter implements MessageBodyWriter<TableData> { @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return TableData.class.isAssignableFrom(type); } @Override public long getSize(TableData data, Class<?> type, Type genericType, Annotation annotations[], MediaType mediaType) { return -1; } @Override public void writeTo(TableData data, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, 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(); } }
在您的示例中,您可以自己检查对象并将结果提供给来创建XML,OutputStream也可以使用JAXB(Jersey内部使用)将对象直接编组到OutputStream。为了您的锻炼目的,JAXB可能更有趣。
OutputStream