How to set and check cookies wih JAX-RS?

You can do the following:

  • To store a new cookie:

    @GET
    @Path("/login")
    @Produces(MediaType.TEXT_PLAIN)
    public Response login() {
        NewCookie cookie = new NewCookie("name", "123");
        return Response.ok("OK").cookie(cookie).build();
    }
    
  • To retrieve the cookie (javax.ws.rs.core.Cookie):

    @GET
    @Path("/foo")
    @Produces(MediaType.TEXT_PLAIN)
    public Response foo(@CookieParam("name") Cookie cookie) {
        if (cookie == null) {
            return Response.serverError().entity("ERROR").build();
        } else {
            return Response.ok(cookie.getValue()).build();
        }
    }
    

    However, you may only want the value:

    @GET
    @Path("/foo")
    @Produces(MediaType.TEXT_PLAIN)
    public Response foo(@CookieParam("name") String value) {
        System.out.println(value);
        if (value == null) {
            return Response.serverError().entity("ERROR").build();
        } else {
            return Response.ok(value).build();
        }
    }
    

By the way, you may want to try the following code:

@GET
@Path("/logout")
@Produces(MediaType.TEXT_PLAIN)
public Response logout(@CookieParam("name") Cookie cookie) {
    if (cookie != null) {
        NewCookie newCookie = new NewCookie(cookie, null, 0, false);
        return Response.ok("OK").cookie(newCookie).build();
    }
    return Response.ok("OK - No session").build();
}

This removes the cookie in the browser. The behavior depends on the implementation of JAX-RS. With RESTEasy (JBoss AS 7.0) and Google Chrome works fine.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)