CORS Support for JavaEE Web Applications

If you’re planning to make your RESTful resource accessible to other domains then you’ll probably want to enable CORS. There are lots of tutorials and open source projects that provide CORS support for Java EE.

CORS Filter

One of those open source project is this little gem called CORS Filter. Its really easy to use. Once you’ve added the 2 JAR (cors-filter.jar, java-property-utils.jar) files to your application, you now need to now configure the CORS filter into your web application.

Lets say you are trying enable CORS for you JAX-RS application rooted at /api (viz. the value of @ApplicationPath), then all you have to do is add the following to your web.xml file

<filter>
   <filter-name>CORS</filter-name>
   <filter-class>
      com.thetransactioncompany.cors.CORSFilter
   </filter-class>
</filter>

<filter-mapping>
   <filter-name>CORS</filter-name>
   <url-pattern>/api/*</url-pattern>
</filter-mapping>

The filter is now configured to add CORS headers to all outgoing responses made to <application_context>/api. There are a host of tweaks to let you tailor the filter to your heart’s content including limiting the origin, tagging request, aging for preflight caches, etc.

During one of my recent projects, I find that I have to explicitly add web.xml just so that I could configure this CORS filter (note: adding the web.xml did not come up in earlier/previous projects because of JSF. This particular project did not use JSF). So I started a little project to use annotation to configure the CORS filter.

@CORS Annotation

My project contains only a single public API/annotation, that is @CORS. Say you decide to CORS enable /api, just annotate any class like so

@CORS({"/api/*"})
public class AClass { …

Here are the list of some of the attributes in @CORS

Attribute Remarks
value, urlPatterns Behaves like @WebFilter#urlPatterns. Use this to configure one or more URL path
initParams This is used to configure the CORS filter. Configurations can be found here.
asyncSupported Enable this for asynchronous operations. This value has to be set to true if the the any of the Servlet and web resources that the CORS filter is rooting supports async. Default value is false.
debugServlet Enable the debug Servlet to display the mappings. Specify a url for the Servlet eg “/cors-debug”.

Implicit Mode – URL Mappings

Another way of using @CORS is to let the annotation figure out what URL patterns should be CORS enable by annotating either a Servlet, JAX-RS application config (@ApplicationPath) or resource (@Path). In the implicit mode, you do not specify the URL mapping in @CORS.

The following example

@CORS
@ApplicationPath("api")
public class AppConfig extends Application { …

will add /api/* to CORS filter. The following table describes how URL paths are determined when using @CORS in implicit mode

Servlet Mapping @CORS
/customer/* /customer/*
/customer /customer
*.do Not mapped
JAX-RS
@ApplicationPath(“api”) /api/*
@Path(“/customer”) /customer
– If resource have any sub resources viz. @Path annotated on any of the method /customer/*
@Path(“/customer/{id}”) /customer/*

Here is another JAX-RS example with sub one sub resource.

@CORS
@RequestScoped
@Path("/customer")
public class CustomerResource {
   …
   @GET
   public Response get() { …

   @Path("{cid}")
   public Response get(@PathParam("cid") String id) {…

The URL that will be enabled for CORS will be /api/customer/* because there is a sub resource (@Path(“{cid}”)) in CustomerResource class.

For JAX-RS you have the option of annotating individual resources or the JAX-RS application config class. In the former’s case, then you are CORS enabling individual resources as in the CustomerResource example from above. You do not need to annotate the application config class. The @CORS annotation will automatically located the application config class and prefix your resource with the path from @ApplicationPath.

If you are annotating the application config class, then it means that you are enabling the entire JAX-RS application eg. /api/*.

Implicit Mode – Asynchronous Operations

One other feature that @CORS support is auto async configuration; by this I mean if a Servlet or JAX-RS resource have either @WebServlet(asyncSupported=…) set to true or injects @Suspended AsyncResponse into a method annotated with any HTTP methods (eg. @GET, @POST), then the deployed CORS filter will support asynchronous operations.

For this to work, you have to annotate either the Servlet or RESTful resource class with @CORS.

If you’re keen to try out this utility, besides downloading cors-filter.jar and java-property-utils.jar, you also have to download cors-filter-annotation.jar. Add the 3 JARS to into your web application.

Till next time.

Advertisements
%d bloggers like this: