JSP中的cookie實現
阿新 • • 發佈:2018-11-27
##一、背景
在我們登入一個網頁的時候,經常會問我們是否要儲存使用者名稱和密碼,其實,儲存的是cookie。cookie是伺服器端生成的一個字串,客戶端以key-value的形式儲存下來。下面,我們就用cookie簡單的實現這樣的功能!!!
##二、功能概述
step1:首次訪問index.jsp後,顯示:第一次訪問!
step2:通過提交表單的方式,跳轉到show.jsp頁面
step3:通過超連結,返回至index.jsp,顯示:tom歡迎回來
##三、index.jsp和show.jsp兩個檔案的原始碼
(1) index.jsp
<%@page import="java.util.Date"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>首頁</title> </head> <body> <% String welcome="第一次訪問!"; String [] info= new String[]{"","",""}; Cookie[] cook=request.getCookies(); if(cook!=null){ for(int i=0;i<cook.length;i++){ if(cook[i].getName().endsWith("tom")){ info=cook[i].getValue().split("#"); welcome="歡迎回來!"; } } } %> <%=info[0]+welcome %> <form action="show.jsp" method="post"> 姓名:<input type="text" name="name" value="<%=info[0]%>"><br> 生日:<input type="text" name="birthday" value="<%=info[1]%>"><br> 郵箱地址:<input type="text" name="mail" value="<%=info[2]%>"><br> <input type="submit" value="提交"> </form> </body> </html>
(2) show.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <% String name =request.getParameter("name"); String birthday =request.getParameter("birthday"); String mail =request.getParameter("mail"); Cookie myCook= new Cookie("tom",name+"#"+birthday+"#"+mail); response.addCookie(myCook); %> <ul> <li>姓名:<%=name %> <li>生日:<%=birthday %> <li>郵箱地址:<%=mail %> <li> <a href="index.jsp">返回</a> </ul> </body> </html>
##四、執行結果展示
(1) 首次訪問
(2) 填入相應的資訊
(3) 跳轉至show.jsp頁面,點選超連結:返回
(4) 再次訪問index.jsp