Cookie入门案例及其注意事项
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/CookieDemo1")
public class CookieDemo1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie cookie=new Cookie("mand","hello");
Cookie cookie1=new Cookie("name","zhangsan");
/* 注意:
1.cookie的存活时间:
setMaxAge() 表示给cookie设置存活时间,
正数:持久化存储在硬盘存活时间
0:删除cookie信息
负数:
2.cookie支持传入多个cookie对象
3.cookie tomcat8.x之后的版本支持cookie传入中文数据
tomcat8.x之前的版本需要把中文转码。此处不再演示
4.cookie的共享问题:
默认情况:不共享
setPath()方法设置cookie的获取范围
如果想要共享。需要在path方法里面设置"\"
*/
cookie.setMaxAge(30);
cookie1.setMaxAge(30);
cookie.setPath("/");
response.addCookie(cookie);
response.addCookie(cookie1);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
接收cookie信息案例
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/CookieDemo2")
public class CookieDemo2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 接收cookie信息
Cookie[] cookies = request.getCookies();
// 遍历接收的cookie信息
if (cookies!=null) {
for (Cookie c:cookies){
String name = c.getName();
String value = c.getValue();
System.out.println(name+" "+value);
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}