I wonder if it\'s possible with JAX-RS to route a request using an header in addition to the HTTP method. In fact, I can\'t find out the way to do that.
I thought ab
Just throw in another option. You can also use Sub-resource locators, which give us some control over the chosen resource (and is part of the JAX-RS spec). For example
@Path("contacts")
public class ContactsResource {
@Path("/")
public AbstractHeaderResource doSomething(@HeaderParam("X-Header") String xHeader) {
if ("RequiredValue".equals(xHeader)) {
return new WithHeaderResource();
}
return new WithOutHeaderResource();
}
public static abstract class AbstractHeaderResource {
@POST
@Consumes(MediaType.APPLICATION_JSON)
public abstract Response doSometing(Contact contact);
}
public static class WithHeaderResource extends AbstractHeaderResource {
@Override
public Response doSometing(Contact contact) {
return Response.ok("*** With Header ***").build();
}
}
public static class WithOutHeaderResource extends AbstractHeaderResource {
@Override
public Response doSometing(Contact contact) {
return Response.ok("*** WithOut Header ***").build();
}
}
}
Test
C:\>curl -v -X POST
-d "{\"name\":\"Peeskillet\"}"
-H "X-Header:RequiredValue"
-H "Content-Type:application/json"
http://localhost:8080/contacts
*** With Header ****
C:\>curl -v -X POST
-d "{\"name\":\"Peeskillet\"}"
-H "Content-Type:application/json"
http://localhost:8080/contacts
*** WithOut Header ****
The resource methods don't have to accept the same parameter type. I did it just for brevity. You can have the sub resource classes extend an empty abstract class or interface (just for typing), and create the methods however you want
If you need to affect the request matching/routing process, you have to use JAX-RS filters - PreMatching filters to be specific (@PreMatching) [this will work in JAX-RS 2.0 onwards] If the use header info in the resource methods, it wont make sense because JAX-RS would have already matched the method
Here is the overall flow in filter implementation
Jersey docs might help -- https://jersey.java.net/documentation/latest/filters-and-interceptors.html#d0e9538