I am trying to connect to Mysql from Jsp in Tomcat and I am getting Java.lang.NullPointer Exception. Please provide any help as soon as possible.
I have set the web.xml and the server.xml properly.
My web.xml contains:
<description>MySQL Test App</description>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
server.xml I have added this:
<Context path="/become3" docBase="become3"
debug="5" reloadable="true" crossContext="true">
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="localhost_become3_log." suffix=".txt"
timestamp="true"/>
<Resource name="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/TestDB">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<!-- Maximum number of dB connections in pool. Make sure you
configure your mysqld max_connections large enough to handle
all of your db connections. Set to -1 for no limit.
-->
<parameter>
<name>maxActive</name>
<value>100</value>
</parameter>
<!-- Maximum number of idle dB connections to retain in pool.
Set to 0 for no limit.
-->
<parameter>
<name>maxIdle</name>
<value>30</value>
</parameter>
<!-- Maximum time to wait for a dB connection to become available
in ms, in this example 10 seconds. An Exception is thrown if
this timeout is exceeded. Set to -1 to wait indefinitely.
-->
<parameter>
<name>maxWait</name>
<value>10000</value>
</parameter>
<!-- MySQL dB username and password for dB connections -->
<parameter>
<name>username</name>
<value>root</value>
</parameter>
<parameter>
<name>password</name>
<value>root</value>
</parameter>
<!-- Class name for mm.mysql JDBC driver -->
<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>
<!-- The JDBC connection url for connecting to your MySQL dB.
-->
<parameter>
<name>url</name>
<value>jdbc:mysql://localhost:3306/first?autoReconnect=true</value>
</parameter>
</ResourceParams>
</Context>
<%@ page import = "java.util.*" %>
<%@ page import = "java.sql.*" %>
<%@ page import = "javax.sql.*" %>
<%@ page import = "java.io.*" %>
<%@ page import = "javax.naming.*" %>
<html>
<head>
<title>DB Test</title>
</head>
<body>
<h2>Results</h2>
<%
try {
Connection con1 = null;
String connectionURL = "jdbc:mysql://localhost:3306/first";
String id = "";
Class.forName("com.mysql.jdbc.Driver").newInstance();
String sql = "select id from deals";
PreparedStatement pstmt2 = con1.prepareStatement(sql);
con1 = DriverManager.getConnection(connectionURL, "*******", "******");
out.println(con1);
ResultSet rs = pstmt2.executeQuery(sql);
while(rs.next()){
id = rs.getString(1);
}
out.println(id);
}
catch(Exception e){
e.printStackTrace();
}
%>
</body>
</html>