java REST 的媒体类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2964387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 23:43:23  来源:igfitidea点击:

MediaType of REST

javarestjax-rs

提问by wonder garance

I am beginner in REST web services.

我是 REST Web 服务的初学者。

I wrote a program of REST to display the HTML or XML. The @Path annotation's value is @Path("{typeDocument}"). There are two methods for GET :

我写了一个 REST 程序来显示 HTML 或 XML。@Path 注释的值为@Path("{typeDocument}")。GET 有两种方法:

@GET
@Produces(MediaType.TEXT_XML)
public String getXml(@PathParam("typeDocument") String typeDocument)

to display XML file, and

显示 XML 文件,以及

@GET
@Produces(MediaType.TEXT_HTML)
public String getHtml(@PathParam("typeDocument") String typeDocument)

to display HTML.

显示 HTML。

The browser Firefox always excutes getHtml() when URL is either

当 URL 为

http://localhost:8080/sources/htmlor http://localhost:8080/sources/xml

http://localhost:8080/sources/htmlhttp://localhost:8080/sources/xml

But IE always excutes getXml().

但 IE 总是执行getXml()

How to excute the correct method, as defined by URL, in different browser ?

如何在不同的浏览器中执行由 URL 定义的正确方法?

回答by Robert Wilson

try using MediaType.APPLICATION_XML instead of TEXT_XML.

尝试使用 MediaType.APPLICATION_XML 而不是 TEXT_XML。

That being said, this isn't the best use of JAX-RS - especially if you're using RestEASY or any other implementation with JAXB support.

话虽如此,这并不是 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
}

would be a much easier method to maintain. You can also use JSPs for the HTML.

将是一种更容易维护的方法。您还可以将 JSP 用于 HTML。

See http://java.dzone.com/articles/resteasy-springfor a good example (using Spring).

有关一个很好的示例(使用 Spring),请参见http://java.dzone.com/articles/resteasy-spring