Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Scope of Instance Variables in Custom Tag

Status
Not open for further replies.

mingus

Programmer
May 8, 2001
59
0
0
US
Say you have a class with an instance scope like belong.
Once you set the variable you set it not for just the current user but all users of the web site. How can I can I make an instance variable accessible to only the current session?


Below "a" is only null the first time any user hits the customer tag, all users after that will have the value filled:

public class X extends BodyTagSupport {

private String a;

public int doStartTag() {
if (a == null)
a = "x";
}

public int doEndTag() {
if (x.equals("SSSS"))
doSomething();
return EVAL_BODY;
}
}
 
Code:
public class X extends BodyTagSupport {

   private String a;

   public int doStartTag() {
         if (a == null)
                a = "x";
   }

   public int doEndTag() {
          if (x.equals("SSSS"))
                  doSomething();
          return EVAL_BODY;
   }
}
The above sets variable [tt]a[/tt] for the custom tag. I know servlets are only instantiated once; it appears that tags are as well.

There are two ways you could address this:
- reset [tt]a=null;[/tt] in [tt]doEndTag()[/tt]
- (better way) set a SESSION_SCOPE attribute.

BodyTagSupport provides the method [tt]getPageContext[/tt]. You can use the page context to set the attribute:

Code:
public class X extends BodyTagSupport {

   private String a;

   public int doStartTag() {

         [red]a = (String) pageContext.getAttribte("attNameHere", pageContext.SESSION_SCOPE);[/red]
         if (a == null)
                a = "x";
   }

   public int doEndTag() {
          if (x.equals("SSSS"))
                  doSomething();
          return EVAL_BODY;
   }
}

You'll need to cast it - pageContext.getAttribute returns an Object. Somewhere along the way, you'll want to change your session scope attribute:
Code:
      String x = "something";
      pageContext.setAttribute("attNameHere", x, pageContext.SESSION_SCOPE);

<marc>
New to Tek-Tips? Get better answers - faq581-3339
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top