Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JAX-RS and HTTP ‘OPTIONS’

DZone's Guide to

JAX-RS and HTTP ‘OPTIONS’

The JAX-RS specification defines sensible defaults for the HTTP OPTIONS command. I actually stumbled upon this by chance!

· Java Zone
Free Resource

Try Okta to add social login, MFA, and OpenID Connect support to your Java app in minutes. Create a free developer account today and never build auth again.

The JAX-RS specification defines sensible defaults for the HTTP OPTIONS command. I actually stumbled upon this by chance! Not sure of this is very obvious (if it is, be kind and don’t laugh at me !)

The Discovery

For the JAX-RS resource represented in the code snippet below, if you execute a HTTP OPTIONS command against the http://host:port/context-root/user URI, you will be surprised to not get a HTTP Status 404 – Not Found error message [ at least I was surprised, until I looked in the JAX-RS specification document of course ;-) ]

@Path("user")
public class UserResource {

    @GET
    @Path("{id}")
    public Response find(@PathParam("id") String id) {
        return Response.ok().build();
    }

    @PUT
    public Response create(/*User user*/) {
        return Response.ok().build();
    }

    @DELETE
    @Path("{id}")
    public Response delete(@PathParam("id") String id) {
        return Response.ok().build();
    }
}


It gave me back the WADL as a response. Sweet ! :-)

WADL returned by the JAX-RS runtime


To Be Noted

  • If there is an explicit resource method which is annotated with @OPTIONS, then the corresponding logic will be executed and the default behavior would get suppressed (now that’s obvious!)
  • This does not mean that you can execute the OPTIONS command at any random URI within your RESTful app. This kicks in after the request matching process and will be applicable only for a valid URI as defined by @Path annotations in your resource classes.
  • I tested with Jersey 2.10 on Glass Fish 4.1. This is standard feature mandated by the specification, hence it is applicable to ANY JAX-RS compliant implementation out there (e.g. RESTEasy)


Build and launch faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:
http ,jax-rs ,rest ,java

Published at DZone with permission of Abhishek Gupta, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}