简体   繁体   English

如何指定Jersey的REST资源返回的默认MimeType

[英]How can I specify the default MimeType returned by a REST resource with Jersey

I am creating a REST interface and have a resource 'data'. 我正在创建REST接口,并具有资源“数据”。 Now I want that an user can specify whether he wants the data as XML or as JSON. 现在,我希望用户可以指定他希望数据是XML还是JSON。 Therefore I have created two methods for the same path, one produces application/xml, the other produces application/json. 因此,我为同一路径创建了两个方法,一个方法产生application / xml,另一个方法产生application / json。 Everything works fine, but how can I specify what should be returned, if an user doesn't set the 'Accept' header field? 一切正常,但是如果用户未设置“ Accept”标头字段,我如何指定应返回的内容?

My tests have shown that it is not always the same. 我的测试表明,它并不总是相同的。 Yesterday the default was application/xml, today my tests have failed, because as default application/json was returned. 昨天默认值为application / xml,今天我的测试失败了,因为返回了默认的application / json。

How can I specify a default? 如何指定默认值?

Code Snippet: 代码段:

@GET
@Path("/rest/data")
@Produces(MediaType.APPLICATION.XML)
public Object getDataAsXML() {
    // return data in XML format
}

@GET
@Path("/rest/data")
@Produces(MediaType.APPLICATION_JSON)
public Object getDataAsJSON() {
    // return data in JSON format
}

Cheers, 干杯,

metalhamster metalhamster

@Path("/myResource")
@Produces("text/plain")// doGetAsPlainText method defaults to the MIME type of the @Produces annotation at the class level. 
public class SomeResource {
    @GET
    public String doGetAsPlainText() {
        ...
    }

    @GET
    @Produces("text/html")
    public String doGetAsHtml() {
        ...
    }
}

The doGetAsPlainText method defaults to the MIME type of the @Produces annotation at the class level. doGetAsPlainText方法在类级别默认为@Produces批注的MIME类型。 The doGetAsHtml method's @Produces annotation overrides the class-level @Produces setting, and specifies that the method can produce HTML rather than plain text. doGetAsHtml方法的@Produces批注将覆盖类级别的@Produces设置,并指定该方法可以生成HTML而不是纯文本。

@GET
@Produces({"application/xml", "application/json"})
public String doGetAsXmlOrJson() {
    ...
}

The doGetAsXmlOrJson method will get invoked if either of the media types "application/xml" and "application/json" are acceptable. 如果可接受的媒体类型为“ application / xml”和“ application / json”,则将调用doGetAsXmlOrJson方法。 If both are equally acceptable then the former will be chosen because it occurs first. 如果两者均可接受,则将选择前者,因为它首先出现。

@Produce @生产

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM