Demo03 :
package com.test.cookie;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Demo03
* 设置cookie有效期及cookie常用方法
*/
public class Demo03 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.发送客户端 可以给客户端返回多个cookie
Cookie cookie = new Cookie("name", "lisi");
response.addCookie(cookie);
Cookie cookie1 = new Cookie("sex", "men");
response.addCookie(cookie1);
//2.获取带客户端的数据
Cookie[] cookies = request.getCookies();
if(cookies != null){
for (Cookie cookie2 : cookies) {
System.out.println(cookie2.getName()+"="+cookie2.getValue());
}
}
//3.cookie的有效期.默认情况下 7天
//关闭浏览器后,cookie不存在.----->没有设置cookie的有效期
/**expiry(有效) 以秒为单位
* getMaxAge():返回以秒为单位的cookie的最大生存时间,默认情况下,-1表示该cookie将保留到浏览器关闭位置.
* setMaxAge():以秒为单位
* 正值表示cookie将在经过该值表示的秒数后过期.注意:该值是cookie过期的最大生存时间,不是cookie的当前生存时间.
* 负值表示cookie不会被持久存储,将在web浏览器退出时删除.0会导致删除cookie[关闭浏览器,cookie就失效.默认值-1]
*/
//有效期设为7天
cookie.setMaxAge(60 * 60 * 24 * 7);
/**
* 扩展(常用的几个方法):
* 赋值新的值 cookie.setValue(newValue);
* 用于指定只有请求了指定的域名,才回带上该cookie.setDomain(domain);
* 只有访问该域名下的 uri 这个路径才会带cookie cookie.setPath(uri);
*/
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>CookieDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>Demo01</display-name>
<servlet-name>Demo01</servlet-name>
<servlet-class>com.test.cookie.Demo01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Demo01</servlet-name>
<url-pattern>/Demo01</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>Demo02</display-name>
<servlet-name>Demo02</servlet-name>
<servlet-class>com.test.cookie.Demo02</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Demo02</servlet-name>
<url-pattern>/Demo02</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>Demo03</display-name>
<servlet-name>Demo03</servlet-name>
<servlet-class>com.test.cookie.Demo03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Demo03</servlet-name>
<url-pattern>/Demo03</url-pattern>
</servlet-mapping>
</web-app>
访问: