可能值得研究Jersey。 Jersey 可以轻松地将 restful web 服务公开为 xml 和/或 JSON。
一个例子...从一个简单的类开始
@XmlType(name = "", propOrder = { "id", "text" })
@XmlRootElement(name = "blah")
public class Blah implements Serializable {
private Integer id;
private String text;
public Blah(Integer id, String text) {
this.id = id;
this.text = text;
}
@XmlElement
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
@XmlElement
public String getText() { return text; }
public void setText(String value) { this.text = value; }
}
然后创建一个资源
@Path("/blah")
public class BlahResource {
private Set<Blah> blahs = new HashSet<Blah>();
@Context
private UriInfo context;
public BlahResource() {
blahs.add(new Blah(1, "blah the first"));
blahs.add(new Blah(2, "blah the second"));
}
@GET
@Path("/{id}")
@ProduceMime({"application/json", "application/xml"})
public Blah getBlah(@PathParam("id") Integer id) {
for (Blah blah : blahs) {
if (blah.getId().equals(id)) {
return blah;
}
}
throw new NotFoundException("not found");
}
}
并暴露它。有很多方法可以做到这一点,例如使用 Jersey 的 ServletContainer。 (web.xml)
<servlet>
<servlet-name>jersey</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
这就是您需要做的一切...弹出浏览器并浏览到http://localhost/blah/1。默认情况下,您将看到 XML 输出。如果您使用的是 FireFox,请安装 TamperData 并将您的 accept 标头更改为 application/json 以查看 JSON 输出。
显然还有更多内容,但Jersey 让所有这些事情变得非常简单。
祝你好运!