Cookie與Session

Cookie與Session

1. Cookie

1.1 cookie原理

​ cookie是服務器創建,通過響應對象傳遞到瀏覽器,瀏覽器對cookie中的數據進行保存(緩存)。以後每次瀏覽器發請求時,瀏覽器會攜帶所有的cookie信息發送到服務器,服務器可以通過請求對象獲取對應的cookie信息。

1.2 cookie特點

1.2.1 不支持中文

//對name進行編碼處理
String name = URLEncoder.encode(name, "UTF-8");
//對cookie的值進行解碼處理
string value = URLDecoder.decode(cookie.getValue(),"utf-8");

1.2.2 修改cookie中的值

​ 1、new一個同名的cookie,然後將這個new出來的cookie響應到瀏覽器,瀏覽器就會覆蓋原有的值。

Cookie cookie = new Cookie("username","admin");
resp.addCookie(cookie)

​ 2、根據對應的name拿到cookie對象,然後再設置對應的cookie值。

Cookie[] cookies = req.getCookies();                                
if (cookies != null) {                                              
    for (Cookie cookie : cookies) {                                 
        if (cookie.getName().equals("username")) {                  
            //解碼                                                    
            username = URLDecoder.decode(cookie.getValue(),"utf-8");
            resp.addCookie(cookie);                                 
        }                                                           
    }                                                               
}                                                                   

1.2.3 刪除cookie

cookie.setMaxAge(int second);

second爲正數:代表多少秒後cookie失效。
second爲0:就代表刪除當前cookie。
second爲負數:關閉瀏覽器cookie就失效。

1.2.4 路徑問題

/cookie/login 在這個路徑下面保存的Cookie

/cookie/*   這個路徑下面是可以拿到Cookie
/cookie2/*  這個路徑下面拿不到Cookie
cookie.setPath("/");//設置保存在根路徑下,都可以訪問

1.3 cookie缺點

  • 只能保存字符串,不能保存對象及集合。
  • 不能保存中文。
  • cookie保存在瀏覽器,不安全。
  • 瀏覽器可以禁用cookie。

2. Session

2.1 session原理

​ session是服務器創建,保存在服務器端。當瀏覽器某一次請求瀏覽器,創建了一個session對象,這個session對象由一個唯一的標誌ID,服務器會將這個sessionid通過cookie返回給瀏覽器,以後每次請求,瀏覽器都會攜帶這個sessionid到服務器。

2.2 session特點

2.2.1 獲取與修改值

HttpSession session = request.getSession(boolean value);
value:true  -> 如果有直接拿,如果沒有就創建一個。
value:false -> 如果有直接拿,如果沒有就返回null。

session.setAttribute("username","tom");

2.2.2 設置死亡時間

參數的的意義:按照瀏覽器請求靜默的時長來計算的。距最後一次請求的時間長度。

  • 直接設置
session.setMaxInactiveInterval(Integer interval)
  • 通過web.xml配置
<session-config>
	<session-timeout>1000</session-timeout>
</session-config>
  • 如果設置爲負數:瀏覽器一關閉,session就失效。

3. 表單重複提交

1、按鈕點擊之後,js代碼禁用按鈕。
2、session+令牌驗證。

  • jsp頁面
<%@ page import="java.util.UUID" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>salary</title>
</head>
<body>
<%
    UUID uuid = UUID.randomUUID();
    request.getSession().setAttribute("token",uuid);
%>
<form action="/xx/safe">
    <input type="hidden" name="cmd" value="token">
    <input type="hidden" name="token" value="${token}">
    轉賬:<input type="text" name="salary"><br>
    <input type="submit" value="確定轉賬">
</form>
</body>
</html>
  • 請求處理
private void token(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/html;charset=utf-8"); 
    //獲取表達數據
    String salary = req.getParameter("salary");
    //獲取表單
    String tokenClient = req.getParameter("token");
    //從session域中獲取值 
    Object tokenServer = req.getSession().getAttribute("token");
    //移除session域中的值
    req.getSession().removeAttribute("token");
    if(tokenServer==null || "".equals(tokenServer.toString())){
        PrintWriter writer = resp.getWriter();
        writer.println("<h1>請不要重複提交!!</h1><br>");
        writer.println("<a href='/xx/salary.jsp'>點擊返回轉賬頁面</a>");
        writer.close();
    }
    if(tokenServer.toString().equals(tokenClient)){
        System.out.println("扣除:"+salary); 
    }
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    resp.sendRedirect("/xx/salary.jsp"); 
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章