Servlet スコープとは?

  • スコープとはデータの有効範囲の事。
  • Servletでは、requestスコープ、sessionスコープ、applicationスコープがある。
  • httpセッション間でデータ共有するときは、request,sessionスコープ。
  • webアプリ間では、applicationスコープ。

requestスコープ

  • requestスコープでデータを操作する場合は、HttpServletRequestインタフェースのオブジェクトを使用。
  • forwardメソッドなどでHttpServletRequestインタフェースのオブジェクトをリクエスト先に引き継ぐことでデータを共有。
public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

  ・・・・・・・・・・・

  //useridデータをrequestスコープで保存
  req.setAttribute("userid", userid);

  ・・・・・・・・・・・

  //forwardメソッドで、HttpServletRequestインタフェースの
  //reqオブジェクトをリクエスト先に引継ぎ
  RequestDispatcher rd = req.getRequestDispatcher("./xxx");
  rd.forward(req, res);
}

sessionスコープ

  • HTTPセッション間でデータを共有したい場合に使用。
  • 異なるページ間でブラウザを閉じるまで、もしくは一定時間経過するまでデータを共有することができます。
  • HttpSessionインタフェースのオブジェクトを使用します。このオブジェクトはHttpServletRequestインタフェースのgetSessionメソッドで取得できます。
public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

  ・・・・・・・・・・・

  //HttpSessionインタフェースのオブジェクトを取得
  HttpSession session = req.getSession();
  //useridデータをsessionスコープで保存
  session.setAttribute("userid", userid);

  ・・・・・・・・・・・

}

applicationスコープ

  • ServletContextインタフェースのオブジェクトを使用します。
  • このオブジェクトはHttpServletクラスのgetServletContextメソッドで取得できます。
public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

  ・・・・・・・・・・・

  //ServletContextインタフェースのオブジェクトを取得
  ServletContext sc = getServletContext();
  //useridデータをapplicationスコープで保存
  sc.setAttribute("userid", userid);

  ・・・・・・・・・・・

}

各スコープのデータ操作

戻り型 method 説明
Object getAttribute(String) 引数に指定されたデータ名に該当するデータ値を返す。該当のデータ名がない場合にはnullを返す。
Enumeration getAttributeNames() スコープで利用可能なすべてのデータ名を返す。
void removeAttribute(String) スコープから削除する。
void setAttribute(String,Object) 第一引数にデータ名、第二引数にデータ値を指定し、スコープにデータを登録。すでにデータ名が存在する場合は、新しく指定されたデータ値が上書き。