Implication of scope and variables in JSP

I found out the hard way that using instance variables in JSP will inadvertently share data among different concurrent users. And when this data comes from a JDBC query which is specific to a user, it causes problems.

One way around this is to declare the page not thread-safe (isThreadSafe=false), but this is not recommended because it introduces latency.

I retrieve data from a JDBC bean with a scope of page, so I think there are no concurrency issues with the bean. However, the page that calls the bean passes some variables, some of which are arrays, when calling the bean.

I have been able to place most of this variable data in session variables, but there are some that I have not been able to do this with. Arrays, for example. I don't know how to initialize an array as a session variable and then access the individual array elements (still as a session variable) to place data in them.

While these seem to be my only two options (declaring page not threadsafe or using session variables exclusively) I also think it's possible that I'm completely confused on this and maybe I'm making this too complicated. Any discussion that would amplify this topic would be appreciated.

Thanks,

Glenn

[1256 byte] By [gwiens] at [2007-9-26 1:49:24]
# 1

Use application variables. Use setAttribute() with the ServletContext to register a handle to your array that can be used throughout your JSPs. You'll need to make sure two things though...

1) that all accesses to the array of database records are read-only, or

2) that all accesses to the array are controlled with 'synchronized' or synchronization techniques.

For example, you could define a jspInit() method that does the initial query, creates your array, and puts the variable into application scope using setAttribute("MyDatabaseQueryResults").

Subsequent JSPs could use getAttribute("MyDatabaseQueryResults") and a cast to access the array.

Just make sure that the jspInit() is the first thing called in your application; you don't want any JSPs to get a null 'MyDatabaseQueryResults' variable. If you use a controller that is accesed first in your Web app, and no other pages are accessed out of sequence, put the code in there.

BTW, you may want to switch to having a Servlet do this since by the time you register a jspInit for your page, your JSP will look very servlet-ish anyway.

CWalker807 at 2007-6-29 2:55:13 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...