2011-08-29 95 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