JAX-RS @CookieParam Annotation Example with RESTEasy 3
March 09, 2015
In this page, we will learn JAX-RS @CookieParam annotation example with RESTEasy 3. @CookieParam binds the HTTP cookie into a resource method parameter. The JAX-RS method parameter can be a
1. Primitive type
2. JAX-RS Cookie Class
3. A class with constructor with single string argument.
4. A class with static method named as valueOf with one string argument.
5. Using registered implementation of javax.ws.rs.ext.ParamConverterProvider
For more detail find the JAX-RS doc.
Here we will show demo for some scenarios discussed above. We are creating two classes as below.
UserDataOne.java
package com.concretepage; public class UserDataOne { private String sessionId; public UserDataOne(String sessionId){ this.sessionId = sessionId; } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } }
UserDataTwo.java
package com.concretepage; public class UserDataTwo { private static String data; public static String getSessionId() { return data; } public static void valueOf(String sessionId){ data = sessionId; } }
EmployeeService.java
package com.concretepage; import java.util.HashMap; import java.util.Map; import javax.ws.rs.CookieParam; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import org.jboss.resteasy.annotations.providers.jackson.Formatted; @Path("/cookie") public class EmployeeService { @GET @Path("/oneway") @Produces("application/json") @Formatted public Response oneWay(@CookieParam("sessionid") String userAgent ) { Map<String,String> map = new HashMap<String,String>(); map.put("sessionid", userAgent); return Response.ok(map).build(); } @GET @Path("/secondway") @Produces("application/json") @Formatted public Response secondWay(@CookieParam("sessionid") UserDataOne data) { return Response.ok(data).build(); } @GET @Path("/thirdway") public Response thirdWay(@CookieParam("sessionid") UserDataTwo data) { return Response.ok(UserDataTwo.getSessionId()).build(); } }
Output
If our application is setting cookie named as sessionid, then we can use below URL to test the application.1. http://localhost:8080/concretepage-1/employee/cookie/oneway
2. http://localhost:8080/concretepage-1/employee/cookie/secondway
3. http://localhost:8080/concretepage-1/employee/cookie/thirdway