Cookie的設定
阿新 • • 發佈:2022-05-24
Cookie的設定
當程式第一次載入是不會有cookie;HttpSession會記錄訪問將cookie的id和對應的服務返回形成cookie
package com.msb.cookies; 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; import java.net.CookieStore; @WebServlet(urlPatterns = "/Demo1.do") public class Demo1 extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie age = new Cookie("age", "23"); Cookie name = new Cookie("name", "Mick"); name.setMaxAge(60);//設定cookie的存活時間;在60秒內再次開啟瀏覽器cookie不會清空;即:即使退出賬號也可以登入 resp.addCookie(age); resp.addCookie(name); //獲取cookie Cookie[] cookies = req.getCookies(); if(cookies!=null){ for (Cookie cookie : cookies) { System.out.println(cookie.getName()+"="+cookie.getValue()); } } } }