tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Craig R. McClanahan" <>
Subject Re: ServletContext.setAttribute()
Date Sat, 15 Jul 2000 00:45:19 GMT
Mason Jones wrote:

> Craig McClanahan wrote:
> >A common way for this to happen is for you to have old servlet classes on
> >your compile CLASSPATH -- such as the "jsdk.jar" file that contains
> >version 2.0 classes (before the ServletContext.setAttribute() method was
> >added to the API).
> You're a psychic. ;-) I had jsdk.jar in my CLASSPATH, alright,
> left over from pre-Tomcat days. Oops. All is well, thanks a lot.


> While I'm at it, though, I'm curious if there's a better way to
> do what I'm trying to do than I am now. I'm still testing, just
> to see what makes the most sense.
> In my servlet, I'm doing the following:
> ServletConfig sc = getServletConfig();
> ServletContext context = sc.getServletContext();
> context.setAttribute("formMessage","You got it?");
> That basically sends a message to the jsp page, which
> it then redirects to. In the jsp page I have to do the
> following to pull the message out:
> ServletConfig sc = getServletConfig();
> ServletContext context = sc.getServletContext();
> String formmsg = (String)context.getAttribute("formMessage");
> out.println(formmsg);
> That's kind of clunky, and it actually seems to be acting as
> if the attribute got put into the HttpSession, because it's
> still there if I go back to the jsp page later.

This does indeed send the message to the JSP page, but there is a problem --
the servlet context attributes are shared by *all* users of your application.
Context attributes stay there until you remove them, or until the server is
shut down.

What you probably want to do in use request attributes, rather than servlet
context attributes, so that the message is specific to this particular user
and it goes away after its been used (in the JSP page).  In your servlet, do

    String message = "You got it?";
    request.setAttribute("formMessage", message);
    RequestDispatcher rd =
    rd.forward(request, response);

> Is there a way to put the attribute in the page context, and
> an easier way to pull it out in the jsp?

In the JSP page, you can retrieve this by using a scriptlet, or (better) by a
bean with request scope:

    <jsp:useBean id="formMessage" scope="request" class="java.lang.String"/>
    The message is <%= formMessage %>.

NOTE:  You have to use RequestDispatcher.forward() rather than
response.sendRedirect(), because the redirect causes a *second* request, so
the message wouldn't be there.  In reality, you will want to do forwards
rather than redirects anyway because they save a round trip to the client.

> Thanks!
> ________________________________________
>   Mason Jones              mason(at)
>   Director of Software Development
>   ClipShow, Inc.  
>   (650) 696-3164           fax (650) 696-3267


View raw message