开发者

How to access Session state in standard Java class?

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?threa开发者_开发百科dID=5124189

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

Cheers


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.


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜