原創聲明:本文為作者原創,未經允許不得轉載,經授權轉載需注明作者和出處
還是登陸網站的例子,有很多網站的登錄界面會有個記住賬號密碼的選項,甚至是有些瀏覽器比如firfox,會在我們點擊登錄按鈕之后會彈出一個選項提示我們記住賬號密碼。那么這個記住的賬號密碼是放在什么地方呢?對,就是放在今天我們要講的cookie里面。上章我們講到的session其實是前端和服務器之間的一個會話,這個會話主要是保存在服務端,那么今天要講的cookie,其實也是一個會話,是保存在客戶端(瀏覽器上)的會話。那么同樣都是會話,cookie和session有什么區別呢?
下面來寫一個保存用戶名密碼的小demo:
servlet:
public class CookieServlet extends HttpServlet {
private static final long serialVersionUID = -271571469551304432L;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String uname = request.getParameter("uname");
String password = request.getParameter("password");
String ck = request.getParameter("ck");
// 被選中的狀態是on 沒有被選中的狀態下是null
if ("on".equals(ck)) {
// 構造Cookie對象
// 添加到Cookie中
Cookie c = new Cookie("users", uname + "-" + password);
// 設置過期時間
c.setMaxAge(600);
// 存儲
response.addCookie(c);
}
}
}
jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%
//el表達式
String names="";
String pwd="";
//取出Cookie
Cookie [] c=request.getCookies();
for(int i=0;i<c.length;i++){
if(c[i].getName().equals("users")){
//存著數據(用戶名+密碼)
names=c[i].getValue().split("-")[0];
pwd=c[i].getValue().split("-")[1];
//再一次的存起來(備用)
request.setAttribute("xingming",names);
request.setAttribute("mima", pwd);
}
}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="cookie" method="post">
用戶名:<input type="text" name="uname" id="uname" value="${xingming}"/><br>
密碼:<input type="password" name="password" id="password" value="${mima }"/><br>
<input type="checkbox" name="ck">記住用戶名和密碼<br>
<input type="submit" value="登錄">
</form>
</body>
</html>
這樣寫出來的一個項目,當我們點記住密碼然后登陸之后,進去了一個空白頁,,
然而我們用同一個瀏覽器在去進入登陸頁面時,你會發現賬號密碼被記住了:
源碼下載地址:
http://pan.baidu.com/s/1o8z64GU
鳴謝:又偷了點懶,文中源碼均由借(chao)鑒(xi)自http://www.cnblogs.com/thrilling/p/4924077.html