セッションを使ったデータの書き込みと読み込み

広告

セッションを開始したら、サーバ側にデータを保存することができます。サーバ側に保存されるデータをセッションオブジェクトと呼びます。サーバ側にはデータを複数保存できますので同じセッション内で複数のセッションオブジェクトを保存することができます。

ではデータを保存してみましょう。既に開始されたセッションに対してデータを保存するには、「HttpSession」インターフェースで定義されている"setAttribute"メソッドを使います。

Binds an object to this session, using the name specified. If an object
of the same name is already bound to the session, the object is replaced. 

After this method executes, and if the new object implements 
HttpSessionBindingListener, the container calls 
HttpSessionBindingListener.valueBound. The container then notifies any 
HttpSessionAttributeListeners in the web application. 

If an object was already bound to this session of this name that 
implements HttpSessionBindingListener, its 
HttpSessionBindingListener.valueUnbound method is called. 

If the value passed in is null, this has the same effect as calling 
removeAttribute(). 

Parameters:
  name - the name to which the object is bound; cannot be null
  value - the object to be bound 
Throws: 
  java.lang.IllegalStateException - if this method is called on an 
    invalidated session

"setAttribute"メソッドは、保存するデータを「名前」と「値」のペアで登録を行います。名前はString型ですが、値の方はObject型ですのでObject型のサブクラスであれば基本的に何でも保存することができます。ただしintなどの基本型は利用できません。

例えばセッションオブジェクトとして、名前を「visited」値を「1」として登録したい場合には下記のように記述します。

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);

  session.setAttribute("visited", "1");
}

逆に既に保存されているセッションオブジェクトを取り出して読み込むためには、「HttpSession」インターフェースで定義されている"getAttribute"メソッドを使います。

Returns the object bound with the specified name in this session, or 
null if no object is bound under the name. 

Parameters:
  name - a string specifying the name of the object 
Returns:
  the object with the specified name 
Throws: 
  java.lang.IllegalStateException - if this method is called on an 
    invalidated session

"getAttribute"メソッドは、既に保存されているセッションオブジェクトの中で、引数に指定した名前を持つものを検索し、その値を戻り値として返してくれます。

サンプルプログラム

では簡単に試してみます。訪問回数をカウントするプログラムを作成してみます。

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>SessionTest1</servlet-class>
  </servlet>

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

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

SessionTest1.java

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

public class SessionTest1 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);
      session.setAttribute("visited", "1");
    }else{
      String visitedStr = (String)session.getAttribute("visited");
      int visited = Integer.parseInt(visitedStr);
      visited++;

      out.println("<p>訪問回数は");
      out.println(visited);
      out.println("回目です</p>");

      session.setAttribute("visited", Integer.toString(visited));
    }

    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」へアクセスしてみます。

セッションオブジェクトの利用

次に「再表示」をクリックして下さい。再表示をクリックするたびに保存されている値を1ずつ増加させているため、訪問回数が増加して表示されます。

セッションオブジェクトの利用

セッションオブジェクトの利用

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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