jsp - 如何在 Jersey 设置cookie?

标签 jsp cookies jersey

我在myeclipse中使用jersey jax-rs作为项目的后端,而在jsp中用作前端。成功登录后,我想从服务器设置cookie。在 Jersey 的官方文档中,我只能找到如何通过 Jersey 获取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。如果您也对此问题感到困扰并最终解决了,请给我一些指示,谢谢。

最佳答案

要在示例中设置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();

关于jsp - 如何在 Jersey 设置cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7231156/

相关文章:

java - 有没有办法告诉 servlet 容器一次生成一个资源实例?

java - spring-security oauth2 REST 服务器在错误凭据(400)错误响应中不需要的 Stacktrace

java - 我可以导入 Jersey 1 和 Jersey 2 并在不同的类中使用不同的导入吗?

javascript - 在 jsp 中使 div 不可刷新(不使用 AJAX)

jsp - 如何安装 JSTL?绝对uri : http://java. sun.com/jSTL/core 无法解析

firefox - 如何制作在 Firefox session 中使用的 cookie?

javascript - 如何从在javascript,asp.net mvc3中设置的cookie中获取键值

c# - 从 Tomcat 到 ASP.Net 的 session 传输问题

java - 文件对话框中可接受的扩展名

java - 未使用 HttpUrlConnection 设置 Cookie