O'Reilly logo

Java SOA Cookbook by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Working with Cookies

Problem

You want your JAX-RS service to set and accept an HTTP cookie.

Solution

Use the @CookieParam annotation on your method parameters.

Discussion

All of the parameter types in JAX-RS work by injection. You can simply add a parameter to your business method that is of the appropriate type (HeaderParam, CookieParam, FormParam, etc.), and the runtime will inject the value so you can work with it locally.

Example 8-29 demonstrates the setting and reading of a cookie.

Example 8-29. CookieService.java

package com.soacookbook.rest.cookie;

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.Cookie;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;

@Path("/cookie")
@Produces("text/html") 
public class CookieService {
  
    //set cookie on home page
    @GET
    @Path("/home")
    public Response home() {
        
        System.out.println("Home page.");
        
        //create a cookie object
        NewCookie cookie = new NewCookie("MY_KEY", "MY_VALUE");
        
        String html = "<html><body><a href='step2'>Click</a> " +
            "to go to the next step.</body></html>";
        
        //include cookie in 200 OK response
        Response response = Response.ok(html).cookie(cookie).build();
        
        System.out.println("Built response.");
        
        return response;
    }
    
    //retrieve cookie previously set
    @GET
    @Path("/step2")
    public String step2(@CookieParam("MY_KEY") Cookie cookie) {
        
        System.out.println("Step 2.");
        
        String html = "";
        
        if (cookie != null) {
            System.out.println("Cookie Name: " + cookie.getName()); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required