0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

セッションを基本からまとめてみた【基礎】

Last updated at Posted at 2025-11-06

セッションとは?

ブラウザとやり取りしたデータを
⚫︎アプリケーションサーバーに保存する
⚫︎保存したデータを取り出せる
※ 使用例

  • システムのログイン
  • ウィザード形式のアプリケーションなど

セッションにデータを保存するコード

データを保存するサーブレットのコード(Sv1)

Sv1.java
public class Sv1 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)

    //パラメータを取得
    String params = request.getParameter("param");

    //セッションを生成
    HttpSession session = request.getSession(true);

    //セッションに値をセット
   session.setAttribute("param", params);
}

データを取り出すサーブレットのコード(Sv2)

Sv2.java
public class Sv2 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)

    //セッションを取得
    HttpSession session = request.getSession(false);

    //セッションから値を取得
   String data = (String)session.setAttribute("param");
}

セッションを無効化するコード

Sv3.java
public class Sv3 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)

    //セッションを取得
    HttpSession session = request.getSession(false);

    //セッションを無効化
   session.invalidate();
}

値を消去するコード

Sv4.java
public class Sv4 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)

    //セッションを取得
    HttpSession session = request.getSession(false);

    //セッションから値を消去
   session.removeAttribute("param");
}

参考サイト

【中級編Java(14)】セッション―複数のページでデータを共有―|Javaプログラミングのゆるふわレシピ

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?