[JAX-RS] Access-Control-Allow-Origin as a Filter

So if you’re getting the Access-Control-Allow-Origin error in chrome. Then you need to be sending those headers with the response from the server. One solution would be to put it in the Response in each method. A better (and more scalable) solution is to use a filter. Then don’t forget to disable it in production.

[JAX-RS] Use @Provider to leverage JAX-RS provider auto-discovery feature.

There are at least 2 ways to register a JAX-RS resource such as a set of web methods or the filters. 1. The first and the verbose way is to override the getClasses method in a subclass of Application. Like this:

The drawback with this approach is that you have to explicitly add all…

[JAX-RS] Some good auth resources

http://stackoverflow.com/questions/26777083/best-practice-for-rest-token-based-authentication-with-jax-rs-and-jersey http://www.developerscrappad.com/1814/java/java-ee/rest-jax-rs/java-ee-7-jax-rs-2-0-simple-rest-api-authentication-authorization-with-custom-http-header/ https://jersey.java.net/documentation/latest/security.html https://www.ibm.com/support/knowledgecenter/SSAW57_8.5.5/com.ibm.websphere.nd.doc/ae/twbs_jaxrs_impl_securejaxrs_webcont.html      

[JAX-RS] Implementing custom MessageBodyWriter for serialization

Say you want to serialize your object in a custom format. For XML you can use JAXB, for JSON you can use Jackson. But in case you have your own specific format, you need to implement your own MessageBodyWriter. 1. Maven web application – pom.xml (here jersey 1.19, feel free to upgrade):

  2….

[JAX-RS] ExceptionMapper example (Maven + Jersey + Glassfish)

Create a new Maven project (Web app archetype) in eclipse and add the dependencies on jersey. Also you will need Glassfish server. 1. pom.xml

2. Main Application

3. An example service

4. The Exception Mapping class. Here we’re mapping the IllegalArgumentException to a BAD_REQUEST

 

[JAX-RS] Using CDI for dependency injection in JAX-RS

1. The resource class

  2. MyService interface

3. MyServiceImpl

4. web.xml (under /WEB-INF/)

5. beans.xml (under /WEB-INF/)

6. Deploy on glassfish! and access it: http://localhost:8080/TestCDI/rest/cdiexample (given that the project name is TestCDI).

[JAX-RS] 3 ways to get cookies

These are 3 ways to obtain cookies values in JAX-RS [code language=”java”] package com.example; import javax.ws.rs.CookieParam; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.HttpHeaders; @Path("/k") public class CookieResource { @GET public String get(@CookieParam("customerId") int custId) { return "Customer ID was " + custId; } @GET @Path("object") public String getAnother(@CookieParam("customerId") Cookie customerId) { if…

[JAX-RS] Simplest possible web service (on Tomcat)

1. SimpleService

2. pom.xml

3. Layout