Cookie的简单使用
Cookie的简单使用
程序逻辑:
- index.jsp用来输入和处理Cookie和取得Cookie(不知道是内存还客户端的)
- 用show.jsp来接收表单数据和Cookie ,再发送Cookie 给客户端。
index.jsp页面
<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GBK"> <title>Insert title here</title> </head> <body> <% String welcome = "第一次访问"; String[] info = new String[]{"","",""}; /* 等于每次都清空了info,如果第二次访问的时候,这里其实会清空的 但是如果存在Cook的话,下面的代码,会把,info再出赋值,这样info就有了值,但如果不清空就会导值没有变化,也不知道会发声明什么 */ Cookie[] cook = request.getCookies(); if (cook!=null){ for(int i = 0 ; i<cook.length ; i ++){ if(cook[i].getName().equals("mrCookInfo")){ info = cook[i].getValue().split("#"); welcome = "欢迎回来!" ; } } } %> <%=info[0] %> <%= welcome %> <form action = "show1.jsp" method ="post" > 姓名 : <input type = "text" name ="name" value= <%=info[0] %>><p> 出生日期 :<input type = "text" name ="birthday" value =<%=info[1] %>><p> 邮箱地址: <input type = "text" name ="mail" value= <%=info[2] %>><p> 登陆 : <input type = "submit" name = "submit" ><p> </form> </body>
show.jsp页面
<%@ page language="java" contentType="text/html" pageEncoding="GBK"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<%
String name = request.getParameter("name");
String birthday = request.getParameter("birthday");
String mail = request.getParameter("mail");
Cookie myCook = new Cookie("mrCookInfo",name+"#"+birthday+"#"+mail);
myCook.setMaxAge(60*60*24*365); // 设置Cookie时间
response.addCookie(myCook);//发送Cookie给客户端
%>
表单提交成功
<ul style="line-height: 24px">
<li>姓名:<%= name %>
<li>出生日期:<%= birthday %>
<li>电子邮箱:<%= mail %>
<li><a href="index1.jsp">返回</a>

浙公网安备 33010602011771号