1. 程式人生 > >Java——Web開發之Cookie的使用

Java——Web開發之Cookie的使用

Cookie:是伺服器給客戶端,並且儲存在客戶端上的一份小資料。

  • 應用場景:自動登陸,瀏覽記錄,購物車
  • http請求是無狀態的。客戶端與伺服器在通訊的時候,是無狀態的,其實就是在客戶端在第二次來訪的時候,伺服器根本就不知道客戶端以前有沒有來訪問過。為了更好的使用者體驗,更好的互動,其實從公司層面講,就是為了更好的收集使用者習慣。
  • Cookie分類:
  1. 會話Cookie:預設情況下,關閉了瀏覽器,那麼cookie就會消失
  2. 持久Cookie:在一定時間內都有效,並且會儲存在客戶端上
  • cookie.setMaxAge(0);    //設定將cookie立即刪除
  • Cookie的安全問題:由於Cookie會儲存在客戶端上,所以有安全隱患;Cookie的大小與個數有限制
  • 簡單使用過程:
  1. 傳送cookie給客戶端
  2. 給響應新增一個cookie
  3. 獲取Cookie,獲取客戶端帶過來的cookie

示範程式碼給出~

Cookie_1.java

package c.Cookie;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Cookie_1
 */
public class Cookie_1 extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
                throws ServletException, IOException {
		//1.Cookie的簡單使用,傳送cookie給客戶端
		//是伺服器傳送給客戶端並且儲存在客戶端上的一份小資料
		response.setContentType("text/html;charset=utf-8");
		/*
		 	方法引數要物件時就給物件
		 	建立物件的幾種方法:
		 	1.直接new
		 	2.單例模式或者提供靜態方法
		 	3.工廠模式構建	stu
		 		StuFactory StuBuilder
		 */
		Cookie c=new Cookie("aa", "bb");
		//給響應新增一個cookie
		response.addCookie(c);
		response.getWriter().write("請求成功!");
		//在客戶端收到的資訊裡面,響應頭中多了一個欄位Set-Cookie:aa=bb
		
		//2.獲取Cookie,獲取客戶端帶過來的cookie
		Cookie[] cookies=request.getCookies();
		if(cookies!=null){
			for (Cookie cookie : cookies) {
				String cookieName=cookie.getName();
				String cookieValue=cookie.getValue();
				System.out.println(cookieName+"="+cookieValue);
			}
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
                    throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

 

實現給客戶端多個cookie,設定cookie的有效期的程式碼~

Cookie_2.java

package c.Cookie;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Cookie_2 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
		//1.先寫cookie,可以給客戶端多個cookie
		Cookie cookie=new Cookie("qq", "22");
		response.addCookie(cookie);
		Cookie cookie4=new Cookie("age", "12");
		response.addCookie(cookie4);
		//去客戶端傳送過來的cookie
		Cookie[] cookies=request.getCookies();
		if(cookies!=null){
			for (Cookie cookie2 : cookies) {
				System.out.println(cookie2.getName()+"="+cookie2.getValue());
			}
		}
		//2.cookie的有效期。預設情況下,關閉瀏覽器,cookie就沒有了(針對沒有設定cookie的有效期)
		//expiry——設定以秒為單位的有效期,正值表示在這個數字過後cookie會失效,負值表示關閉瀏覽器就會失效,預設是-1
		int expiry=60*60*24*7;
		cookie.setMaxAge(expiry);
		
		//用於指定只有請求了指定的域名,才會帶上該cookie
		cookie.setDomain(".bcd.com");
		//只有訪問該域名下的JavaWeb_2的這個路徑才會帶cookie
		cookie.setPath("/JavaWeb_2");
		//賦一個新的值
		cookie.setValue("rr");
		
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

小案例:獲取最近訪問時間~

login.html

<!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>Insert title here</title>
</head>
<body>
獲取最近訪問時間<br>
	<form action="Cookie_3">
		賬號:<input type="text" name="username" /><br>
		密碼:<input type="text" name="password" /><br>
		<input type="submit" value="登陸" /><br>
	</form>
</body>
</html>

CookieUtil.java

package cookie.util;

import javax.servlet.http.Cookie;

public class CookieUtil {
	public static Cookie findCookie(Cookie[] cookies,String name){
		if(cookies!=null){
			for (Cookie cookie : cookies) {
				if(name.equals(cookie.getName())){
					return cookie;
				}
			}
		}
		return null;
	}
}

Cookie_3.java

package c.Cookie;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cookie.util.CookieUtil;

/*
 	獲取最近訪問時間
 */
public class Cookie_3 extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		if("admin".equals(username)&&"123".equals(password)){
			//獲取cookie
			
			Cookie[] cookies=request.getCookies();
			//從數組裡找出想要的cookie
			Cookie cookie= CookieUtil.findCookie(cookies, "last");
			if(cookie==null){
				//第一次登陸無cookie
				Cookie cookie2=new Cookie("last",System.currentTimeMillis()+"");
				cookie2.setMaxAge(60*60);
				response.addCookie(cookie2);
				response.getWriter().write("歡迎登陸!");
			}else{
				//第二次登陸,有cookie
				//1.獲取以前的cookie
				long lastVisitTime=Long.parseLong(cookie.getValue());
				//2.輸出到介面
				//歡迎登陸!上次來訪時間為:Wed Nov 14 20:16:02 CST 2018
				response.getWriter().write("歡迎登陸!"+"上次來訪時間為:"+new Date(lastVisitTime));
				//3.重置登陸時間
				cookie.setValue(System.currentTimeMillis()+"");
				response.addCookie(cookie);
			}
		}else{
			response.getWriter().write("登陸失敗!");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}