import java.sql.*; import javax.servlet.*; import java.io.*; import javax.servlet.http.*; import java.util.*; /****** * * DatabaseServlet: * A superclass for servlets that use a database. * The database and the connections are specified * in a configuration file (variable confile) using * parameters: * dbDriver * dbServer * dbLogin * dbPassword * This class supports only one database and one user account. * connections are not pooled. * * -- Harri Laine 5.1.2006 */ public class DatabaseServlet extends HttpServlet { // parameters for database connection protected static String dbDriver =null; protected static String dbServer = null; protected static String dbLogin = null; protected static String dbPassword = null; protected static boolean driverLoaded =false; // you may include here other initialization paramerers that // apply for all servlets public void init (ServletConfig config) throws ServletException { super.init(config); if (!driverLoaded) { String cFile = config.getServletContext().getInitParameter("confile"); // confile must be defined in deployment description Properties p = new Properties(); try { p.load(new FileInputStream(cFile)); dbDriver = (String) p.get("dbDriver"); dbServer = (String) p.get("dbServer"); dbLogin = (String) p.get("dbLogin"); dbPassword = (String) p.get("dbPassword"); // load the driver class Class.forName(dbDriver); driverLoaded =true; } catch (Exception f) { f.printStackTrace(); } } } /***** /* Open database connection */ public static Connection getConnection() { // returns a database connection or null if setting up the // connection fails Connection con=null; try { con= DriverManager.getConnection(dbServer,dbLogin,dbPassword); // here is a proper place for adjustments // language, data format, commit behaviour, timeout, etc. } catch (SQLException ignored) {} return con; } /**** /* Close database connection */ public static void closeConnection(Connection con) { try { con.close(); } catch (SQLException ignored) {} } }