1、应用
Http是无状态协议,服务器不能记录浏览器的访问状态,也就是说服务器不能曲风两次请求是否由一个客户端发出。
Cookie实际上就是服务器保存在浏览器上的一段信息,浏览器有了Cookie之后,每次向服务器发送请求都会同时将该信息发送给服务器,服务器收到请求后,就可以根据该信息处理请求。
2、运行原理
1、第一次向服务器发送请求的时候在服务器端创建一个cookie对象
2、将cookie对象发送给浏览器
3、以后浏览器再发送请求就会携带者该cookie 对象
4、服务器根据不同的cookie对象来区分不同的用户
3、示例
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/CreateCookie">CreateCookie</a><br>
<a href="${pageContext.request.contextPath}/GetCookies">GetCookie</a><br>
</body>
</html>
CreateCookie.java
package servlet;
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;
/**
* 创建Cookie
*/
public class CreateCookie extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1、创建Cookie对象
//不能使用中文
Cookie cookie = new Cookie("user", "admin");
Cookie cookie2 = new Cookie("user1", "path");
//设置cookie的持久化时间为...s
//设置cookie的持久化时间(age)为...s
//age>0 为cookie对象age秒后失效
//age=0 为cookie对象直接失效
//age<0 默认,会话级别的cookie
cookie2.setMaxAge(60);
cookie2.setPath(request.getContextPath()+"/pages");
//设置Cookie对象的有效路径,即访问什么路径的时候会携带Cookie,默认是项目的根目录
//2、发送Cookie
response.addCookie(cookie);
response.addCookie(cookie2);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
GetCookies.java
package servlet;
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;
/**
* 获取Cookies
*/
public class GetCookies extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取Cookies
Cookie[] cookies = request.getCookies();
if(cookies!=null) {
//遍历每一个cookie对象
for(Cookie cookie:cookies) {
//获取cookie的name
String name = cookie.getName();
//获取cookie的value
String value = cookie.getValue();
System.out.println("cookie's name is "+ name + ", it's value is " + value+".");
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}