Javier Guti�rrez wrote:

>          Hi,         How can I pass a reference to a JavaBean from a
> servlet to a JSP page?         Thanks.

There are actually three different ways to do it, depending on how long
the reference should last, and which JSP pages (and servlets, for that
matter) should be able to see it.  In each of the cases, assume that
"myBean" is a reference to the bean you want to send, and that "theBean"
is the key I'm going to use to store the bean under (from the servlet
perspective), and use as the identity of the bean in the JSP page.

These techniques are portable to any environment compliant with the
servlet API 2.1 and JSP 1.0 specifications.  In each case, the passing
works from servlet->JSP, servlet->servlet, JSP->JSP, or JSP->servlet
transitions.


(1) Request Lifetime

Use this technique to pass beans that are relevant to this particular
request to a bean you are calling through a request dispatcher (using
either "include" or "forward").  This bean will disappear after
processing this request has been completed.

SERVLET:
    request.setAttribute("theBean", myBean);
    RequestDispatcher rd =
        getServletContext().getRequestDispatcher('/thepage.jsp");
    rd.forward(request, response);

JSP PAGE:
    <jsp:useBean id="theBean" scope="request" class="....." />


(2) Session Lifetime

Use this technique to pass beans that are relevant to a particular
session (such as in individual user login) over a number of requests.
This bean will disappear when the session is invalidated or it times
out, or when you remove it.

SERVLET:
    HttpSession session = request.getSession(true);
    session.putValue("theBean", myBean);
    /* You can do a request dispatcher here,
        or just let the bean be visible on the
        next request */

JSP PAGE:
    <jsp:useBean id="theBean" scope="session" class="..." />


(3) Application LIfetime

Use this technique to pass beans that are relevant to all servlets and
JSP pages in a particular app, for all users.  For example, I use this
to make a JDBC connection pool object available to the various servlets
and JSP pages in my apps.  This bean will disappear when the servlet
engine is shut down, or when you remove it.

SERVLET:
    getServletContext().setAttribute("theBean", myBean);

JSP PAGE:
    <jsp:useBean id="theBean" scope="application" class="..." />

Craig McClanahan

===========================================================================
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff JSP-INTEREST".  For general help, send email to
[EMAIL PROTECTED] and include in the body of the message "help".

Reply via email to