Web系開発メモ

Java, C#, HTML, CSS, JavaScript のことなどを書いてます。

Servlet セッション管理をする方法(値の保持と取得)

Servlet API の HttpSession を使うと、リクエストをまたがって値(オブジェクト)を保持することができます。

これから、セッションに値を設定して取得する方法を書いていきます。

バージョン

ブログ執筆時のバージョンは以下の通りです。

動作確認のために、以下の製品を使用しました。

目次

  1. 値を設定するサーブレットの作成
  2. 値を取得するサーブレットの作成
  3. ディレクトリ階層の作成
  4. pom.xml の作成
  5. 動作確認

1. 値を設定するサーブレットの作成

以下のクラスを作成します。

org/example/session/SetAttributeServlet.java

package org.example.session;

import java.io.IOException;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@WebServlet("/session/set")
@SuppressWarnings("serial")
public class SetAttributeServlet extends HttpServlet {
  public void doGet(
    HttpServletRequest req, HttpServletResponse res)
  throws ServletException, IOException {
    // リクエストパラメーターを取得
    String msg = req.getParameter("msg");
    // セッションを作成して取得
    HttpSession session = req.getSession();
    // セッションに値を設定(キー:"msg")
    session.setAttribute("msg", msg);
    // HTMLを返却
    res.setContentType("text/html");
    res.setCharacterEncoding("utf-8");
    res.getWriter().println(
      "<html><body>設定完了</body></html>"
    );
  }
}

リクエストパラメーターの値を取得してセッションに設定しています。

セッションを作成したくない場合(ログインしていない場合など)は、セッション取得時に引数 false を指定します。

HttpSession session = req.getSession(false);

引数省略時は以下のコードと同じで、セッションがない場合に作成して取得します。

HttpSession session = req.getSession(true);

2. 値を取得するサーブレットの作成

上で設定した値を取得するクラスを作成します。

org/example/session/GetAttributeServlet.java

package org.example.session;

import java.io.IOException;
import java.io.PrintWriter;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@WebServlet("/session/get")
@SuppressWarnings("serial")
public class GetAttributeServlet extends HttpServlet {
  public void doGet(
    HttpServletRequest req, HttpServletResponse res)
  throws ServletException, IOException {
    // セッションから値を取得してHTMLを返却
    HttpSession session = req.getSession(false);
    if (session == null) {
      html("セッションなし", res);
    } else {
      String msg = (String) session.getAttribute("msg");
      html(msg, res);
    }
  }
  private void html(
    String msg, HttpServletResponse res)
  throws IOException {
    res.setContentType("text/html");
    res.setCharacterEncoding("utf-8");
    PrintWriter o = res.getWriter();
    o.print("<html><body>");
    o.print(msg);
    o.println("</body></html>");
  }
}

3. ディレクトリ階層の作成

動作確認をする場合、以下のコマンドでプロジェクト sample-servletディレクトリ階層を作成します。

mkdir sample-servlet
cd sample-servlet
mkdir src\main\java
mkdir src\main\webapp\WEB-INF

作成したら、src/main/java 配下にサーブレットのコードを置きます。

4. pom.xml の作成

フォルダ sample-servletpom.xml を作成します。

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>sample-servlet</artifactId>
  <version>1.0.0</version>
  <packaging>war</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>jakarta.servlet</groupId>
      <artifactId>jakarta.servlet-api</artifactId>
      <version>5.0.0</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>${project.artifactId}</finalName>
    <plugins>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.4.0</version>
      </plugin>
      <plugin>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <version>11.0.15</version>
        <configuration>
          <scan>1</scan>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

サーブレットコンテナを起動できるように、build で Jetty Plugin を定義しています。

5. 動作確認

以下のコマンドでコンテナを起動します。

sample-servlet> mvn jetty:run

起動後にブラウザで以下の URL を開きます。

http://localhost:8080/session/set?msg=Hello!

処理が完了したら、以下の URL を開きます。

http://localhost:8080/session/get

ブラウザに以下の文字列が表示されます。

Hello!