writeCookie.jsp:
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>writeCookie</title>
</head>
<body>
<%
String username="prometheus";
String cookieName="cookie_Name";
Cookie cookie=new Cookie(cookieName, "cookie_Content");
/*第一个参数cookieName定义了Cookie的名字,后一个参数,也是个字符串,定义了Cookie的内容。也就是我们希望网页在用户的机器上标识的文档内容。*/
cookie.setMaxAge(10); //设定Cookie在用户机器硬盘上的存活期为10秒。
response.addCookie(cookie); //添加cookie
response.sendRedirect("readCookie.jsp?username="+username);//利用response.sendRedirect传递参数
%>
</body>
</html>
readCookie.jsp:
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>readCookie</title>
</head>
<body>
<table border=1>
<tr><td>Name</td><td>value</td></tr>
<%
String username=request.getParameter("username");//接收传递过来的参数
Cookie cookies[]=request.getCookies();
Cookie sCookie=null;
String svalue=null;
String sname=null;
for(int i=0;i<cookies.length;i++)
{
sCookie=cookies[i];
sname=sCookie.getName(); //读取cookie的名字
svalue=sCookie.getValue(); //读取cookie的值
%>
<tr><td><%=sname%></td><td><%=svalue%></td></tr>
<%
}
%>
<tr><td>username</td><td><%=username%></td></tr>
</table>
</body>
</html>