<jsp:useBean> はJSPページのJaveBeansをインスタンス化するJSPアクションタグです。
<jsp:useBean />
<jsp:useBean>
の使用例を次に示す。
<!DOCTYPE html>
<html>
<head>
<title>JSP useBean sample</title>
</head>
<body>
<jsp:useBean id="counter" scope="session" class="com.segakuin.example.Counter" />
<%
if((request.getParameter("reset")) != null)
counter.reset();
if((request.getParameter("inc")) != null)
counter.inc(count);
if((request.getParameter("dec")) != null)
counter.dec(count);
%>
<h1>カウンタの増減</h1>
<p>カウンタの値: <%= counter.getCount() %></p>
<form method="post" action="incsamp.jsp">
<input type="submit" name="inc" value="増やす">
<input type="submit" name="dec" value="減らす">
<input type="submit" name="reset" value="リセット">
</form>
</body>
</html>
Counter.java の内容を以下に示す。
package com.segakuin.example;
public class Counter {
int count;
public Counter() {
count = 0;
}
public void setCount(int c) {
count = c;
}
public int getCount() {
return count;
}
public void inc() {
count++;
}
public void dec() {
count--;
}
public void reset() {
setCount(0);
}
}
上記のJSPを実行した際、ブラウザに送信されるHTMLを次に示します(count
の値が3になっている状態の例)。
<!DOCTYPE html>
<html>
<head>
<title>JSP useBean sample</title>
</head>
<body>
<h1>カウンタの増減</h1>
<p>カウンタの値: 3</p>
<form method="post" action="incsamp.jsp">
<input type="submit" name="inc" value="増やす">
<input type="submit" name="dec" value="減らす">
<input type="submit" name="reset" value="リセット">
</form>
</body>
</html>
<jsp:useBean>
タグには次の属性を指定する。
<jsp:useBean id="employee" class="com.segakuin.example.Employee" />
スコープ | 変数の有効範囲 |
---|---|
page | JSPページ |
request | HTTPリクエスト |
session | HTTPセッション |
application | Webアプリケーション |
scope属性にpageスコープを指定すると、変数の有効範囲がそのJSPページになる。画面遷移がある場合、後続のJSPページで変数を参照することはできない。
<jsp:useBean id="employee" class="com.segakuin.example.Employee" scope="page"/>
scope属性にrequestスコープを指定すると、変数の有効範囲がそのHTTPリクエストになる。ひとつのHTTPリクエストを処理するモジュールが複数あった場合、それらすべてが有効範囲になる。
<jsp:useBean id="employee" class="com.segakuin.example.Employee" scope="request"/>
scope属性にsessionスコープを指定すると、変数の有効範囲がそのHTTPセッションになる。画面遷移がある場合、後続のJSPページでも変数を参照できる。
<jsp:useBean id="employee" class="com.segakuin.example.Employee" scope="session"/>
scope属性にapplicationスコープを指定すると、変数の有効範囲がウェブアプリケーション全体になる。HTTPリクエストやHTTPセッションに関わらず、すべてのJSPページから変数を参照できる。
<jsp:useBean id="department" class="com.segakuin.example.Department" scope="application"/>
<jsp:useBean id="employee" class="com.segakuin.example.Employee" />
JSPのアクションタグには、他にも次のタグがある。