This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Would like ask about the scope of a custom taglib's class.
I have an arraylist declared inside the taglib class, outside of methods (private ArrayList abc = new ArrayList()).
In the doStartTag method, I put an abc.add("something");
Subsequently, i output the size of abc to my console.
When the JSP which calls this tag is run, each time it is refreshed, the abc size grows.
I would like to believe that taglib classes are instances (of page scope), much like Java beans where it is set such that scope = "page".
However, in my case, the arraylist looks to be shared across all pages in the application. (I expect the arraylist to always remain as size 1, as each jsp has its own instance of the taglib class, thus the arraylist is declared independently for each of the JSP page)
Ironically, if i were to put a string variable in the taglib class, and set it to some value through 1 JSP page, and then tries to retrieve the value of that variable via another JSP, the value will not be shared.
So how is it so that the arraylist acts like an application-scope or static variable?
TagSupport is a "classic" tag mechanism from JSP 1. The rules about instantiating and sharing such tags are complex and various containers may interpret them differently. I know I ran into a lot of trouble with that back "in the days".
As of 2002, JSP 2 introduced simplified "simple tags" that extend from SimpleTagSupprt. The rules are a lot more straight-forward; essentially tags cannot be shared and every use instantiates a new object.
I'd suggest catching up with modern times and using simple tags rather than obsolete classic tags.
Joined: Nov 06, 2012
Thanks Bear Bibeault, I see now.
Unfortunately, my current project is a legacy one, where the IDE and application server is restricted to older JSP standards.
So there is no firm way to say force a classic taglib to instantiate a new class (not shared) for each page I presume?
To avoid that problem you can override the release method in your class
You might also want to call this method from your Tag constructor. I am not 100% sure what the flow is but I think if you don't call it yourself it does not get called, someone that knows more about this please confirm/correct this statement!