Search code examples
javatomcatservlet-filtersactivejdbc

Tomcat + ActiveJDBC: open/close connection using servlet filter?


My web application uses ActiveJDBC. This ORM framework requires to open new DB connection with every new thread (and of course close it when the thread finishes). I am wondering if the best way to achieve this is to use a Web Filter.

if this is the case, where do I call Base.open()? the options are init() or doFilter(). also, if I plan to call Base.close() in destroy(), I need to know that indeed destroy() is always called at the thread termination, whether it is normal or abnormal.

EDIT: after reading about servlet filters, I now believe that the proper processing would be to open and close the connection in doFilter():

public void doFilter(final ServletRequest request, final ServletResponse response, FilterChain chain) throws IOException, ServletException { 
  Base.open();
  chain.doFilter(request,wrapper);
  Base.close(); 
} 

is this the correct way?


Solution

  • Yes, this is the correct way of opening and closing a connection for ActiveJDBC in a web environment.

    In addition to that, this is the right place to manage exceptions. For instance, you might want to manage transactions like this:

    try{
      Base.openTransaction(); 
      chain.doFilter(request,wrapper);
      Base.commitTransaction(); 
    }catch(Exception e){
      // log exception
      Base.rollbackTransaction();
    }finally{
      Base.close();
    }
    

    Ultimately rather than dealing with Servlets, why not give ActiveWeb a spin? See more here: http://javalite.io/database_configuration