Null Pointer Exception Running JDBC Tomcat Java [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have a SQL database which we managed to get connected using the proper drivers. Firstly here's the code
package com.Derp.test.blah;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.io.PrintWriter;
public class DBConnect {
String databaseURL;
String user;
String password;
public DBConnect(String inurl, String inuser, String inpass) {
databaseURL = inurl;
user = inuser;
password = inpass;
}
#SuppressWarnings("null")
public List<String> dbConnector() throws ClassNotFoundException {
System.out.println("dburl: "+databaseURL);
System.out.println("user: "+user);
System.out.println("pass: "+password);
List<String> imgPaths = null;
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(databaseURL, "service_manager", "watermelon");
if (conn != null) {
System.out.println("Connected to the database");
Statement s = conn.createStatement();
//Count the amount of users in the Accounts table with the user name of the query
System.out.println("Before executeQuery");
ResultSet rs = s.executeQuery("SELECT * FROM testable");
while(rs.next()){
System.out.println(rs.getString("imgpath"));
imgPaths.add(rs.getString("imgpath"));
}
System.out.println("Size of Images: " + imgPaths.size());
//return imgPaths;
}
} catch (SQLException ex) {
System.out.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
return imgPaths;
Ignore how horrible some parts of this code is please. In the while loop
System.out.println(rs.getString("imgpath"));
Is printing out results to the console that are in the SQL database, however I am unable to add the results to the imgPaths String List, and am getting the following error.
Jan 30, 2019 10:20:20 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.Derp.test.blah.TestServlet] in context with path [/BlahTest] threw exception
java.lang.NullPointerException
at com.Derp.test.TestBlah.DBConnect.dbConnector(DBConnect.java:39)
at com.Derp.test.TestBlah.TestServlet.doGet(TestServlet.java:140)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:791)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Null pointer exception... Any help would be greatly appreciated.

Your imgPaths variable is initialized to null. Change the initialization to a list object then it would allow you to add items.

Related

When trying to display a list of books from the database on the jsp page , i have Null value for 'password' [duplicate]

This question already has answers here:
Where to place and how to read configuration resource files in servlet based application?
(6 answers)
getResourceAsStream() vs FileInputStream
(6 answers)
Closed 11 months ago.
I has been develop webapp via servelt + jsp , apache tomcat and postgresql and have problems with connection to database. I don't understand how it's decide.
Exception :
org.postgresql.util.PSQLException: Something unusual has occurred to cause the driver to fail. Please report this exception.
at org.postgresql.Driver.connect(Driver.java:285)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:681)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:229)
at org.postgresql.ds.common.BaseDataSource.getConnection(BaseDataSource.java:103)
at org.postgresql.ds.common.BaseDataSource.getConnection(BaseDataSource.java:87)
at ua.dragunov.library.dao.UserDAO.getAll(UserDAO.java:93)
at ua.dragunov.library.service.UserService.getAll(UserService.java:33)
at ua.dragunov.library.servlets.BookListServlet.doGet(BookListServlet.java:19)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:889)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1743)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.lang.IllegalArgumentException: Null value for 'password'
at org.postgresql.shaded.com.ongres.scram.common.util.Preconditions.checkNotNull(Preconditions.java:41)
at org.postgresql.shaded.com.ongres.scram.common.util.Preconditions.checkNotEmpty(Preconditions.java:55)
at org.postgresql.shaded.com.ongres.scram.client.ScramSession$ServerFirstProcessor.clientFinalProcessor(ScramSession.java:128)
at org.postgresql.jre7.sasl.ScramAuthenticator.processServerFirstMessage(ScramAuthenticator.java:147)
at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:778)
at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:161)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:213)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:51)
at org.postgresql.jdbc.PgConnection.\<init\>(PgConnection.java:225)
at org.postgresql.Driver.makeConnection(Driver.java:465)
at org.postgresql.Driver.connect(Driver.java:264
UserDAO code :
#Override
public List<User> getAll() {
List<User> users = new ArrayList<>();
try(Connection connection = dataSource.getConnection()) {
Statement getAllStatement = connection.createStatement();
ResultSet resultSet = getAllStatement.executeQuery("SELECT * FROM users");
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getLong(1));
user.setLogin(resultSet.getString(2));
user.setEmail(resultSet.getString(3));
user.setPassword(resultSet.getString(4));
users.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}
My DataSource code :
public class LibraryDataSource {
private static final Logger LOGGER = Logger.getLogger(LibraryDataSource.class);
private LibraryDataSource() {}
public static DataSource getLibraryDataSource() {
PGSimpleDataSource libraryDatasource = new PGSimpleDataSource();
try(FileReader propertiesReader =
new FileReader("src/main/resources/application.properties")) {
Properties databaseProperties = new Properties();
databaseProperties.load(propertiesReader);
libraryDatasource.setURL(databaseProperties.getProperty("databaseUrl"));
libraryDatasource.setUser(databaseProperties.getProperty("databaseUser"));
libraryDatasource.setPassword(databaseProperties.getProperty("databasePassword"));
} catch (FileNotFoundException e) {
LOGGER.info("LibraryDataSource::getLibraryDataSource : ", e);
} catch (IOException e) {
LOGGER.info("LibraryDataSource::getLibraryDataSource : ", e);
}
return libraryDatasource;
}
}
I tried to choose any version of tomcat and i was test on main method and in main method it's work. All data from the database is pulled, but have some problems on server

I'm not executing anything and it's still saying Cannot close a connection while a transaction is still active

I keep on getting this error and I'm not sure why. Here is the code. Im not even executing any sql and it's still saying "Cannot close a connection while a transaction is still active"
DataAccess da = new DataAccess();
int param = Integer.parseInt(request.getParameter("geoAreaID"));
try (Connection tempConnection = DataAccess.OpenConnection())
{
tempConnection.rollback();
tempConnection.close();
}
catch (SQLException e)
{
e.printStackTrace();
System.exit(e.getErrorCode());
}
catch (Exception e)
{
e.printStackTrace();
System.exit(2);
}
The DataAccess class has the method to open the connection, here it is.
public static Connection OpenConnection() throws SQLException
{
Properties tempConnectionProperties = new Properties();
tempConnectionProperties.put("user", CONNECTION_USER);
tempConnectionProperties.put("password", CONNECTION_PASSWORD);
Connection tempConnection = DriverManager.getConnection(CONNECTION_STRING, tempConnectionProperties);
tempConnection.setAutoCommit(true);
tempConnection.createStatement().executeUpdate("SET SCHEMA APP");
return tempConnection;
}
this is the full error message
java.sql.SQLException: Cannot close a connection while a transaction is still active.
at org.apache.derby.client.am.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.client.am.ClientConnection.closeResourcesX(Unknown Source)
at org.apache.derby.client.am.ClientConnection.closeX(Unknown Source)
at org.apache.derby.client.am.ClientConnection.close(Unknown Source)
at org.apache.derby.client.net.NetConnection.close(Unknown Source)
at dkaru.servlets.GeographicAreaServlet.doGet(GeographicAreaServlet.java:36)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Caused by: ERROR 25001: Cannot close a connection while a transaction is still active.
at org.apache.derby.client.am.ClientConnection.checkForTransactionInProgress(Unknown Source)
... 29 more
Setting the auto commit property of the connection worked for me. Code shown below :
conn.setAutoCommit(true);

POSTGRESQL: This connection has been closed on prepareStatement

My error is this:
org.postgresql.util.PSQLException: This connection has been closed.
at org.postgresql.jdbc.PgConnection.checkClosed(PgConnection.java:766)
at org.postgresql.jdbc.PgConnection.prepareStatement(PgConnection.java:1582)
at org.postgresql.jdbc.PgConnection.prepareStatement(PgConnection.java:372)
at com.ifpb.pw1.sysfood.dao.impl.UsuarioDaoBD.buscar(UsuarioDaoBD.java:61)
at com.ifpb.pw1.sysfood.managers.GerenciadorUsuario.buscaUsuario(GerenciadorUsuario.java:37)
at com.ifpb.pw1.sysfood.command.impl.Login.execute(Login.java:55)
at com.ifpb.pw1.sysfood.servlets.FrontController.processRequest(FrontController.java:26)
at com.ifpb.pw1.sysfood.servlets.FrontController.doPost(FrontController.java:48)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:491)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:764)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1388)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
But before my application authenticates the user through a query in the database (postgresql), and does not present any error.
But when I query to get the user data I get the following error (as shown above).
My code is this:
public Usuario buscar(String email) {
try {
String sql = "SELECT * FROM Usuario WHERE email = ?";
PreparedStatement stmt = conexao.prepareStatement(sql);
stmt.setString(1, email);
ResultSet resultado = stmt.executeQuery();
if(resultado.next()){
Usuario u = new Usuario(
resultado.getInt("id"),
resultado.getString("nome"),
resultado.getString("email"),
resultado.getString("profissao"),
resultado.getString("sexo"),
resultado.getBytes("fotoPerfil")
);
System.out.println("User from dao: " + u);
resultado.close();
stmt.close();
conexao.close();
return u;
}
resultado.close();
stmt.close();
conexao.close();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
Is something wrong with my code? What is wrong? can you help me?
I've done a lot of research, but so far I can not find anything about it.

Cannot create JDBC driver of class '' for connect URL 'jdbc:mysql://localhost:3306/web13?useSSL=false&serverTimezone=UTC'

I created a properties file
url=jdbc:mysql://localhost:3306/web13?useSSL=false&serverTimezone=UTC
username=root
password=root
and I created a connection pool
private static DataSource dataSource;
static {
try {
//load properties file
InputStream is = DBCPUtils.class.getClassLoader().getResourceAsStream("db.properties");
//load input stream
Properties props = new Properties();
props.load(is);
//create data source
dataSource = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
Then I got the problem. I searched some anwsers, they said driver needs to be registered like Class.forName(com.mysql.jdbc.Driver). But my version of driver seems to be able to register by itself, so this solution can not work.
Error:
Oct 02, 2018 9:46:09 AM org.apache.catalina.core.StandardContext
reload INFO: Reloading Context with name [/WEB13] is completed
java.sql.SQLException: Cannot create JDBC driver of class '' for
connect URL
'jdbc:mysql://localhost:3306/web13?useSSL=false&serverTimezone=UTC'
at
org.apache.commons.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2224)
at
org.apache.commons.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2104)
at
org.apache.commons.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1563)
at
org.apache.commons.dbutils.AbstractQueryRunner.prepareConnection(AbstractQueryRunner.java:319)
at org.apache.commons.dbutils.QueryRunner.query(QueryRunner.java:327)
at com.itheima.login.LoginServlet.doGet(LoginServlet.java:36) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:634) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:741) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:770)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
at
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748) Caused by:
java.sql.SQLException: No suitable driver at
java.sql.DriverManager.getDriver(DriverManager.java:315) at
org.apache.commons.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2209)
... 29 more
Your properties file is missing a property, which means the DBCP is not able to create/initialize the driver.
You need to add
driverClassName = org.mysql.jdbc.Driver
#Ziyan Zhu,
You have added wrong url in db.properties:
url in db properties be like jdbc:mysql://localhost:3306/web13 where web13 is your database name.
In addition you are missing some method in your connection pool as described over here
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
public class DBCPUtils {
private static DataSource dataSource;
static {
try {
// 1.Load the properties file input stream
InputStream is = DBCPUtils.class.getClassLoader().getResourceAsStream("db.properties");
// 2.Load the input stream
Properties props = new Properties();
props.load(is);
// 3.create data source
dataSource = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static DataSource getDataSource() {
return dataSource;
}
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
i just had the same problem, but i was working with glassfish. if there is anyone in the future who has this problem attempting establishing a database connection in glassfish server, the solutions is to add java mysql connector to glassfish server then your problem is solved.
go to .../glassfish-installation-folder/Glassfish[your-version]/glassfish/lib/here-paste-your-mysql-connector-driver.jar
it's my pleasure. :)

JDBC data source not working when project deployed on tomcat

I have developed a servlet which calls a MariaDB database through a JDNI datasource. This works fine when I run the web project within eclipse on a tomcat server run within eclipse.
However, when I deploy the project on a tomcat server outside eclipse, using a WAR file, the same servlet does not work. For testing purposes, the project also contains another servlet that connect directly (i.e. not using the JDNI datasource) to the same mariaDB and it works fine even when deployed to tomcat server outside eclipse.
I am running out of ideas concerning what could possibly be wrong and would greatly appreciate if someone could shed some light.
Configuration information:
OS : macOS High Sierra
tomcat version : 8.5
eclipse : Neon.2., release 4.6.2
Java : 8
MariaDB driver : mariadb-java-client-2.2.0
Outiside eclipse, The driver is in two locations:
/tomcat-folder/lib
/tomcat-folder/webapps/my-app/WEB-INF/lib (from the WAR file)
I have added the following resource reference to the application web.xml file:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/MYDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
I have added the following resource to /tomcat-folder/contf/context.xml:
<Resource name="jdbc/MYDB” auth="Container" type="javax.sql.DataSource"
maxTotal="100" maxIdle="30" maxWaitMillis="10000"
username="root" password="" driverClassName="org.mariadb.jdbc.Driver"
url="jdbc:mariadb//localhost:3306/MYDB”/>
The error I get is :
java.sql.SQLException: Cannot create JDBC driver of class 'org.mariadb.jdbc.Driver' for connect URL 'jdbc:mariadb//localhost:3306/MYDB'
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2167)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2037)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1543)
at DBConfigTest.getConnection(DBConfigTest.java:123)
at DBConfigTest.doGet(DBConfigTest.java:59)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1437)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.sql.SQLException: No suitable driver
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2158)
... 28 more
java.lang.NullPointerException
at DBConfigTest.doGet(DBConfigTest.java:61)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1437)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
the servlet code is as follows:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DBConfigTest extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// JDBC driver name and database URL
// static final String JDBC_DRIVER = "org.mariadb.jdbc.Driver";
// static final String DB_URL="jdbc:mariadb://localhost/MYDB"+"?user=root&password=";
// Database credentials
// static final String USER = "root";
// static final String PASS = "";
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n");
// Execute SQL query
//Statement stmt=null;
//Connection conn=null;
Connection connection=null;
PreparedStatement statement=null;
try {
// Register JDBC driver
//Class.forName("org.mariadb.jdbc.Driver");
// Open a connection
//conn = DriverManager.getConnection("jdbc:mariadb://localhost/MYDB"+"?user=root&password=");
connection = getConnection();
String sql = "SELECT * FROM ingredient";
statement = connection.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
// Execute SQL query
/*stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM ingredient";
ResultSet rs = stmt.executeQuery(sql);*/
// Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("ingredient_id");
String code = rs.getString("ingredient_code");
String description = rs.getString("ingredient_description");
//Display values
out.println("ID: " + id + "<br>");
out.println(", Code: " + code + "<br>");
out.println(", Description: " + description + "<br>");
}
out.println("</body></html>");
// Clean-up environment
rs.close();
statement.close();
connection.close();
} catch(SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if(statement!=null)
statement.close();
} catch(SQLException se2) {
} // nothing we can do
try {
if(connection!=null)
connection.close();
} catch(SQLException se) {
se.printStackTrace();
} //end finally try
} //end try
}
private Connection getConnection() {
Connection connection = null;
try {
/*InitialContext context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("jdbc/MYDB");
connection = dataSource.getConnection();*/
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/MYDB");
connection = ds.getConnection();
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
The url in the example below should be url="jdbc:mariadb://localhost:3306/MYDB”. A colon (:) in the JDBC URL, after mariadb and before //, was missing.
<Resource name="jdbc/MYDB” auth="Container" type="javax.sql.DataSource"
maxTotal="100" maxIdle="30" maxWaitMillis="10000"
username="root" password="" driverClassName="org.mariadb.jdbc.Driver"
url="jdbc:mariadb//localhost:3306/MYDB”/>

Categories

Resources