views:

60

answers:

5

I need a mechanism to read session state from a Java class, without having to pass any arguments (including HttpRequest) to the class. The reason is that the class is 1-3 calls away from the servlet and i dont want to pollute the method argument list with an extra arg for every call. I basically have the same prob of these guys: http://forums.sun.com/thread.jspa?threadID=5124189

For which apparently Java does not have a solution currently..

Cheers

+3  A: 

The tempting mechanism is to use ThreadLocal storage, but in some App Servers this is dangerous - the App Server may use pools of Threads and a single request may be processed by different threads at different points.

Some App Servers (I know WebSphere does) offer a specific API for this purpose. In WAS it's a UserWorkArea. See here for a reference, a little way down the article.

I'm not aware of a portable solution to this problem.

djna
@djna: Yes, we are doing this in WAS. And for the same reason I didn't come up with this suggestion. So, I would say +1.
Adeel Ansari
Found this, http://www.devwebsphere.com/devwebsphere/2005/06/dont_use_thread.html. Quite old though, but I think its worth reading it.
Adeel Ansari
Thanks, im using Tomcat6 and not sure if it's 1 thread/request... will look into thread local - thanks!
Ricardo
+1  A: 

One solution could be the use of ThreadLocal. Be careful to clean it at the end of your request.

Jerome
how do i know when is the end of the request? do you know if i can use threadlocal safely inside struts interceptors?
Ricardo
A: 

The idea is to make things loosely coupled. If your class is not really a Servlet by any means, that should not depend on Servlet related stuff. Otherwise, it would become tightly coupled with Servlet API, and will make things difficult later on. For example writing a test for a loosely coupled classes is trivial. Further, you would be able to use the same class in some other environment, I mean other than web.

So, if you can tell us what are you up to, someone might come up with some design suggestions.

Adeel Ansari
+2  A: 

Do not pass HttpSession to you "standard" Java classes. For better solutions check dependency injection containers like Spring or Guice and read about session scope.

This is normally solved by a combination of a thread local pattern and a servlet filter, but it's normally bad to have "standard" Java classes to access session, request, and so on directly.

ps. Please do something about your accept rate.

lexicore
I quite agree. +1
Adeel Ansari
A: 

What you want is in effect a global variable, and "polluting" the parameter lists in your other classes is a lot cleaner. It gets easier to read and test.

If you want to avoid your code depending on servlet.jar, use the adapter pattern: Make an interface of the operations you need, let your methods accept an argument of that interface, and make a simple wrapper implementation of it that just delegates to the HttpSession.

gustafc