JAX-RS: OPTIONS for every Resource
UPDATE 09/12/2013: THIS DOES NOT WORK. Using this all @GET/@DELETE/@POST/@PUT are not working any more.
Finally I solved my problem. I created a super class OptionsResource
, from which all resources inherit. This resoruce contains:
// Match root-resources@OPTIONS@PermitAllpublic Response options() { return Response.status(Response.Status.NO_CONTENT).build();}// Match sub-resources@OPTIONS@Path("{path:.*}")@PermitAllpublic Response optionsAll(@PathParam("path") String path) { return Response.status(Response.Status.NO_CONTENT).build();}
An example:
@Path("/test")public class TestResource extends OptionsResource { @GET @Produces("text/plain;charset=UTF-8") public Response index() { return Response.status(Status.OK).entity("works").build(); }}
This matches:
- curl -I -X OPTIONS http://myhost.com/test
- curl -I -X OPTIONS http://myhost.com/test/asd/aasd/12/
- etc.
Quite a late reply, but a much nicer solution is to use a filter that catches all the OPTIONS call before path matching. In Kotlin, it will look like this:
@Provider @PreMatchingclass OptionsFilter: ContainerRequestFilter { override fun filter(requestContext: ContainerRequestContext) { if (requestContext.method == "OPTIONS") { requestContext.abortWith(Response.status(Response.Status.NO_CONTENT).build()) } }}
The java version:
@Provider@PreMatchingpublic class OptionFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { if (requestContext.getMethod().contentEquals("OPTIONS")) { requestContext.abortWith(Response.status(Response.Status.NO_CONTENT).build()); } }}