Matthew Buckett
Matthew Buckett

Reputation: 4371

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.

Upvotes: 3

Views: 2248

Answers (2)

Peter
Peter

Reputation: 630

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.

Upvotes: 3

El Guapo
El Guapo

Reputation: 5781

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

to getThing()

Upvotes: -1

Related Questions