JAX-RS: OPTIONS for every Resource

Viewed 7719

I am using a JAX-RS interface with XMLHttpRequest (XHR). Due to the XHR preflight, XHR send always OPTIONS before calling the real resource.

Now I have dozens of methods and I need the OPTIONS for every resoruce. Is there any way to do this automatically? I dont want to write dozens of methods like:

@OPTIONS
@Path("/{id}")
@PermitAll
public Response optionsById() {
    return Response.status(Response.Status.NO_CONTENT).build();
}

@OPTIONS
@Path("/{id}/data")
@PermitAll
public Response optionsByData() {
    return Response.status(Response.Status.NO_CONTENT).build();
}
3 Answers

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 @PreMatching
class OptionsFilter: ContainerRequestFilter {
    override fun filter(requestContext: ContainerRequestContext) {
        if (requestContext.method == "OPTIONS") {
            requestContext.abortWith(Response.status(Response.Status.NO_CONTENT).build())
        }
    }
}

The java version:

@Provider
@PreMatching
public 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());
        }
    }
}
Related