JGURU 에 올라온 글입니다. 날짜 상으론 꾀나 오래 된 글 입니다.
The jsp:useBean tag is very powerful. It allows you to declare a variable
using a single syntax, but produces code that (a) either initializes the
variable, or locates it if it’s already been initialized, and (b) stores it in
one of a number of locations, depending on its scope.
In order to share variables between JSPs and Servlets, you need to know how
to create and to access variables from inside your servlet code. Following are
examples which should help you understand how to do this.
———————————————————————-
<jsp:useBean
class="foo.Counter" scope="application" />
In this example, when the Counter bean is instantiated, it is placed within
the servlet context, and can be accessed by any JSP or servlet that belongs to
the application (i.e. belongs to the same servlet context).
The servlet equivalent of the above useBean action is:
foo.Counter counter = (foo.Counter)getServletContext().getAttribute("counter");
if (counter == null) {
counter = new foo.Counter();
getServletContext().setAttribute("counter", counter);
}
———————————————————————-
<jsp:useBean
id="counter" class="foo.Counter" scope="session" />
In this example, when the Counter bean is instantiated, it is placed within
the current session, and can be accessed by any JSP or servlet during a
subsequent request by the current user.
The servlet equivalent of the above useBean action is:
HttpSession session = request.getSession(true);
foo.Counter counter = (foo.Counter)session.getValue("counter");
if (counter == null) {
counter = new foo.Counter();
session.putValue("counter", counter);
}
———————————————————————-
<jsp:useBean
id="counter" class="foo.Counter" scope="request" />
In this example, when the Counter bean is instantiated, it is placed within
the current request object, and can be accessed by any JSP or servlet during a
the same request; e.g., if a RequestDispatcher is used, or if
<jsp:include> or <jsp:forward> sends the request to another servlet
or JSP.
The servlet equivalent of the above useBean action is:
foo.Counter counter = (foo.Counter)request.getAttribute("counter");
if (counter == null) {
counter = new foo.Counter();
request.setAttribute("counter", counter);
}
———————————————————————-
<jsp:useBean
id="counter" class="foo.Counter" scope="page" />
In this example the Counter bean is instantiated as a local variable inside
the JSP method. It is impossible to share a page scope variable with another JSP
or Servlet.
The servlet equivalent of the above useBean action is:
foo.Counter counter = new foo.Counter();