JAX-RS: OPTIONS for every Resource

痴心易碎 提交于 2019-12-23 07:22:37

问题


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();
}

回答1:


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
@PermitAll
public Response options() {
    return Response.status(Response.Status.NO_CONTENT).build();
}

// Match sub-resources
@OPTIONS
@Path("{path:.*}")
@PermitAll
public 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.



回答2:


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())
        }
    }
}


来源:https://stackoverflow.com/questions/20404661/jax-rs-options-for-every-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!