从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
发布于 2014-04-02 21:18:47
每个HttpServletRequest都有一个Cookie对象数组;您可以使用request.getCookies()访问它们。
通过迭代此数组,您可以找到之前根据其name填充的cookie,然后读取其value。
设置cookie的方法是使用response.addCookie(...)将cookie添加到响应中。
发布于 2014-04-02 21:32:58
要添加新的cookie,您可以使用如下方法:
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值,您可以使用:
Cookie[] cookies = request.getCookies();
for (int i = 0; i < cookies.length; i++) {
String name = cookies[i].getName();
String value = cookies[i].getValue();
}https://stackoverflow.com/questions/22812012
复制相似问题