服务端创建CookieServlet, 返回cookie给客户端:
package com.king;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
public class CookieServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("ParamServlet doGet -------");
Cookie[] cookies = req.getCookies();
if (cookies == null || cookies.length == 0) {
System.out.println("No Cookies");
Cookie co = new Cookie("user", "normal");
co.setMaxAge(3600);
resp.addCookie(co);
}
PrintWriter out = resp.getWriter();
out.println("<h1>CookieTest</h1>");
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
doGet(req, resp);
}
}
抓包, 结果就是: 浏览器会保存cookie信息, 下次再访问CookieServlet时, 会把cookie信息带上,如下: