Java EE web project on servlets. Tomcat 9 is used as a container. You need to write a ConnectionPool .

At the root of the project in the META-INF folder is the context.xml :

 <Context> <Resource name="list" type="javax.sql.DataSource" maxTotal="12" maxIdle="8" maxWaitMillis="10000" username="abc" password="abc" driverClassName="org.gjt.mm.mysql.Driver" url="jdbc:mysql://localhost/list" /> </Context> 

At the root of the project in WEB-INF in web.xml :

 <resource-ref> <description>MySQL DB Connection Pool</description> <res-ref-name>list</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> 

The connection pool itself:

  public class ConnectionPool { private static DataSource dataSource; private ConnectionPool() { } static { try { InitialContext initContext= new InitialContext(); dataSource = (DataSource) initContext.lookup("java:comp/env/list"); } catch (NamingException e) { e.printStackTrace(); } } public static Connection getConnection() throws SQLException { Connection connection = dataSource.getConnection(); return connection; } } 

The application crashes on the Connection creation line:

 Connection connection = dataSource.getConnection(); 

update: brought the name to one form (in context.xml, in web.xml in ConnectionPool)

Now instead of NullPointer I catch this:

 javax.servlet.ServletException: Servlet execution threw an exception org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) 

How to live?

    1 answer 1

    Your ConnectionPool written completely wrong. For some reason, you implemented it as a set of static fields and methods. Initializing the dataSource field You are also static and in case of failure you only print out the exception exception and continue to work as if nothing had happened. At the same time, the dataSource remains null , which results in a NullPointerException in getConnection() .

    • This approach describes more than one source, including English. Could you indicate the direction, how to implement the correct pool? I took out the correct handling of exceptions for brackets, I would like to first get to work, and then correctly catch, display an error in the console, pack into another exception and forward it above - Donatello
    • The idea was as follows: when loading a class, the dataSource is initialized, then in a specific DAO implementation you can pull out the connection as ConnectionPool.getConnection () - Donatello