0

I am designing a REST API using JAX-RS. The endpoint looks like the following:

@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response get(
     @QueryParam("param1") final String param1,
     @QueryParam("param2") final String param2) {
     // Code goes here
} 

I have nearly 7-8 parameters. So I would like to do something like the following:

@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response get(@Context MyContextObject context) {
     // Code goes here
}

And I have the context object as follows:

final class MyContextObject {

    // get methods

    public MyContextObject(final Builder builder) {
        // set final fields
    }

    private final String param1;
    private final String param2; 

    public static final class Builder {
        // builder code goes here
    }
}

Can you please advise how I can do that?

Thanks in advance.

  • I have never used JAX-RS, but it seems like this should be doable. Have you tried it? If so, can you paste the error? I'd suspect you would have to either modify the request JSON/XML to match the new pattern with the wrapper or somehow do a custom de-serializer for it. – CodeChimp Mar 17 '14 at 13:11
  • Maybe this could be of some help http://stackoverflow.com/questions/3047400/using-context-provider-and-contextresolver-in-jax-rs – sergiu Mar 17 '14 at 14:24

1 Answers1

0

If you want to do by creating separate bean class as you said, you would need to get the query parameters in bean class like below.

final class MyContextObject {

// get methods

public MyContextObject(final Builder builder) {
    // set final fields
}

private @QueryParam("param1") final String param1;
private @QueryParam("param2") final String param2;
//and so on...
public static final class Builder {
    // builder code goes here
}
}

If you do so, the query parameters get bounded to these private variables in the bean class and you would get them in your rest service using getters.

King Midas
  • 1,442
  • 4
  • 29
  • 50