如何在泽西岛设置cookie? [英] How to set cookie in Jersey?
问题描述
我在myeclipse中使用jersey jax-rs作为项目的后端,而在jsp中使用前端.成功登录后,我想从服务器设置cookie.在球衣的官方文档中,我只能找到如何通过球衣获取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?
这是我的登录部分,我返回响应并重定向到URL"/",这意味着index.jsp.
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();
}
}
这是我的"/"部分:
@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.如果您也对此问题感到困扰并最终解决了,请给我一些指示,谢谢.
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.
推荐答案
要在示例中设置Cookie,您可以执行以下操作:
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();
但是,如果要重定向到"/",则还需要返回3xx响应而不是200,例如:
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屋!