쿠키 케이스 코드

예 1: 서블릿에서 클라이언트로 쿠키 저장

//SetCookie Servlet
Cookie c=new Cookie("season","spring");
c.setMaxAge(30);
response.addCookie(c);
Cookie d=new Cookie("nextseason","summer");
d.setMaxAge(10);
response.addCookie(d);

예 2: 클라이언트 측에서 쿠키 읽기

//getCookie.jsp
<%
Cookie[] a=request.getCookies();
for(int i=0;i<a.length;i++)
{
out.println(a[i].getName()+“:"+a[i].getValue()+"<br>");
}
%>

예 3: 쿠키 계산 사용

//visitCount.jsp计数次数
<%@ page contentType="text/html;charset=UTF-8" %>
<%int count = 0; 
 Cookie[] cookies = request.getCookies(); / / 得到所有的Cookie
if(cookies != null) { 
   for(int i=0; i<cookies.length; i++) {
       if(cookies[i].getName().equals("Counter"))
            count = Integer.parseInt(cookies[i].getValue());  //获取Counter以前值
   }  }
count++;
if(count == 1)
   out.println("欢迎首次光临");
else 
  out.println("您已经光临了" + count+"次");
// 将新的count写入客户端
Cookie c = new Cookie("Counter", ""+count);
c.setMaxAge(60*60*24*365);       // Cookie 的有效期为 1 年
response.addCookie(c); %>

예 4: 쿠키 삭제

//cookie remove.jsp
<%
int count=0;
// 将新的count写入客户端
Cookie c = new Cookie("Counter", ""+count);
c.setMaxAge(0);       // Cookie 的有效期为 0
response.addCookie(c); %>

예시 5 : 장바구니 로그인 실험

1. 홈페이지에서 장바구니 페이지로 이동

//首页home.html
<a href="cart.jsp">购物车</a>
<a href=”remove.jsp”>删除计数cookie</a>

2. 장바구니 페이지에서 먼저 사용자가 로그인했는지 확인하고 그렇지 않으면 로그인 페이지로 이동하십시오.

//购物车  cart.jsp
<h1>购物车</h1>
<%int count = 0; 
 Cookie[] cookies = request.getCookies(); // 得到所有的Cookie
if(cookies != null) { 
   for(int i=0; i<cookies.length; i++) {
       if(cookies[i].getName().equals("Counter"))
            count = Integer.parseInt(cookies[i].getValue());  //获取Counter以前值
   }  }

if(count==0)response.sendRedirect(request.getContextPath()+"/login.html");
%>
//login.html
<h1>用户登录</h1>
	<form action="visit.jsp" method="post">
		用户名<input type="text" name="user"><br><br>
		密码
		<input type="password" name="password"><br>		
		<input type="submit" value="提交">
	</form>
//visit.jsp
<%int count = 0; 
 Cookie[] cookies = request.getCookies(); // 得到所有的Cookie
if(cookies != null) { 
   for(int i=0; i<cookies.length; i++) {
       if(cookies[i].getName().equals("Counter"))
            count = Integer.parseInt(cookies[i].getValue());  //获取Counter以前值
   }  }

count++;
if(count == 1)
  response.getWriter().println("欢迎首次光临");
else 
  response.getWriter().println("您已经光临了" + count+"次");

// 将新的count写入客户端
Cookie c = new Cookie("Counter", ""+count);
c.setMaxAge(60*60*24*365);       // Cookie 的有效期为 1 年
response.addCookie(c); 
response.sendRedirect(request.getContextPath()+"/cart.jsp");
%>

추천

출처blog.csdn.net/rej177/article/details/124106380