我是 REST Web 服务的初学者。
我编写了一个 REST 程序来显示 HTML 或 XML。 @Path 注释的值为 @Path("{typeDocument}")
。 GET 有两种方法:
@GET
@Produces(MediaType.TEXT_XML)
public String getXml(@PathParam("typeDocument") String typeDocument)
显示 XML 文件, 和
@GET
@Produces(MediaType.TEXT_HTML)
public String getHtml(@PathParam("typeDocument") String typeDocument)
显示 HTML。
当 URL 为以下任一情况时,Firefox 浏览器总是执行 getHtml()
http://localhost:8080/sources/html或http://localhost:8080/sources/xml
但 IE 总是执行 getXml()
。
如何在不同的浏览器中执行URL定义的正确方法?
最佳答案
尝试使用 MediaType.APPLICATION_XML 而不是 TEXT_XML。
话虽如此,这并不是 JAX-RS 的最佳用途 - 特别是如果您使用 RestEASY 或任何其他支持 JAXB 的实现。
@GET
@Produces(MediaType.APPLICATION_XML)
@Path("/{typeDocument}")
public MyObject getXml(@PathParam("typeDocument") String typeDocument) {
myObjectService.get(typeDocument);
}
@XmlRootElement(name="myObject")
public class MyObject {
// Some properties
}
将是一种更容易维护的方法。您还可以将 JSP 用于 HTML。
参见http://java.dzone.com/articles/resteasy-spring一个很好的例子(使用 Spring)。
关于java - REST 的媒体类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2964387/