2011-08-29 93 views
8

我在myeclipse中使用泽西jax-rs作为我的项目的后端和作为前端的jsp。我想在成功登录后从服务器设置cookie。在球衣的官方文件中,我只能找到如何通过球衣获得cookie。有没有人可以给我演示做这样的事情?如何在泽西岛设置cookie?

这是我的登录部分,我返回一个响应并重定向到URL“/”,这意味着index.jsp。

@Path("/login") 
@POST 
@Consumes("application/x-www-form-urlencoded") 
public Response login(@FormParam("email") String email, 
     @FormParam("password") String password) { 
    Map<String, Object> model = MapFactory.newHashMapInstance(); 
    model.put("email", email); 
    model.put("password", password); 
    loginCheck(model); 
    if (model.get("emailCheck").equals("ok") 
      && model.get("passwordCheck").equals("ok")) { 
     return Response.ok(
       new Viewable("/index", new NewCookie("name", 
         "Hello, world!"))).build(); 
    } else { 
     return Response.ok(new Viewable("/login", model)).build(); 
    } 
} 

这是我的“/”的一部分:

@GET 
@Produces("text/html") 
public Response getIndex(@CookieParam("name") String name) { 
    HashMap<String, Object> model = MapFactory.newHashMapInstance(); 
    model.put("name", name); 
    System.out.println("cookie name:\t" + name); 
    return Response.ok(new Viewable("/index", model)).build(); 
} 

我每次运行此代码,我发现我不能从索引部分得到的cookie。如果你也曾经为这个问题困扰过,并最终解决了这个问题,请给我一些指导,谢谢。

回答

18

要设置在你的榜样饼干,你可以做这样的事情:

return Response.ok(new Viewable("/index", model)) 
       .cookie(new NewCookie("name", "Hello, world!")) 
       .build(); 

但是,如果你想重定向到“/”你还需要返回3xx应答,而不是200,例如:

return Response.seeOther("/") 
       .cookie(new NewCookie("name", "Hello, world!")) 
       .build(); 
+0

顺便说一下,当我想从我的网站注销时,你知道如何清理它们(在泽西岛)吗? – mons

+2

尝试使用Response.ok()。cookie(new NewCookie(“name”,null,null,null,null,0/* maxAge * /,false))。build()将cookie的maxAge设置为0。 ' –

+0

是的,我正在使用maxAge来“清理”它们。我只是想知道是否有其他方法像xxx.clean()方法来清理cookie。无论如何,这个问题已经成功解决了。感谢您的回答。感谢您的分享。 – mons