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

Supporting CORS in JAX-RS 2/Java EE 7

DZone's Guide to

Supporting CORS in JAX-RS 2/Java EE 7

· Java Zone ·
Free Resource

The CMS developers love. Open Source, API-first and Enterprise-grade. Try BloomReach CMS for free.

Many developers, especially more inexperienced ones, don't seem to realize that browsers automatically enforce the well-known same-origin policy. This means that browsers will make sure that any scripts (likely JavaScript :-)) can only access URLs on the same server that the script came from. For most applications this is not an issue. However, in some deployment scenarios (e.g. JavaScript clients on a plain web server trying to access REST resources on a separate back-end application server) this can be a real and unexpected problem. The solution to this problem is CORS or Cross-Origin Resource Sharing. If you are not familiar with CORS, you should read the detailed write-up here. Essentially using CORS a server side resource indicates that it is explicitly allowing an exception to the same-origin policy.

JAX-RS users should ask how they can handle CORS if the need arises. The answer to this question is that while most JAX-RS providers may not yet support CORS out of the box, it is pretty easy to handle this yourself using JAX-RS 2 server-side filters. Max Lam does a very nice job showing you how in a code-intensive blog entry. The entry is actually a nice demonstration of JAX-RS 2 filters in action in the real world.

Perhaps JAX-RS 2.1 could explore built-in CORS support as a possibility?

BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}