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

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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?

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

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