1. 程式人生 > >JSP:Cookie的建立,讀取,設定時期和刪除

JSP:Cookie的建立,讀取,設定時期和刪除

比較簡單,主要為了個人記憶和查詢

<%@ page language="java" contentType="text/html; charset=GB18030"
	pageEncoding="GB18030"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="GB18030">
<title>Insert title here</title>
</head>
<body>
	<%
		String username = request.getParameter("name1");		//建立Cookie
		Cookie user_name = new Cookie("cookie_name", username);
		response.addCookie(user_name);
		out.print(username);
	%>
	<%
		Cookie[] Cookies = request.getCookies();		//讀取Cookie
		if (Cookies == null) {
			out.print("none any Cookie");
		} else {
			for (int i = 0; i < Cookies.length; i++) {
				if (Cookies[i].getName().equals("cookie_name")) {
					out.println(Cookies[i].getValue() + "<br>");
				}
			}
		}
	%>
	<%
		Cookie login = new Cookie("today", "true");   //設定Cookie的存在時間
		login.setMaxAge(86400);
		response.addCookie(login);
	%>
	<%
		Cookie killMyCookie = new Cookie("mycookie", null);		//刪除Cookie
		killMyCookie.setMaxAge(0);
		killMyCookie.setPath("/");
		response.addCookie(killMyCookie);
	%>
</body>
</html>