First of all, I'm a computer science student, and I'm not very much into computer science world yet (i.e. I've little experience doing stuff on my own). So sorry for not having all the knowledge possible on it.
Then, in one of my classes I learnt how to create web application with java (jsp, beans, etc.) plus all the client-side stuff (html, css, javascript, ect.).
I work on NetBeans IDE.
To connect to a MySQL database, I use connection pooling in this way:
1) Add MySQL JDBC Driver jar
2) A DBConnect.java java class with a method that returns a connection:
public static Connection getConnection() {
/* JNDI query to locate the DataSource object */
Context initContext;
try {
initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env"); // JNDI standard naming root
DataSource ds = (DataSource) envContext.lookup("jdbc/aName");
/* Ask DataSource for a connection */
Connection conn;
try {
conn = ds.getConnection();
return conn;
} catch (SQLException ex) {
Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, ex);
throw new RuntimeException("cannot open Connection", ex);
}
} catch (NamingException ex) {
Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, ex);
throw new RuntimeException("cannot find DataSource reference", ex);
}
}
3) web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<resource-ref>
<description>Resource reference to a DataSource for managing a connection pool.</description>
<res-ref-name>jdbc/aName</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
4) context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/myApp">
<Resource
auth="Container"
driverClassName="com.mysql.jdbc.Driver"
maxActive="100"
maxIdle="30"
maxWait="10000"
name="jdbc/aName"
username="username"
password="password"
type="javax.sql.DataSource"
url="jdbc:mysql://"whateverhost":"whateverport"/dbSchema?autoReconnect=true"/>
</Context>
Now, I created a small project and I wanted to publish it online for free. I ran into OpenShift and I managed to push all my files on it (even if the folders' schema is different).
The problem is that the connection pooling doesn't work, and I don't have a clue on what to do.
Running the application, these are the exceptions:
java.lang.RuntimeException: cannot open Connection
....
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
....
java.sql.SQLException: No suitable driver
....
mysql-connector jar is in /WEB_INF/lib and pom.xml has:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
Maybe the solution is quite simple but I don't know what to do.
Thank you.
I think the problem is your web.xml file. It's redundant. Context.xml specifies a data source with the appropriate configuration and then web.xml specifies one without a URL or driver class name.
Try removing this resource-ref block from web.xml and try again:
<resource-ref>
<description>Resource reference to a DataSource for managing a connection pool.</description>
<res-ref-name>jdbc/aName</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
You also have extra quotes in your URL attribute in context.xml:
url="jdbc:mysql://"whateverhost":"whateverport"/dbSchema?autoReconnect=true"/>
Make this:
url="jdbc:mysql://whateverhost:whateverport/dbSchema?autoReconnect=true"/>
I'va ran into this problem myself on OpenShift and also on my Tomcat(that it was installed on personal PC).
It seems that the problem is related to the context.xml file.
Even if i edited the context.xml file that was in my cloned openshift project it seemed that the problem didn't dissappear.
I've managed to solve this on my personal machine by accessing eclipse server directory: /Servers/Tomcat v7.0 Server at localhost-config/context.xml
In the context.xml i had to manually add:
<Resource name="jdbc/MySQLPool"
url="jdbc:mysql://localhost:3306/sakila"
driverClassName="com.mysql.jdbc.Driver"
username="root"
password="nbuser"
auth="Container"
type="javax.sql.DataSource"
maxActive="20"
maxIdle="5"
maxWait="10000"
/>
Saved the file and everything was solved for the Tomcat on my PC.
At this moment i'm still trying to solve the OpenShift issue.
I am using eclipse, and even if i edit the context.xml that is in my OpenShift clone, it seems that somehow, the context.xml file on the OpenShift-Tomcat platform must be accessed and updated like in the previous example.
Hope this help !
Update:
I've managed to solve it for the OpenShift platform in the same manner.
By using Filezilla(guide for openshift can be found here: https://blog.openshift.com/using-filezilla-and-sftp-on-windows-with-openshift/ )
i've connected to the server, accesed the Tomcat directory(in my case: jbossews/conf/context.xml) and i've manually edited the file by adding the same xml Resource like above.
Hope it helps !
Related
Why connection is not working after few seconds? Application is hanging up and not running as expected and returning the below error.
java.lang.ClassCastException:
org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper
cannot be cast to org.apache.tomcat.dbcp.dbcp2.DelegatingConnection
Below is the code that is used to get the connection:
OracleConnection oracleConnection = (OracleConnection)
((DelegatingConnection)connection).getInnermostDelegate();
using libraries: commons-pool1.6.jar for encryption & tomcat-dbcp.jar for database.
Using encrypted username and password in Tomcat context.xml.
Also, using accessToUnderlyingConnectionAllowed=true in context.xml file.
Issue is with JAVA8 and Tomcat8. Able to work properly with plain credentials, the only issue happens with encrypted credentials.
You shouldn't do casting or unwrapping. Use correct DataSource type in Tomcat 'conf/context.xml' file. In case of Oracle it is: oracle.jdbc.pool.OracleDataSource.
Set also correct driver and factory.
Look at this example of mine:
<Context>
<!-- Default set of monitored resources. If one of these changes, the -->
<!-- web application will be reloaded. -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<Resource name="UNCUNC"
auth="Container"
type="oracle.jdbc.pool.OracleDataSource"
factory="oracle.jdbc.pool.OracleDataSourceFactory"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:#p260unc4.big.ru:1566:uncunc"
user="dsserv"
password="dsservPass"
connectionProperties="SetBigStringTryClob=true"
maxTotal="20" maxIdle="10"
maxWaitMillis="-1"/>
<JarScanner scanManifest="false"/>
Later in the java code use it like this (don't cast):
try {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("UNCUNC");
} catch (NamingException e) {
logger.error("DATASOURCE error", e);
}
Connection conn = ds.getConnection();
Should work just fine. Take attention in different versions of Tomcat you need to use 'username' instead 'user' field.
I faced the same issue. After a lot of analysis realized it was classloading issue. Fixed the issue by providing ojdbc jar in shared.loaded (in conf/catalina.properties)
shared.loader="/path/to/ojdbcN_jar/ojdbcN.jar"
This will make sure that the OracleConnection classes are loaded from the same jar in Tomcat and in the deployed webapp.
And in the application where OracleConnection is needed, use the below:
OracleConnection oracleConnection = connection.unwrap(OracleConnection.class);
Note: In my application I have ojdbc jar so that my application compiles fine, but when deployed, the jar used will be the one mentioned in shared loader.
Also don't forget to enable accessToUnderlyingConnectionAllowed when creating the Tomcat JDBC connection pool
I know there's many questions regarding this exception, however, I believe I've tried everything for many days, without any luck yet. As this is a production server, I can only work on this after midnight :(
I have a Tomcat app. Recently, I've updated the connection pool, in order to use Tomcat's jdbc-connection pool. In my Windows developing machine, everything works fine, but now that I'm trying to implement this on my Linux Server, I get this exception (see title) when ever my app tries to connect to MySQL.
I'm using "Easy Tomcat 7" which is supposed to be the same as the regular version of Tomcat, only it comes with the CPanel software.
I just need this DB to be available for this app (not multiple app's).
This is my java DB class:
public class DBUtil {
static DataSource ds;
static {
try {
Context context = new InitialContext();
ds = (DataSource)context.lookup("java:comp/env/jdbc/rhwebDB");
} catch (NamingException e) {
e.printStackTrace();
System.out.println("DBUtil.NamingException" + e);
} catch(Exception e) {
System.out.println(e);
}
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
This is my context.xml file, which is located on myAppDirectory/META-INF
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource
name="jdbc/rhwebDB"
auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
testWhileIdle="true"
testOnBorrow="true"
testOnReturn="false"
validationQuery="SELECT 1"
validationInterval="30000"
timeBetweenEvictionRunsMillis="30000"
maxActive="20"
minIdle="3"
maxIdle="15"
maxWait="10000"
initialSize="3"
removeAbandonedTimeout="60"
removeAbandoned="true"
logAbandoned="true"
minEvictableIdleTimeMillis="30000"
username="dbuser"
password="dbpwd"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/rhmexweb_rhweb"/>
</Context>
I don't use WAR files. I just upload files to my server and re-start tomcat when needed, which normally works just fine.
In case this is relevant too, Tomcat's server.xml file has this settings for this website. I've also tried adding parameter copyXML="true", with no luck so far:
<Host name="rhweb.net" appBase="webapps">
<Alias>www.rhweb.net</Alias>
<Context path="" reloadable="false" docBase="/home/rhweb/public_html" debug="1"/>
</Host>
Here's the full stacktrace I get when my app tries to establish a connection with MySQL:
javax.naming.NameNotFoundException: Name [jdbc/rhwebDB] is not bound in this Context. Unable to find [jdbc].
at org.apache.naming.NamingContext.lookup(NamingContext.java:820)
at org.apache.naming.NamingContext.lookup(NamingContext.java:154)
at org.apache.naming.NamingContext.lookup(NamingContext.java:831)
at org.apache.naming.NamingContext.lookup(NamingContext.java:154)
at org.apache.naming.NamingContext.lookup(NamingContext.java:831)
at org.apache.naming.NamingContext.lookup(NamingContext.java:168)
at org.apache.naming.SelectorContext.lookup(SelectorContext.java:158)
at javax.naming.InitialContext.lookup(InitialContext.java:415)
at util.DBUtil.<clinit>(DBUtil.java:23)
at Solutio.AdminRH.Entity.ISeguridadAdminDB.verificaUsuario(ISeguridadAdminDB.java:142)
at org.apache.jsp.menu_jsp._jspService(menu_jsp.java:115)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:200)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
I've also tried adding these lines in my app's web.xml file (which I hadn't had to include in my windows machine)
<resource-ref>
<description>MySQL RhWeb Datasource</description>
<res-ref-name>jdbc/rhwebDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
And when I include those lines, the exception I get is this one:
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
It seems that Tomcat can't find my META-INF/context.xml file, or it doesn't recognize this link:
ds = (DataSource)context.lookup("java:comp/env/jdbc/rhwebDB");
My linux, Tomcat and JDK versions are:
CentOS release 6.8 (Final)
Apache Tomcat/7.0.42
java version "1.7.0_131"
I don't know what else can I try to fix this. Any help will be really appreciated
UPDATE
I still haven't found a solution yet. I've realized some probable configuration issues that may be related to all this:
The app is located here:
/home/rhmexweb/public_html
However, on the Tomcat's server.xml file the host definition for this website is:
<Host name="rhweb.mx" appBase="webapps">
<Context path="" reloadable="false" docBase="/home/rhmexweb/public_html" />
</Host>
The reason why is not located on the webapps directory, is because CPanel automatically creates every account in /home/account-name/public_html, so that's why a context element is needed here (I guess). If I remove the whole Context tag, and instead I use appBase="/home/rhmexweb/public_html", then Tomcat won't find all the jars and content from the WEB-INF folder (/home/rhmexweb/public_html/WEB-INF). I mentioned this because I added the parameter copyXML="true" just to see where would tomcat tries to copy context.xml file, and if it changes it's name, but it turns out that there are two different paths. First I got a writing permissions exception when I first include that parameter, and it was trying to create a folder here:
/var/lib/easy-tomcat7/webapps/
This path, only contains folders of the default tomcat app's (manager, examples & host-manager)
The folder where all the websites are listed and all the compiled jsp files are is this one:
/usr/local/easy/etc/easy-tomcat7/Catalina/
however, in /usr/local/easy/etc/easy-tomcat7/Catalina/rhweb.mx/ there is no WEB-INF directory.
Anyway, what I'd like to know is if having a Context element in the host definition might be a problem for Tomcat in order to find the appPath/META-INF/context.xml file.
It looks like there is something wrong with the context.xml setup. Try server.xml or /META-INF/context.xml to see if it behaves any different.
You can try moving the configuration to the server.xml as per Tomcat 7 docs:
<GlobalNamingResources>
<Resource
name="jdbc/rhweb_rhwebDB"
auth="Container"
type="javax.sql.DataSource"
...
/>
</GlobalNamingResources>
link to global resource in the context.xml:
<Context>
<ResourceLink
global="jdbc/rhweb_rhwebDB"
name="jdbc/rhwebDB"
type="javax.sql.DataSource"
/>
</Context>
and then refer to it in /WEB-INF/web.xml like you already do:
<resource-ref>
<res-ref-name>jdbc/rhwebDB</res-ref-name>
<res-ref-type>javax.sql.DataSource</res-ref-type>
<res-auth>Container</res-auth>
</resource-ref>
If this won't work you can check few other approaches discussed in this answer.
I finally solved it!!
Maybe it's a workaround but it works.
I copied the app-directory/META-INF/context.xml file to:
$CATALINA_BASE/conf/[enginename]/[hostname]/context.xml.default
(notice the "default" part of the filename)
As it's stated in the Tomcat's documentation
Now I don't need to add any entry in my app's web.xml file, neither a META-INF/context.xml file in my app directory (which is not located on the Tomcat's/webapps directory)
All I need is to put a context.xml.default file (containing it's DB information) in every folder listed in this path:
$CATALINA_BASE/conf/[enginename]/
which in my server is:
/usr/local/easy/etc/easy-tomcat7/Catalina/
so for this website, I copied it to:
/usr/local/easy/etc/easy-tomcat7/Catalina/myDomain.com/
You'll notice my path is different from the one specified in Tomcat's documentation, and that's because I'm using CPanel's easy-tomcat 7 which has a different structure than the regular Tomcat. That fact made everything more complicated when looking for a solution, even if it's called easy-tomcat.
About why Tomcat could never read the /META-INF/context.xml, that remains a mistery, but honestly, I don't care much since this method it's easier (one file instead of two)
Please help,
I have a Java Spring MVC application (Tomcat 7) on OpenShift which is trying to use a resource lookup in Context.xml. I keep getting 500 errors when it tries to create the session session = (Session) envContext.lookup("mail/Session"); ( see code below ). There are no exceptions in the logs in app-root/logs/jbossews.log, e.printStackTrace(); doesn't print anything in the catch block. Do exceptions get logged somewhere else perhaps? I'm used to having a access.log and error.log in apache/tomcat, jbossews.log doesn't see to tell me anything (FYI I am not using RHC tools, I'm just tailing the log over ssh).
My project runs fine on my local system in eclipse with no issues.
Please help,
Thanks
Session session = null;
Context initalContext = new InitialContext();
Context envContext = (Context) initalContext.lookup("java:comp/env");
try{
// Blows up here with a 500 error
session = (Session) envContext.lookup("mail/Session");
}
catch (Exception e) {
// No StackTrace printed
e.printStackTrace();
}
Here is my resource located in jbossews/conf/context.xml
<Resource
name="mail/Session"
type="javax.mail.Session"
auth="Container"
mail.smtp.host="smtp.gmail.com"
mail.smtp.socketFactory.port="465"
mail.smtp.socketFactory.class="javax.net.ssl.SSLSocketFactory"
mail.smtp.auth="true"
mail.smtp.port="465"
mail.from="XXXXXX#mailserver.com"
mail.user="XXXXXX#mailserver.com"
password="XXXXXX"
/>
I tried adding the following to my web.xml to see if that would fix the problem (It didn't).
<resource-ref>
<description>Resource reference to a factory for javax.mail.Session instances that may be used for sending electronic mail messages, preconfigured to connect to the appropriate SMTP server.</description>
<res-ref-name>mail/Session</res-ref-name>
<res-type>javax.mail.Session</res-type>
<res-auth>Container</res-auth>
</resource-ref>
Figured out my issue was due to an issue in my pom.xml (Not related to accessing Context.xml after all). Annoyingly Exceptions weren't being logged in jbossews.log so I had to explicitly log them via Exception exception = (Exception) httpRequest.getAttribute("javax.servlet.error.exception");
exception.printStackTrace(); ( httpRequest being a HttpServletRequest Object)
The problem in my pom.xml was this, I tried using:
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.1</version>
<scope>provided</scope>
</dependency>
Using the following dependency solved the issue.
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.2</version>
</dependency>
Note: In order for the Context.xml "mail/Session" resource to work on OpenShift I had to create a lib folder in src/main/webapp/WEB-INF/ and place javax.mail-api.jar inside.
Hope this helps anyone else experiencing problems.
I'm rebuilding my development environment and I can't get JDBC working. I'm running Tomcat 7 under Eclipse Java EE Mars.2 and am using mysql-connector-java. Also Linux Mint 17.2. I upgraded to latest on a bunch of things but I don't think that's it.
When I start the Tomcat server under Eclipse, I keep getting the following. I'm not running it separately on this machine. Just under Eclipse.
SEVERE:
Servlet.service() for servlet [jsp] in context with path [] threw exception [javax.servlet.ServletException: javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "java.lang.NullPointerException"] with root cause
javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "java.lang.NullPointerException"
I assume this means it cannot find the driver? All the file structures are the same as my old PC. And the IDE is not complaining about anything missing. It's just when I try to start the server.
I added the mysql-connector-java-5.1.39-bin.jar to the Tomcat/lib folder. Specifically: /opt/apache-tomcat-7.0.69/lib. And I made sure the Server is referencing that folder. I also made sure it is not in the webapp's lib folder. This is how I always did it before.
I assume it's a driver thing. But maybe not? Can someone please suggest a good way to debug this? Because, I'm stumped...
META-INF/context.xml is as it's been from the previous environment. Password is correct and can connect from the IDE no problem.
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/mydbdb"
auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
driverClassName="com.mysql.jdbc.Driver"
testWhileIdle="true" testOnBorrow="true" testOnReturn="false"
validationQuery="SELECT /* ping */" validationInterval="30000"
timeBetweenEvictionRunsMillis="30000"
maxActive="100" minIdle="10" maxWait="10000" initialSize="10"
removeAbandonedTimeout="600" removeAbandoned="true" logAbandoned="true"
minEvictableIdleTimeMillis="30000"
jmxEnabled="true"
username="user" password="password"
useUnicode="true" useEncoding="true" characterEncoding="UTF-8"
url="jdbc:mysql://localhost:3306/mydb?useOldAliasMetadataBehavior=true&zeroDateTimeBehavior=convertToNull"
/>
<Resource name="mail/MailSession"
auth="Container"
type="javax.mail.Session"
mail.smtp.auth="false"
mail.smtp.host="localhost"
/>
</Context>
It is with great embarrassment that I admit I forgot to copy the web.xml file from the old environment... Doh! Sitting so close... Sometimes you can't see the forest for the trees.
If you double-click your Tomcat instance under Eclipse it will take you to the setting for the server, and from there you can select the "Open Launch Configuration" option where you can add your driver jar to the bootstrap classpath.
That said, I don't think the problem is a missing driver as that generally results in a "Class not found" exception. Check your logs carefully and maker sure you're not getting any errors. I'm making the assumption that you're letting Tomcat open your database connections to create a datasource. It seems like you don't have your data source configured in your Tioomcat server.xml and context.xml and therefore your servlet is throwing a null pointer exception when trying to use it.
Why does it say null URL and gives a empty ' ' class in the exception when I have provided the database URL?
I am trying to connect to a derby database via a servlet while using Tomcat. When the servlet gets run, I get the following exceptions:
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1452)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at servlets.servlet_1.doGet(servlet_1.java:23) // ---> Marked the statement in servlet
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:964)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.lang.NullPointerException
at sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(JdbcOdbcDriver.java:507)
at sun.jdbc.odbc.JdbcOdbcDriver.knownURL(JdbcOdbcDriver.java:476)
at sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(JdbcOdbcDriver.java:307)
at java.sql.DriverManager.getDriver(DriverManager.java:253)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1437)
... 24 more
Servlet :
package servlets;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.http.*;
import javax.servlet.*;
import javax.sql.DataSource;
public class servlet_1 extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
// String queryString = request.getQueryString();
System.out.println("!!!!!!!!!!!!!!!!!!!");
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/PollDatasource");
Connection connection = ds.getConnection(); // -->LINE 23
String sqlQuery = "select * from PollResult";
PreparedStatement statement = connection.prepareStatement(sqlQuery);
ResultSet set = statement.executeQuery();
System.out.println("after the final statement");
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
What exception is this? Why do I get this exception?
I have added the following tag in context.xml of Tomcat :
<Resource name="jdbc/PollDatasource" auth="Container" type="javax.sql.DataSource"
driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
url="jdbc:derby://localhost:1527/poll_database;create=true"
username="suhail" password="suhail"
maxActive="20" maxIdle="10" maxWait="-1" />
and this in web.xml :
<resource-ref>
<description>my connection</description>
<res-ref-name>jdbc/PollDatasource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
Where am I making a mistake?
Image that shows the database URL..
NOTE : After the answer by #Bryan Pendleton I changed the driver to org.apache.derby.jdbc.ClientDriver but I get the same exception.
I can't see anything obviously wrong, but perhaps a different approach might help you debug it?
You could try specify your datasource in the per-application-context instead of the global tomcat one.
You can do this by creating a src/main/webapp/META-INF/context.xml (I'm assuming you're using the standard maven directory structure - if not, then the META-INF folder should be a sibling of your WEB-INF directory). The contents of the META-INF/context.xml file would look something like:
<?xml version="1.0" encoding="UTF-8"?>
<Context [optional other attributes as required]>
<Resource name="jdbc/PollDatasource" auth="Container"
type="javax.sql.DataSource" driverClassName="org.apache.derby.jdbc.ClientDriver"
url="jdbc:derby://localhost:1527/poll_database;create=true"
username="suhail" password="suhail" maxActive="20" maxIdle="10" maxWait="-1"/>
</Context>
Obviously the path and docBase would need to match your application's specific details.
Using this approach, you don't have to specify the datasource details in Tomcat's context.xml file. Although, if you have multiple applications talking to the same database, then your approach makes more sense.
At any rate, give this a whirl and see if it makes any difference. It might give us a clue as to what is going wrong with your approach.
Several fixes:
Use the right driver class name for your environment: if you are using an out-of-process Derby server, then you want ClientDriver (and need to use derbyclient.jar), the hostname and port, etc. If you want an in-process Derby server, then you want derby.jar, EmbeddedDriver, and a URL that is appropriate for an embedded database.
Put your driver JAR file only in Tomcat's lib/ directory.
Don't put anything in Tomcat's conf/context.xml: there's really no reason for it. Instead, use your webapp's META-INF/context.xml to define your <Resource>.
The error "Cannot create JDBC driver of class '' for connect URL 'null' usually occurs because the JDBC driver is not in the right place (or in too many places, like Tomcat's lib/ directory but also in the webapp's WEB-INF/lib/ directory). Please verify that you have the right driver JAR file in the right place.
I was getting this problem because I put context.xml into the wrong path:
./src/main/resources/META-INF/context.xml
The correct path was:
./src/main/webapp/META-INF/context.xml
These two things don't match:
driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
url="jdbc:derby://localhost:1527/poll database;create=true"
If you are using the EmbeddedDriver, your URL should not contain network syntax.
Conversely, if you are using network syntax, you need to use the ClientDriver.
http://db.apache.org/derby/docs/10.8/getstart/rgsquck35368.html
If you are using eclipse, you should modify the context.xml, from the server project created in your eclipse package explorer. When using tomcat in eclipse it is the only one valid, the others are ignored or overwriten
Context envContext = (Context)initContext.lookup("java:comp/env");
not:Context envContext = (Context)initContext.lookup("java:/comp/env");
Did you try to specify resource only in context.xml
<Resource name="jdbc/PollDatasource" auth="Container" type="javax.sql.DataSource"
driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
url="jdbc:derby://localhost:1527/poll_database;create=true"
username="suhail" password="suhail"
maxActive="20" maxIdle="10" maxWait="-1" />
and remove <resource-ref> section from web.xml?
In one project I've seen configuration without <resource-ref> section in web.xml and it worked.
It's an educated guess, but I think <resource-ref> declaration of JNDI resource named jdbc/PollDatasource in web.xml may override declaration of resource with same name in context.xml and the declaration in web.xml is missing both driverClassName and url hence the NPEs for that properties.
The problem could also come because of a lack of SQL driver in your Tomcat installation directory.
I had to had mysql-connector-java-5.1.23-bin.jar in apache-tomcat-9.0.12/lib/ folder.
https://dev.mysql.com/downloads/connector/j/
In my case I solved the problem editing [tomcat]/Catalina/localhost/[mywebapp_name].xml instead of META-INF/context.xml.
I had this problem on a Tomcat 6. I had the Oracle jdbc driver .jar in two sites, one in the tomcat6/lib folder and in my C:/develop/lib folder which I was pointing on my catalina.properties file:
common.loader=${catalina.base}/lib,${catalina.base}/lib/*.jar,${catalina.home}/lib,${catalina.home}/lib/*.jar,C:/develop/lib/*.jar
One of these .jar must be deleted, the tomcat6/lib one or the common.loader one.
If you're using an embedded driver, the connectString is just
jdbc:derby:databaseName
(whith options like;create=true;user=xxx etc).
If you're using client driver, the connect string can be left as is, but if changing the driver gives no result... excuse the question, but are you 100% sure you have started the Derby Network Server as per the Derby Tutorial?
I had a similar problem using Tomcat against Oracle. I DID have the context.xml in the META-INF directory, on the disc. This file was not showing in the eclipse project though. A simple hit on the F5 refresh and the context.xml file appeared and eclipse published it. Everything worked past that. Hope this helps someone.
Try hitting F5 in eclipse