FileDocCategorySizeDatePackage
ConnectionFilter.javaAPI DocExample2100Mon Nov 24 09:37:54 GMT 2003com.oreilly.patterns.chapter10

ConnectionFilter

public class ConnectionFilter extends Object implements Filter

Fields Summary
private DataSource
dataSource
Constructors Summary
Methods Summary
public voiddestroy()

    
public voiddoFilter(javax.servlet.ServletRequest request, javax.servlet.ServletResponse response, javax.servlet.FilterChain chain)
Retrieve a connection, run the filter chain, and return the connection.


        Connection con = null;
        
        try {
          con = dataSource.getConnection();
          
          // Set the connection, and retrieve the previous connection for 
          // disposal
          Connection previousCon = ConnectionManager.setConnection(con);
          if(previousCon != null) 
            try { previousCon.close(); } catch (SQLException e) {}

          // Run the rest of the filter chain.  
          chain.doFilter(request, response);
          
          // Make sure we disassociate the connection, just in case.
          ConnectionManager.setConnection(null);
        } catch (SQLException e) {
          ServletException se = new ServletException(e);
          throw se;
        } finally {
          if (con != null)
            try { con.close(); } catch (SQLException e) {}
        }
    
public voidinit(javax.servlet.FilterConfig filterConfig)
Create a datasource from a parameter defined in web.xml.

    
                  
          
        try {
            InitialContext iCtx = new InitialContext();
            Context ctx = (Context) iCtx.lookup("java:comp/env");
            dataSource = (DataSource) 
              ctx.lookup(filterConfig.getInitParameter("JNDI_datasource"));
        } catch (Exception e) {
            ServletException se = new ServletException();
            // Uncomment in JDK 1.4 for easier troubleshooting.
            // se.initCause(e); 
            throw se;
        }