Web 学習履歴 (10) - Cookie/セッション

会話

一般的な会話テクニック

Cookie
はクライアント側のテクノロジであり、プログラムは各ユーザーのデータを Cookie の形式でユーザーのそれぞれのブラウザーに書き込みます。ユーザーがブラウザを使用してサーバー内の Web リソース トランザクションにアクセスすると、ユーザーは自分のデータを持ち込むことになります。このようにして、Web リソースはユーザー自身のデータを処理します。

セッション
はサーバー側のテクノロジーであり、サーバーはブラウザーごと、つまりセッションごとにメモリ空間を開きます。メモリ空間はブラウザごとに占有されているため、すべてのユーザーがアクセスすると、その情報がセッション オブジェクトに保存されます。同時に、各セッション オブジェクトはセッション ID に対応し、サーバーはセッション ID を Cookie に書き込みます。再度アクセスすると、ブラウザーは Cookie を取得して対応するオブジェクトを見つけます。

クッキー

これはクライアント側のセッション技術です. サーバーによってブラウザに保存される小さなデータです. ブラウザが将来サーバーにアクセスするたびに, この小さなデータがサーバーに運ばれます.

機能
ブラウザにデータを保存する
ブラウザに保存したデータをサーバに持ち込む

関連する API

//创建一个cookie对象
new Cookie(String name,String value);
//将cookie写回浏览器
response.addCookie(cookie);
//获得浏览器带过来的cookie
request.getCookies();

//返回cookie中设置的key
cookie.getName();
//返回cookie中设置的value
cookie.getValue();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
    Cookie[] cookies = request.getCookies();
    if (cookies != null){
    
    
        for (Cookie cookie : cookies) {
    
    
            if ("akey".equals(cookie.getName())){
    
    
                System.out.println(cookie.getValue());
            }
        }
    }
    Cookie cookie = new Cookie("akey","aaa");
    response.addCookie(cookie);
}

通常、Cookie はカプセル化されています。

public class CookieUtils {
    
    
    public static Cookie getTargetCookie(String key,Cookie[] cookies){
    
    
        if (cookies == null){
    
    
            return null;
        }
        for (Cookie cookie : cookies) {
    
    
            if (key.equals(cookie.getName())){
    
    
                return cookie;
            }
        }
        return null;
    }
}

クッキーの分類

セッション レベルの Cookie
デフォルトでは、ブラウザ プロセスが終了すると Cookie は消えます

パーシスタント Cookie は、
Cookie の有効期限を設定します
cookie.setMaxAge(int expiry);
-1: デフォルト、ブラウザが閉じられるまでデータが保存され、ブラウザ ファイルに保存されることを意味します
0: 必要に応じて Cookie を削除することを意味しますCookie を削除するには、パスが一貫していて
0 より大きいことを確認してください: データの有効時間を秒単位で保存します (キャッシュされたデータをディスクに保存します)。

cookie セット有効パス

setPath(文字列 URL)

機能
他の Web サイト/プロジェクトからの Cookie が自分のプロジェクトに運ばれないことを保証します
パスが異なる場合、Cookie のキーを呼び出して、
自分のプロジェクトが自分のプロジェクトの Cookie を合理的に使用できるようにすることができます


Cookie を運ぶにはデフォルトのパスが必要です。Cookie は、アクセスされたリソースの URL に Cookie の有効なパスが含まれている場合にのみ運ばれます。

通常、Cookie パスは次のように設定されます:
cookie.setPath(request.getContextPath());

ケース - ユーザーのそれぞれの最終訪問時間を記録する

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        Cookie[] cookies = request.getCookies();
     Cookie targetCookie = CookieUtils.getTargetCookie("lasttime",cookies);
     if (targetCookie == null){
    
    
         Cookie cookie = new Cookie("lasttime",System.currentTimeMillis() + "");
         cookie.setMaxAge(60*60);
         cookie.setPath(request.getContextPath());
         response.addCookie(cookie);
         response.getWriter().print("第一次访问");
     }
     else {
    
    
//         Cookie cookie = new Cookie("lasttime",System.currentTimeMillis()+"");
//         cookie.setPath(request.getContextPath());
//         cookie.setMaxAge(60*60);
//         response.addCookie(cookie);
         String time = targetCookie.getValue();
         Date date = new Date(Long.parseLong(time));
         response.getWriter().print("你上次访问的事件是" + date.toLocaleString());
     }
    }

セッション

サーバー側の技術です。サーバーは、ブラウザごとにメモリ空間を開きます。つまり、セッション オブジェクト

クッキーとセッションの異なる
クッキーはブラウザ側に保存され、サイズや数に制限があります。セッションはサーバー側に保存 原則としてサイズ制限がないので安心

Cookie は中国語をサポートしておらず、文字列のみを格納できます。セッションは、基本的なデータ型、コレクション、オブジェクトなどを格納できます。

実行処理
cookie(cookie)で渡されたsessionIdを取得
cookieにsessionIdがない場合はsessionオブジェクトを作成
cookieにsessionIdがある場合は指定のsessionオブジェクトを探す

sessionId があり、セッション オブジェクトが存在する場合は、それを直接使用します。
sessionId があり、セッション オブジェクトが破棄されている場合は、2 番目の手順を実行します。

クッキーに基づくセッション

スコープ
セッション、ブラウザ単位でユーザーのそれぞれのデータを保存

request.getSession();
オブジェクト getAttribute(文字列名): 値を取得
void setAttribute(文字列名,オブジェクト値); 値を格納
void removeAttribute(文字列名); 削除

3 つのドメイン オブジェクトの比較
ServletContext
HttpSession
HttpServletRequest

サーバーが正常にシャットダウンされた場合は、
セッションをサーバー ディスクにパッシベートし、再起動して、ディスク上のファイルをメモリにアクティブ化します。

3 つのドメイン オブジェクトの選択方法
通常、最小の
リダイレクト、複数のリクエスト、セッション スコープ、および
セッションで最小の解決が可能です
転送の場合は、一般的にリクエストを選択します

ケース: 1 回限りの確認コードの確認

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<center>
    <h1>用户登录:</h1>
    <form action="login" method="post">
        姓名:<input type="text" name="username"/><br/>
        密码:<input type="password" name="password"/><br/>
        验证码:<input type="text" name="code"/><br/>
        <img src="code" onclick="changeImg(this)"/><br/>
        <input type="submit" value="登录">
    </form>
</center>
</body>
</html>
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset = utf-8");
        String usercode = request.getParameter("code");
        String code = (String) request.getSession().getAttribute("code");
        if (!code.equals(usercode)){
    
    
            response.getWriter().print("验证码有误");
            return;
        }

    }
}
import cn.dsna.util.images.ValidateCode;

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

@WebServlet("/code")
public class CodeServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        ValidateCode validateCode = new ValidateCode(200,50,4,100);

        String code = validateCode.getCode();
        System.out.println(code);
        request.getSession().setAttribute("code",code);

        validateCode.write(response.getOutputStream());

    }
}

おすすめ

転載: blog.csdn.net/qq_49658603/article/details/108474990