セッションの開始

広告

セッションはクライアント毎に作成され、セッションが開始されるとセッションを識別するためのセッションIDをクライアントの保存し、また保存したい値をセッション変数としてサーバ側に保存します。クライアントに保存されるセッションIDはクッキーを利用して保存されます。

それではまずセッションを開始してみましょう。"doGet"メソッドや"doPost"メソッドの引数で渡されてくる「HttpServletRequest」インターフェースのオブジェクトからセッションを作成します。「HttpServletRequest」インターフェースで用意されている"getSession"メソッドを使います。

Returns the current HttpSession associated with this request or, if
there is no current session and create is true, returns a new session. 

If create is false and the request has no valid HttpSession, this 
method returns null. 

To make sure the session is properly maintained, you must call this 
method before the response is committed. If the container is using 
cookies to maintain session integrity and is asked to create a new 
session when the response is committed, an IllegalStateException is 
thrown. 

Parameters:
  create - true to create a new session for this request if 
    necessary; false to return null if there's no current session 
Returns:
  the HttpSession associated with this request or null if create is 
    false and the request has no valid session

"getSession"メソッドは、サーブレットを要求してきたクライアントに対してセッションが既に開始されていればそのセッションを返します。また引数に"ture"を指定した場合にはセッションが開始されていなければ新規にセッションを開始した後でそのセッションを返してきます。

引数に"false"を指定した場合、セッションが存在しない場合にはnullが帰ってきます。

利用方法としては下記のようになります。

public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws IOException, ServletException{

  response.setContentType("text/html; charset=Shift_JIS");
  PrintWriter out = response.getWriter();

  HttpSession session = request.getSession(true);
}

サンプルプログラム

では簡単に試してみます。セッションが存在するかどうかを確認し、セッションが無ければセッションを開始します。

今回作成するWebアプリケーションのパスは「session」とし、Webアプリケーションの置き場所は「d:\servlet-sample\session\」としました。コンテキストファイルは下記のようになります。

session.xml

<Context path="/session"
docBase="d:/servlet-sample/session"/>

web.xmlファイルは下記のようにしました。

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
  version="2.4">

  <servlet>
    <servlet-name>sessiontest</servlet-name>
    <servlet-class>SessionTest</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>sessiontest</servlet-name>
    <url-pattern>/sessiontest</url-pattern>
  </servlet-mapping>
</web-app>

プログラムは下記の通りです。

SessionTest.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SessionTest extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException{

    response.setContentType("text/html; charset=Shift_JIS");
    PrintWriter out = response.getWriter();

    HttpSession session = request.getSession(false);

    out.println("<html>");
    out.println("<head>");
    out.println("<title>セッションテスト</title>");
    out.println("</head>");
    out.println("<body>");

    if (session == null){
      out.println("<p>セッションは存在しません。開始します</p>");
      session = request.getSession(true);
    }else{
      out.println("<p>セッション開始してます</p>");
    }

    out.println("<a href=\"/session/sessiontest\">再表示</a>");

    out.println("</body>");
    out.println("</html>");
  }
}

上記をコンパイル後に「d:\servlet-sample\session\WEB-INF\classes\」ディレクトリにクラスファイルを移動した後で、ブラウザで「http://localhost:8080/session/sessiontest」へアクセスしてみます。

セッション開始

初回アクセス時にはセッションは開始されていません。この時点でセッションを開始します。次に「再表示」をクリックして下さい。

セッション開始

今度はセッションが開始されています。また、クライアントに保存されているクッキーを見てみます。

セッション開始

セッションが開始されると、セッションIDをクッキーとしてクライアントに保存します。上記の「JSESSIONID」がクッキー名、その後の英数字の羅列がセッションIDとなります。セッションが開始されたクライアントが該当のサーバにアクセスすると、サーバに対してクライアントに保存されたクッキーが渡され、セッションIDから該当のセッションを探し出すという処理が行われています。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。