LoginSignup
7
7

More than 5 years have passed since last update.

JSP/サーブレット セッション情報の設定・取得

Posted at

JSP/サーブレットでセッション情報を設定・取得する方法です。

セッション情報の設定

JSP/サーブレットの暗黙オブジェクトsession(javax.servlet.http.HttpSessionの実装)に、setAttribute(String, object)メソッドで値を設定します。

Sessionの設定
protected void doGet(HttpServletRequest request, HttpServletResponse response){
  String value = "XxxValue";
  // 第2引数は(Stringに限らず)任意のオブジェクトを設定可能
  session.setAttribute("XxxKeyString", value);
}

セッション情報の取得

sessionオブジェクトのgetAttribute(String)メソッドで値を取得します。

Sessionの取得
protected void doGet(HttpServletRequest request, HttpServletResponse response){
  String value = session.getAttribute("XxxKeyString");
}

よく使うsessionオブジェクトのメソッド

メソッド 説明
getAttributeNames() セッションに紐づくオブジェクト名の一覧(Enumeration)を取得
getCreationTime() セッションが生成された時刻(long)を取得
getLastAccessedTime() セッションID付きリクエストを受け取った最後の時刻
setMaxInterval(int), getMaxInactiveInterval() サーブレットコンテナに最終アクセスしてからセッションを保持する最大秒数を設定・取得
isNew() まだセッションが設定されていない場合にtrue
invalidate() セッションを無効化
7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7