Clarifying the use of SessionFactory

As mentioned previously I have started using a SessionFactory approach when working with session to Domino using Corba/DIIOP. I forgot forever to mention that you should really combine the use of the SessionFactory with a servlet filter to recycle() the session once the thread has completed. The filter could be as simple as this:

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import dk.horisontnet.domino.SessionFactory;

public class CloseSessionFilter implements Filter {

   public void init(FilterConfig config) throws ServletException {
   }

   public void destroy() {
   }

   public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
                                            throws IOException, ServletException {
      // do work from other filters
      chain.doFilter(req, res);

      // close session
      SessionFactory.closeSession();
   }
}

The above filter uses a new method in the SessionFactory class called closeSession():

public static void closeSession() {
   try {
      // declarations
      Session session = null;

      // look for a session in the thread local
      session = (Session)pSession.get();
      if (null != session) {
         session.recycle();
         pSession.set(null);
      }
   } catch (Exception e) {
      // do nothing but log it
      logger.warn("Exception thrown while closing session to Domino", e);
   }
}

Deploy the filter via web.xml as described previously.

Update on 13/Feb/06: Remember to nullify the ThreadLocal (code in bold above) after recycling the Domino session to avoid having a recycled session being reused once the thread is reused from Tomcats thread pool. Failure to do so will result in the dreaded “Object no longer exists on server”-NotesException.