Cookie示例

writecookie.jsp:

<%@ page contentType="text/html;charset=gb2312" %>
<!--<%@ page import="java.util.*"%>-->
<%@ page language="java" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312">
<title>写入cookie</title>
</head>
<body>
<div align="center">写入cookie示例</div>
<br>
<%
 Cookie cook=new Cookie("Yp","this is a cookie example");
 cook.setMaxAge(30*60);
 response.addCookie(cook);
 out.print("写入Cookie完成");
%>
<br>
<br>
<a href="readcookie.jsp">读取cookie</a>
</body>
</html>

 

 

 

readcookie.jsp:

<%@ page contentType="text/html;charset=gb2312"%>
<%@ page language="java"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312"%>
<title>读取cookie</title>
</head>
<body>
<%
 Cookie cookies[]=request.getCookies();
 Cookie sCookie=null;
 String sname=null;
 String svalue=null;
 if(cookies==null)
 {
  out.println("没有cookie记录");
 }
 else
 {
  out.println("<br>cookie个数:"+cookies.length); 
  for(int i=0;i<cookies.length;i++)
  {
   sCookie=cookies[i];
   sname=sCookie.getName();
   svalue=sCookie.getValue();
   out.println("<br>cookie名字:"+sname+",cookie的值:"+svalue);
  }
 }
%>
</body>
</html>

 

 

JspCookie.jsp(首先读取客户端所有的Cookie并输出到网页上,然后修改Cookie的有效期,将修改后的有效期输出到网页上,最后创建新的Cookie并把它写到客户端):

<%@ page contentType="text/html;charset=GBK" %>
<html>
<head>
<title>JspCookie</title>
<body bgcolor="#ffffff">
<%
 Cookie[] cookies=request.getCookies();
 if(cookies!=null)
 {
  for(int i=0;i<cookies.length;i++){
%>
<P>
 <b>
  Cookie name:
 </b>
  <%=cookies[i].getName()%>
 <b>
  Cookie value:
 </b>
  <%=cookies[i].getValue()%>
</p>
<p>
 <b>
  Old max age in seconds:
 </b>
  <%=cookies[i].getMaxAge()%>
  <%cookies[i].setMaxAge(600);%>
 <b>
  New max age in seconds:
 </b>
  <%=cookies[i].getMaxAge()%>
</p>
<%}
  
 }
%>
<%!int count1=0;
   int count2=0;
%>

<%
 response.addCookie(new Cookie("cookieName"+count1++,"cookieValue"+count2++));
%>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值