如何设置和检查JAX-RS的cookie?

我是RESTful API的noobie,我正在尝试构建一个Login服务,我在其中提供电子邮件和密码,如果validation成功,则存储cookie。 另外,我如何检查cookie(如果存储)?

怎么能实现这一目标?

@Path("/login") @POST @Produces(MediaType.APPLICATION_JSON) @Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON}) public Response Login(final String i_LoginDetails) throws JSONException { final JSONObject obj = new JSONObject(i_LoginDetails); try { if (isValidUser(obj.getString("email"), obj.getString("password"))) { // Set a cookie } else { // return error invalid-credentials message } } catch (Exception e) { e.printStackTrace(); } return Response.ok("TEST").build(); } 

我如何检查cookie(如果设置)?

您可以执行以下操作:

  • 要存储新cookie:

     @GET @Path("/login") @Produces(MediaType.TEXT_PLAIN) public Response login() { NewCookie cookie = new NewCookie("name", "123"); return Response.ok("OK").cookie(cookie).build(); } 
  • 要检索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(); } } 

    但是,您可能只想要这个值:

     @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(); } } 

顺便说一下,您可能想尝试以下代码:

 @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(); } 

这将删除浏览器中的cookie。 行为取决于JAX-RS的实现。 使用RESTEasy(JBoss AS 7.0)和谷歌浏览器工作正常。