經過cookie保存並讀取用戶登陸信息實例

經過cookie的getCookies()方法可獲取全部cookie對象的集合;經過getName()方法能夠獲取指定的名稱的cookie;經過getValue()方法獲取到cookie對象的值。另外,將一個cookie對象發送到客戶端,使用response對象的addCookie()方法。javascript

下面經過cookie保存並讀取用戶登陸信息的例子加深一下理解。html

(1)建立index.jsp文件。在改文件中,首先獲取cookie對象的集合,若是集合不爲空,就經過for循環遍歷cookie集合,從中找出設置的cookie(這裏設置爲lee),並從該cookie中提取出用戶名和註冊時間,再根據獲取的結果顯示不一樣的提示信息。java

index.jspcookie

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%@page import="java.net.URLDecoder" %>
<!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=utf-8">
<title>經過cookie保存並讀取用戶登錄信息</title>
</head>
<body>
<%
Cookie[] cookies=request.getCookies();//從request中得到cookie對象的集合
String user="";//登陸用戶
String date="";//註冊時間
if(cookies!=null){
    for(int i=0;i<cookies.length;i++){
        if(cookies[i].getName().equals("lee")){
            user=URLDecoder.decode(cookies[i].getValue().split("#")[0]);//獲取用戶名
            date=cookies[i].getValue().split("#")[1];//獲取註冊時間
                                                                          
        }
    }
                                                                  
}
if("".equals(user)&&"".equals(date)){ //若是沒有註冊
%>
遊客你好,歡迎你初次光臨!
<form action="deal.jsp"method="post">
請輸入姓名:<input name="user"type="text"value="">
<input type="submit"value="肯定">
</form>
<%
}else{ //已經註冊
    %>
    歡迎[<b><%=user %><b>]再次光臨<br>
    你註冊的時間是:<%=date %>
<%
}
%>
</body>
</html>


(2)編寫deal.jsp文件,用來向cookie中寫入註冊信息。jsp

deal.jspide

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%@page import="java.net.URLEncoder" %>
<!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=utf-8">
<title>寫入cookie</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");//設置請求的編譯爲utf-8
String user=URLEncoder.encode(request.getParameter("user"),"utf-8");//獲取用戶名
Cookie cookie=new Cookie("lee",user+"#"+new java.util.Date().toLocaleString());//建立並實例化cookie對象
cookie.setMaxAge(60*60*24*30);//設置cookie有效期爲30天
response.addCookie(cookie);
%>
<script type="text/javascript">window.location.href="index.jsp"</script>
</body>
</html>


技巧:在向cookie中保存的信息中若是包括中文,須要調用java.net.URLEncoder類的encode()方法保存到cookie中的信息進行編碼;在讀取內容時,須要應用到java.net.URLDecoder類的decode()方法進行解碼。這樣就能夠成功地向cookie中寫入中文。post

相關文章
相關標籤/搜索