如何使用jersey编写XML MessageBodyWriter提供程序 [英] How to write an XML MessageBodyWriter provider with jersey

查看:107
本文介绍了如何使用jersey编写XML MessageBodyWriter提供程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我并不是特别想解决任何问题,而是我正在学习球衣的路径。

I am not trying to solve any problem in particular, but rather I am on a learning path to jersey.

我有一个标记为这样的实体类:

I have an entity class marked like this:

@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响应,我怎么能这样做?

Which give a correct XML response. Supposing I want to write a MessageBodyWriter which replicate same behavior, which is producing an XML response, how could I do that ?

@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标记注释我可以看到正确调用了消息体编写器。

by marking with @Provider annotation I can see the message body writer is correctly invoked.

当调用writeTo时,Object o是Vector,Type genericType是List,但此时我完全是迷失了如何用XML转换对象。

When writeTo is invoked, Object o is a Vector and Type genericType is a List but at this point I am completely lost on how I could transform the object in XML.

L. ast,如果一切都已经由泽西及其注释提供,MessageBodyWriter如何有用呢?

Last, if everything is already provided by jersey and its annotations, how can a MessageBodyWriter be useful ?

再次,我重申这只是一个学术练习。

Again, I am repeating that this is just an academic exercise.

推荐答案

通常会使用 MessageBodyWriter 将对象转换为Jersey的数据格式什么都不知道。以下是将 TableData 域对象转换为CSV的示例:

Typically one would use a MessageBodyWriter to convert objects to data formats that Jersey knows nothing about. Here's an example of translating a TableData domain object to CSV:

@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 c $ c> OutputStream 或者您可以使用JAXB(Jersey内部使用)将对象直接编组到 OutputStream 。出于您的目的练习JAXB可能更有趣。

In your example you could either create XML by inspecting the object yourself and feeding the result to the OutputStream or your could use JAXB (which Jersey uses internally) to marshall the objects directly to the OutputStream. For the purposes of your exercise JAXB is probably more interesting.

这篇关于如何使用jersey编写XML MessageBodyWriter提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆