- スコープとはデータの有効範囲の事。
- Servletでは、requestスコープ、sessionスコープ、applicationスコープがある。
- httpセッション間でデータ共有するときは、request,sessionスコープ。
- webアプリ間では、applicationスコープ。
requestスコープ
- requestスコープでデータを操作する場合は、HttpServletRequestインタフェースのオブジェクトを使用。
- forwardメソッドなどでHttpServletRequestインタフェースのオブジェクトをリクエスト先に引き継ぐことでデータを共有。
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
・・・・・・・・・・・
req.setAttribute("userid", userid);
・・・・・・・・・・・
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 session = req.getSession();
session.setAttribute("userid", userid);
・・・・・・・・・・・
}
applicationスコープ
- ServletContextインタフェースのオブジェクトを使用します。
- このオブジェクトはHttpServletクラスのgetServletContextメソッドで取得できます。
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
・・・・・・・・・・・
ServletContext sc = getServletContext();
sc.setAttribute("userid", userid);
・・・・・・・・・・・
}
各スコープのデータ操作
戻り型 |
method |
説明 |
Object |
getAttribute(String) |
引数に指定されたデータ名に該当するデータ値を返す。該当のデータ名がない場合にはnullを返す。 |
Enumeration |
getAttributeNames() |
スコープで利用可能なすべてのデータ名を返す。 |
void |
removeAttribute(String) |
スコープから削除する。 |
void |
setAttribute(String,Object) |
第一引数にデータ名、第二引数にデータ値を指定し、スコープにデータを登録。すでにデータ名が存在する場合は、新しく指定されたデータ値が上書き。 |