3

Can some one help me?

How to pass session or request object from servlet to a java class either in some method or in constructor of java class.

SERVLET:

HttpSession session = request.getSession(true);

I want to pass this session object to java class and some one tell me how to retrieve and use.

Java Class

public class ProductsCart {

private Map<Integer, Integer> productsInCart=new HashMap<Integer,Integer>();

public Map<Integer, Integer> storeProductsInCart(int productId, int count) {

......

}

How to use session object in this class?

Thanks in advance. Anju

Anju
  • 167
  • 12

1 Answers1

-1

How ur flow is from you servlet till you reach this code (ProductsCart)? May be knowing that could help in providing a better suggestion.

One simple way to share context is this - If ur entire request is handled in a single thread (u don't have asynch call or not spawning new threads in between), u can use a thread local. You need to declare the thread local in a common place where both ur servlet class and ProductsCart class has visibility.

public class SessionContext {

    private static final ThreadLocal<HttpSession> activeSession = 
                                          new ThreadLocal<HttpSession>();

    public HttpSession getSession () {
        return activeSession.get();
    }

    public void setSession (HttpSession session) {
        activeSession.set(session);
    }
}

Now from u servlet class u can set it:

SessionContext.setSession(session);

And from ProductsCart u can access it.

HttpSession session = SessionContext.getSession()

There will one copy of thread local variable for every thread and as mentioned, this would work only if u are executing the entire flow from same thread. If u are spawning new thread, u may try InheritableThreadLocal. The new thread will inherit the valu from parent thread. But if u are using a thread pool or aynchrounous call, this will not work. In that case, it would be better to pass that to the class.

Also, when u return from servlet make sure to set it to null so that another request will not use it unknowingly.

Rajesh Jose
  • 314
  • 2
  • 12