首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在不同的servlet中添加和读取cookies

如何在不同的servlet中添加和读取cookies
EN

Stack Overflow用户
提问于 2014-04-02 20:47:33
回答 2查看 145关注 0票数 0

从index.html页面中的一个表单(您可以在其中写下年龄和姓名),我能够(使用POST)调用我的servlet01,它测试我是成年人还是未成年人(如果年龄小于...,则只需编写类似out.println(“您是成年人”)或out.println(“您是未成年人”)之类的内容。)

现在我必须更改servlet01:它应该记住与cookie相同的信息(年龄和姓名),并且: a)当用户是成年人时,servlet01也应该要求插入地址。地址需要保存在另一个cookie上,始终使用servlet01并生成一个报告,其中显示姓名、年龄和地址;

Servlet02应该读取cookies (年龄和姓名)并说“用户名:”+姓名+“年龄:”+年龄+“你是未成年人”

这就是我所做的: servlet01 http://pastebin.com/aFMSkeZ4

servlet02 http://pastebin.com/YqMZpqJd

EN

回答 2

Stack Overflow用户

发布于 2014-04-02 21:18:47

每个HttpServletRequest都有一个Cookie对象数组;您可以使用request.getCookies()访问它们。

通过迭代此数组,您可以找到之前根据其name填充的cookie,然后读取其value

设置cookie的方法是使用response.addCookie(...)将cookie添加到响应中。

票数 0
EN

Stack Overflow用户

发布于 2014-04-02 21:32:58

要添加新的cookie,您可以使用如下方法:

代码语言:javascript
复制
public void setCookie(HttpServletRequest request, HttpServletResponse response){
    final String cookieName = "my_cool_cookie";
    final String cookieValue = "my cool value here !";  // you could assign it some encoded value
    final Boolean useSecureCookie = new Boolean(false);
    final int expiryTime = 60 * 60 * 24;  // 24h in seconds
    final String cookiePath = "/";

    Cookie myCookie = new Cookie(cookieName, cookieValue);
    cookie.setSecure(useSecureCookie.booleanValue());  // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL
    cookie.setMaxAge(expiryTime);  // A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.
    cookie.setPath(cookiePath);  // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories
    response.addCookie(myCookie);
}

要读取Cookie值,您可以使用:

代码语言:javascript
复制
Cookie[] cookies = request.getCookies();

for (int i = 0; i < cookies.length; i++) {
  String name = cookies[i].getName();
  String value = cookies[i].getValue();
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22812012

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档