简体   繁体   中英

Specifying @Produces wildcard handling in JAX-RS

Assume a class:

public class MyResource {

    @Path("/thing")
    public String getThing() {
        // returns HTML
    }

    @Path("/thing")
    @Produces(MediaType.APPLICATION_JSON)
    public String getThingJSON() {
        // returns JSON
    }
}

How can I have requests with a header of Accept: */* be handled by getThing() ? At the moment having a wildcard accept header results in getThingJSON() getting called. If I have an accept header of Accept: text/html then getThing() gets called.

I ran into the same issue, where I have to methods with a specific @Produces() annotations. This trick works:

@Path("/thing")
public String getThing() {}

@Path("/thing")
@Produces({MediaType.APPLICATION_JSON, "*/*;q=0"})
public String getThingJSON() {}

When using MIME types, you can add the q property, which indicates priority (0 to 1). The absence of the q property implies 1, but apparently the q=0 tricks Jersey to use the other function.

It's kind of a hack, so I don't know if it will remain working, but helped me out.

Try adding a @Produces({MediaType.WILDCARD})

to getThing()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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