Struts 1: how do i get session variable in DAO layer

2.3k Views Asked by At

I am using struts 1 (maintenance tasks on a legacy project). The application is tiered in ActionClasses calling Manager classes and Manager classes instantiating and using DAO layer classes/

I have to code conditional logic, where based on a session variable, I want DAO layer to switch between different DB2 schemas.

How do I read session in a DAO java class? One obvious way is to refactor manager/dao class constructors to pass along session variables all through call-chain

in struts 2, we use ActionContext.getContext().getSession();

is there something like that which I can do in struts 1 ?

---EDIT For all the purists (including me)-------------

I am working on this code-base, for prototyping updated business logic. This is a code that's inherited , wrote way back in 2003-2004. After prototyping, this code will not be used at-all, going straight to recycle-bin.

I understand that DAO doesn't need to access HTTP session, and that's what I follow when i write my code.

But my question is, is there a way to access session in DAO in struts 1 framework (filters/hacks?)

3

There are 3 best solutions below

0
On BEST ANSWER

The easiest is to have a thread local, maybe set in a filter or trivially-customized request processor, accessed via a static method. I feel dirty.

3
On

You don't do this. You'll be setting yourself for massive headaches in the future. Instead, pass the value through the call chain.

0
On

If you, like me, try ThreadLocal only to learn that the request can spawn child threads, you can use a combination of ServletRequestListener (Java EE) and RequestContextHolder (Spring-web) to achieve this:

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        ServletRequest sr = sre.getServletRequest();
        if(sr instanceof HttpServletRequest)
            // second parameter will let child threads inherit this object
            RequestContextHolder.setRequestAttributes(new ServletRequestAttributes((HttpServletRequest) sr), true);
    }
    
    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        ServletRequest sr = sre.getServletRequest();
        if(sr instanceof HttpServletRequest) {
            RequestContextHolder.resetRequestAttributes();
        }
    }

And then in any place you need the HttpSession:

            ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpSession httpSession = attr.getRequest().getSession(false); // true == allow create