Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to implement custom http session in java?

I will need to implement my own version of HttpSession in Java. I have found very little information which explains how achieve such a feat.

I guess my problem is - how do I override the existing HttpSession no matter the application server's implementation?

I did run across a quality but rather old read which helps me achieve my goal - http://java.sun.com/developer/technicalArticles/Servlets/ServletControl/

Are there any other approaches?

like image 449
plymouth5 Avatar asked Aug 20 '11 22:08

plymouth5


1 Answers

Its two ways.

"Wrapping" the original HttpSession in your own HttpServletRequestWrapper implementation.

I made this a short time ago for clustering distributed sessions with Hazelcast and Spring Session.

Here is explained pretty well.

First, implement your own HttpServletRequestWrapper

public class SessionRepositoryRequestWrapper extends HttpServletRequestWrapper {

        public SessionRepositoryRequestWrapper(HttpServletRequest original) {
                super(original);
        }

        public HttpSession getSession() {
                return getSession(true);
        }

        public HttpSession getSession(boolean createNew) {
                // create an HttpSession implementation from Spring Session
        }

        // ... other methods delegate to the original HttpServletRequest ...
}

After, from your own Filter, wraps the original HttpSession, and put it inside the FilterChain provided by your Servlet Container.

public class SessionRepositoryFilter implements Filter {

        public doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
                HttpServletRequest httpRequest = (HttpServletRequest) request;
                SessionRepositoryRequestWrapper customRequest =
                        new SessionRepositoryRequestWrapper(httpRequest);

                chain.doFilter(customRequest, response, chain);
        }

        // ...
}

Finally, set your Filter at the beginning in the web.xml to ensure it performs before any other.

The second manner to achieve it is providing to your Servlet Container your custom SessionManager.

For example, in Tomcat 7.

like image 158
Dani Avatar answered Oct 01 '22 22:10

Dani