【问题标题】:How to set cookie in Jersey?如何在泽西岛设置 cookie?
【发布时间】:2011-11-06 01:35:03
【问题描述】:

我在 myeclipse 中使用 jersey jax-rs 作为我的项目的后端,并使用 jsp 作为前端。我想在成功登录后从服务器设置 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。如果你也被这个问题困扰并最终解决了,请给我一些指导,谢谢。

【问题讨论】:

    标签: jsp cookies jersey


    【解决方案1】:

    要在您的示例中设置 cookie,您可以执行以下操作:

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

    【讨论】:

    • 顺便问一下,当我想从我的网站注销时,你知道如何清理它们(穿着运动衫)吗?
    • 尝试将 cookie 的 maxAge 设置为 0,使用 Response.ok().cookie(new NewCookie("name", null, null, null, null, 0 /*maxAge*/, false)).build()
    • 是的,我正在使用 maxAge 来“清理”它们。我只是想知道是否还有其他方法,例如 xxx.clean() 方法来清理 cookie。无论如何,这个问题已经成功解决了。谢谢你的回答。感谢您的分享。
    猜你喜欢
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    相关资源
    最近更新 更多