0

I using my implementation ServletContextListener for writing in servlet context my object for work with database. In unit test my database handler work but same code in ServletContextListener throw java.sql.SQLException.

This is my database handler test which create Connection to DB and it's work. No exception no problem. All ok:

@Test
public void whenCreateDBJoinInstanceThenResultOfMethodGetDBExecutorNotNull() throws SQLException {
    final DBJoint db = new DBJointHandler("database_scripts", "authentication_database");
    Assert.assertNotNull(db);
    db.closeConnection();
}

This is use same DBJoint which create Connection to database:

@WebListener
public class ContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {

        final ServletContext servletContext = servletContextEvent.getServletContext();

        servletContext.setAttribute("db", new DBJointHandler("database_scripts", "authentication_database"));

    }
    ...
}

And this my result:

java.sql.SQLException: No suitable driver found for jdbc:postgresql://localhost:5432/user_storage

And place which throw this Exception:

public Connection getConnection() throws SQLException {

        return DriverManager.getConnection(
                properties.get("url"),
                properties.get("username"),
                properties.get("password")
        );

}

This is exactly the same code which in test. When i run test then it's ok. When i use ServletContextListener it's Exception.

What wrong? How fix this issue? Thank you.

Pavel
  • 2,005
  • 5
  • 36
  • 68
  • 1
    It is a problem with the JDBC driver not being loaded. Check out [this answer](https://stackoverflow.com/a/1911487/3586783) for tips on how to make sure the JDBC driver is loaded. – pacifier21 Jun 02 '17 at 03:19
  • 1
    @pacifier21 that Q&A is obsolete. It is no longer necessary to use Class.forName(...) to load JDBC drivers (since Java 5 in fact). – Steve C Jun 02 '17 at 03:23
  • 1
    You need to ensure that the PostgreSQL JDBC driver is available for your application by either including it in your WEB-INF/lib directory (assuming a WAR deployment) or installing it as part of your server (whatever that may be). – Steve C Jun 02 '17 at 03:25
  • 1
    Fair enough, but that doesn't change the fact that it is not finding the JDBC driver for postgresql. The driver needs to be in the proper path to get loaded into the environment. – pacifier21 Jun 02 '17 at 03:26
  • @Steve C I add jar of postgres in `WEB-INF/lib/` and `apache-tomcat/lib/` but same result. I Try call `Class.forName("com.example.jdbc.Driver");` in `ContextListener` but i had ClassNotFoundException. JDBCDriver is lost((( – Pavel Jun 02 '17 at 04:03
  • 1
    Exactly which jar did you add and where did it come from? Also, what version of Java are you using? – Steve C Jun 02 '17 at 04:06

0 Answers0