Stephen Gray a écrit :

> Hello all,
>
> I've come across a problem with using private variables in custom tags
> with Tomcat. I have this tag class:
>
> public class TestTag extends TagSupport {
> private Date testDate = new Date();
>
> public int doStartTag() throws JspException {
> pageContext.setAttribute("date", testDate);
> return Tag.EVAL_BODY_INCLUDE;
> }
> }
>
> accessed from a jsp via: <t:Test>${date}</Test>
>
You doing it wrong, the specs tell you that the tag will not be altered
between begin of doStartTag() and exit doEndTag(), so you can not assume
the state of local variables to stay constant or be reset after
doEndTag() has been called. You don't even have guarantees the same tag
instance won't be used in separate pages :) If you take a look at
generated code from .jsp in catalina you will notice tomcat is doing tag
pooling.

I suggest you read details of doStartTag() and doEndTag() in javadoc:
http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/jsp/tagext/Tag.html#doStartTag()
http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/jsp/tagext/Tag.html#doEndTag()

In short:
The doStartTag method assumes that the properties pageContext and parent
have been set. It also assumes that any properties exposed as attributes
have been set too. When this method is invoked, the body has not yet
been evaluated.

That's all you can assume :)

in you case, i suggest you do


public int doStartTag() throws JspException {
testDate = new Date();
....

> There's also a tld file that defines the Test tag linked to the
> TestTag class with one variable (date).
>
> If I open my browser and go to the jsp it displays the current
> date/time. If I then open a browser on a different machine and go to
> the jsp it displays the same date/time, which means (I think) that
> Tomcat is creating one instance of my TestTag class in the application
> context and handing out references to it to all users.
>
> The problem with this is that private variables are usually used to
> store the value of tag attributes after they are set via setter
> methods. If 2 people access the tag at more or less the same time then
> there's a chance that one user's attributes will clobber the other's.

no, there is no clash, as a tag won't be shared between doStartTag() and
doEndTag()

>
> Can someone tell me whether I'm doing something wrong here - and if
> not perhaps Tomcat should be creating a separate instance of the tag
> class for each session?
>
Tomcat uses pooling for performance reason. A set of instances is reused
when it is safe to do so.

> Thanks,
> Steve
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: [EMAIL PROTECTED]
> For additional commands, e-mail: [EMAIL PROTECTED]
>

David Delbecq


---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to