如何在泽西岛设置 cookie? [英] How to set cookie in Jersey?

查看:28
本文介绍了如何在泽西岛设置 cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I am using jersey jax-rs in myeclipse as backend of my project and jsp as frontend. I want to set cookie from server after successful login. In the jersey's official document, I can only find how to get cookie by jersey. Does anyone can give me a demo to do such things?

This is my login part and I return a response and redirect to URL "/" which means 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();
    }
}

This is my "/" part:

@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:	" + name);
    return Response.ok(new Viewable("/index", model)).build();
}

Every time I run this code, I find that I cannot get cookie from the index part. If you also ever bothered by this question and finally solved it, plz give me some directions, thanks.

解决方案

To set the cookie in your example, you can do something like this:

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

But if you want to redirect to "/" you would also need to return 3xx response instead of 200, for example:

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

这篇关于如何在泽西岛设置 cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆