no suitable driver exception in connection pooling - java

I am trying to implement connection pooling using servlet. I know there are lots of similar questions has been asked but none is able to help.
Here is exception :
java.sql.SQLException: Cannot create JDBC driver of class for connect URL null at
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2160)
at
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2032)
at
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1532)
at
connection.CityInfoServlet.showCityInformation(CityInfoServlet.java:104)
at connection.CityInfoServlet.doGet(CityInfoServlet.java:76) 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:291)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source) Caused by:
java.sql.SQLException: No suitable driver at
java.sql.DriverManager.getDriver(Unknown Source) at
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2144)
... 27 more
I don't know why this exception show :
Caused by: java.sql.SQLException: No suitable driver.
I added jar file in WEB-INF/lib folder.
Here is my Servlet Code :
package connection;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
#WebServlet("/CityInfoServlet")
public class CityInfoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
DataSource dataSource = null;
public void init( ServletConfig config ) {
try{
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
dataSource = (DataSource) envContext.lookup("jdbc/worldDB");
}
catch( Exception exe )
{
exe.printStackTrace();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "City Information From Mysql Database";
out.print("<html><body bgcolor=\"#f0f0f0\">");
out.print("<h1 align=\"center\">" + title + "</h1>\n");
showCityInformation(out);
out.print("</body></html>");
}
private void showCityInformation( PrintWriter out )
{
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
String sql = "select * from city limit ?";
connection = dataSource.getConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, 10);
ResultSet rs = preparedStatement.executeQuery();
while( rs.next() )
{
int id = rs.getInt(1);
String name = rs.getString(2);
String countryCode = rs.getString(3);
String district = rs.getString(4);
int population = rs.getInt(5);
out.print("ID: " + id + "<br>");
out.print("Name: " + name+ "<br>");
out.print("CountryCode: " + countryCode+ "<br>");
out.print("District: " + district+ "<br>");
out.println("Population: " + population+ "<br>");
out.println("--------------------------------------"+ "<br>");
}
rs.close();
}
catch( Exception e )
{
e.printStackTrace();
}
finally
{
try {
if( preparedStatement != null ) {
preparedStatement.close();
}
}
catch( SQLException sqlException ){
sqlException.printStackTrace();
}
try
{
if( connection != null )
{
connection.close();
}
}
catch( SQLException sqlException )
{
sqlException.printStackTrace();
}
}
}
}
This is context.xml file
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/worldDB" auth="Container" type="javax.sql.DataSource"
maxTotal="100" maxIdle="30" maxWaitMillis="10000"
username="root" password="12345" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/world"/>
</Context>

Cannot create JDBC driver of class for connect URL null
The URL for the connection isn't set, so the JDBC libraries can't determine what driver to load.

I think that..
1 - you have to copy suitable driver to Server/lib folder
2 - If you have to created DataSource Connection context.xml on your project META-INF then modify
3 - WEB.xml of you project like this (add this)
<resource-ref>
<description>MySQLDatasource</description>
<res-ref-name>jdbc/worldDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
Then you can run this app http://localhost:8080/app_name - ok
but if you want to call this app from http://localhost:8080
then you have to
1 - add Context tag to your Server/conf/server.xml file
2 - add this line to your Server/conf/context.xml
<Resource name="jdbc/worldDB" auth="Container" type="javax.sql.DataSource"
maxTotal="100" maxIdle="30" maxWaitMillis="10000"
username="root" password="12345" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/world"/>
3 - restart server
then it will find this connection from Server context.

Related

Java Jee getting a Connection pool configured in context.xml

I'm making a webapp using JSP and MYSQL.
I have set up a connection pool and used it in a Servlet, but I cannot access it.
I had to create manually the "lib" folder inside WEB-INF to put the database connector and the META-INF folder to put the context.xml file, because those folders were not there at the begining.
I'm following a tutorial from 2016 so I don't know how different it is now.
Thanks in advance for your help.
Src folder:
Main files:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
</web-app>
context.xml
<Context>
<Resource name="jdbc/wishes" auth="Container" type="javax.sql.DataSource" maxActive="15" maxIdle="3" maxWait="5000" username="root" password="" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/jee">
</Resource>
</Context>
Servlet
package com.gabit.dev.makeawish.controllers;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
#WebServlet(name = "ServletDatabase", value = "/ServletDatabase")
public class ServletDatabase extends HttpServlet {
private static final long serialVersionUID = 1L;
#Resource(name = "jdbc/wishes")
private DataSource myPool;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter output = response.getWriter();
response.setContentType("text/plain");
Connection myConnection = null;
Statement myStatement = null;
ResultSet myResult = null;
try {
myConnection = myPool.getConnection();
String query = "SELECT * FROM wishes";
myStatement = myConnection.createStatement();
myResult = myStatement.executeQuery(query);
while (myResult.next()) {
String title = myResult.getString(2);
output.println(title);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Error
java.lang.NullPointerException: Cannot invoke "javax.sql.DataSource.getConnection()" because "this.myPool" is null
at com.gabit.dev.makeawish.controllers.ServletDatabase.doGet(ServletDatabase.java:31)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:683)
...
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:833)

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”/>

Failed to connect MySQL in IDEA 12.1.4

I had learn javascript on the base of code of my web. Then, I tried to develop a new web but failed. After google, I still don't have clues. So I ask for help here. Thanks for advance.
My IDEA is 12.1.4. The install process is:
1) I make new project by selecting "JavaEE Web Module";
2) I then copy previously java script to deal with mysql, and a part of code would be listed below;
package inhouse;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;
public class DBTool {
private DataSource ds = null;
private Connection conn = null;
private Statement stm = null;
private ResultSet rs = null;
private Context ctx = null;
public DBTool() throws NamingException{
this("editingphosphorylation");
}
public DBTool(String dbName) throws NamingException{
try{
ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/" + dbName);
}
catch (NamingException e) {
throw new NamingException("Can't get DataSource from pool: " + e.getMessage());
}
}
public Connection getConnection() throws SQLException{
conn = ds.getConnection();
return conn;
}
......
}
3) Add "resource-ref" to WEB-INF/web.xml;
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_2_5.xsd"
version="2.5">
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/editingphosphorylation</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
4) Download "mysql-connector-java-5.1.40-bin.jar", and put it to WEB-INF/lib;
5) With "View-Tool Windows-Database", I confirm mysql database could be accessed;
6) But when start tomcat, it output following error:
HTTP Status 500 - An exception occurred processing JSP page /geneList.jsp at line 26
type Exception report
message An exception occurred processing JSP page /geneList.jsp at line 26
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: An exception occurred processing JSP page /geneList.jsp at line 26
23:
24: try{
25: db = new DBTool();
26: conn = db.getConnection();
27: //Class.forName("com.mysql.jdbc.Driver").newInstance();
28: //Connection conn = java.sql.DriverManager.getConnection("jdbc:mysql://localhost:3306/editingphosphorylation","2pm","editingphosphorylation");
29: pst = conn.prepareStatement("select * from gene_sequence where geneName = ?");
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:455)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
javax.servlet.ServletException: org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:916)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:845)
org.apache.jsp.geneList_jsp._jspService(geneList_jsp.java:147)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1452)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
inhouse.DBTool.getConnection(DBTool.java:39)
org.apache.jsp.geneList_jsp._jspService(geneList_jsp.java:85)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NullPointerException
sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(JdbcOdbcDriver.java:524)
sun.jdbc.odbc.JdbcOdbcDriver.knownURL(JdbcOdbcDriver.java:493)
sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(JdbcOdbcDriver.java:307)
java.sql.DriverManager.getDriver(DriverManager.java:262)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1437)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
inhouse.DBTool.getConnection(DBTool.java:39)
org.apache.jsp.geneList_jsp._jspService(geneList_jsp.java:85)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Any geneList.jsp is like this
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# page import="inhouse.*, java.sql.*" %>
<%# page import="java.io.*" %>
<html>
<head>
<title>get gene list</title>
</head>
<body>
<% String geneName = request.getParameter("geneName");
DBTool db;
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
try{
db = new DBTool();
conn = db.getConnection();
//Class.forName("com.mysql.jdbc.Driver").newInstance();
//Connection conn = java.sql.DriverManager.getConnection("jdbc:mysql://localhost:3306/editingphosphorylation","2pm","editingphosphorylation");
pst = conn.prepareStatement("select * from gene_sequence where geneName = ?");
pst.setString(1, geneName);
rs = pst.executeQuery();
if(rs.next()){
rs.beforeFirst();%>
<table>
<th>
<td>Gene Name</td><td>Transcript Name</td><td>DNA Sequence</td><td>Protein Sequence</td>
</th>
<%while(rs.next()){
String geneNameRetrieve = rs.getString("geneName");
String transcriptNameRetrieve = rs.getString("transcriptName");
String dnaSequenceRetrieve = rs.getString("dnaSequence");
String proteinSequenceRetrieve = rs.getString("proteinSequence"); %>
<tr>
<td><%=geneNameRetrieve%></td><td><%=transcriptNameRetrieve%></td><td><%=dnaSequenceRetrieve%></td><td><%=proteinSequenceRetrieve%></td>
</tr><%
}%>
</table>
<%}else{%>
<div>No data.</div>
<%}
DBTool.close(rs, pst);
}finally {
DBTool.close(conn);
}%>
</body>
</html>
Compare with previously project, and according to google, I found the new project lack META-INF directory, so I make a new directory in web, and put a new context.xml into it.
<?xml version='1.0' encoding='utf-8'?>
<Context path="/">
<Loader delegate="true" />
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource name="jdbc/editingprosphorylation" auth="Container" type="javax.sql.DataSource"
maxActive="555" maxIdle="50" maxWait="10000"
timeBetweenEvictionRunsMillis="60000"
username="2pm" password="editingprosphorylation" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/editingprosphorylation"/>
</Context>
However, it doesn't work. After google, I hardly don't know how to do, Any suggestion would be grateful!
Typo:
editingphosphorylation (editingpHosphorylation)
editingprosphorylation (editingpRosphorylation)

Connect Servlet to MySQL database in eclipse [duplicate]

This question already has answers here:
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed 6 years ago.
I successfully connected database with simple java program using JDBC but when I am trying to connect database with Servlet, it gives me following errors and exceptions:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:8888/ebookshop
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at QueryServlet.doGet(QueryServlet.java:35)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:534)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
All severs running well and also I already added servlet and connecter API's in my library.
For more Information these are my html and servlet files are:
html file
<html>
<head><title>Yet Another Bookshop</title></head>
<body>
<h2>Yet Another Bookshop</h2>
<form method="get" action="http://localhost:9999/Sixth/query">
<b>Choose an author:</b>
<input type="checkbox" name="author" value="Tan Ah Teck">Ah Teck
<input type="checkbox" name="author" value="Mohammad Ali">Ali
<input type="checkbox" name="author" value="Kumar">Kumar
<input type="submit" value="Search">
</form>
</body>
</html>
My servlet:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class QueryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// JDK 6 and above only
// The doGet() runs once per HTTP GET request to this servlet.
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set the MIME type for the response message
response.setContentType("text/html");
// Get a output writer to write the response message into the network socket
PrintWriter out = response.getWriter();
Connection conn = null;
Statement stmt = null;
try {
// Step 1: Allocate a database Connection object
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:8888/ebookshop", "myuser", "xxxx"); // <== Check!
// database-URL(hostname, port, default database), username, password
// Step 2: Allocate a Statement object within the Connection
stmt = conn.createStatement();
// Step 3: Execute a SQL SELECT query
String sqlStr = "select * from books where author = "
+ "'" + request.getParameter("author") + "'"
+ " and qty > 0 order by price desc";
// Print an HTML page as the output of the query
out.println("<html><head><title>Query Response</title></head><body>");
out.println("<h3>Thank you for your query.</h3>");
out.println("<p>You query is: " + sqlStr + "</p>"); // Echo for debugging
ResultSet rset = stmt.executeQuery(sqlStr); // Send the query to the server
// Step 4: Process the query result set
int count = 0;
while (rset.next()) {
// Print a paragraph <p>...</p> for each record
out.println("<p>" + rset.getString("author")
+ ", " + rset.getString("title")
+ ", $" + rset.getDouble("price") + "</p>");
count++;
}
out.println("<p>==== " + count + " records found =====</p>");
out.println("</body></html>");
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You need to load your driver before you get a connection, something like that:
//Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
Here is a nice example: http://www.tutorialspoint.com/jdbc/jdbc-sample-code.htm
you should add this line,
Class.forName("com.mysql.jdbc.Driver");
As it is the first step to establish connection with JDBC driver,
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// Step 1: Allocate a database Connection object
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:8888/ebookshop", "myuser", "xxxx"); // <== Check!
// database-URL(hostname, port, default database), username, password
// Step 2: Allocate a Statement object within the Connection
stmt = conn.createStatement();
Provide that you added the mysql connector jar in your buidpath
As I see this jdbc:mysql://localhost:8888/ebookshop you have changed the default port of mysql from 3306 to 8888
If you did not change the port just use 3306 as the port for mysql
As the exception is saying No suitable driver found that obviously means you don't have the
mysql-connector-[version].jar in your classpath If you are using eclipse just place the jar under WEB-INF/lib and if you are using standalone tomcat just place the driver jar in the lib folder of Tomcat
try this
public static void connect() throws Exception {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost:3306/database_name?autoReconnect=true";
c = DriverManager.getConnection(url,"root","123");
}
thanx..

Access denied when attempting to connect to mysql from servlet in myeclipse

I'm trying to run a simple servlet/mysql webapp using tomcat server in my eclipse.
when I try to connect to the database from a servlet, I get the following error:
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create
PoolableConnectionFactory (Access denied for user ''#'localhost' (using password: YES))
below is the script that I executed:
The servlet:
import java.io.IOException;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
public class EmployeeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Resource(name = "jdbc/testDB")
DataSource ds;
public EmployeeServlet() {
super();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
Connection con = ds.getConnection();
Statement stmt = con.createStatement();
String query = "select * from Employee";
ResultSet rs = stmt.executeQuery(query);
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.print("<center><h1>Employee Details</h1></center>");
out.print("<html><body>");
out.print("<table border=\"1\" cellspacing=10 cellpadding=5>");
out.print("<tr><th>Employee ID</th>");
out.print("<th>Employee Name</th>");
out.print("<th>Salary</th>");
out.print("<th>Department</th></tr>");
while (rs.next()) {
out.print("<tr>");
out.print("<td>" + rs.getInt("emp_id") + "</td>");
out.print("<td>" + rs.getString("emp_name") + "</td>");
out.print("<td>" + rs.getDouble("salary") + "</td>");
out.print("<td>" + rs.getString("dept_name") + "</td>");
out.print("</tr>");
}
out.print("</table></body></html>");
} catch (SQLException e) {
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
content of context.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<Context crossContext="true">
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource name="jdbc/testDB" auth="Container"
type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="root"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/mysql">
</Context>
try connecting to mysql from any other tool / from command prompt with all the information you used in your code to connect to the same. Try including the port also in the connection url. Default port is 3306
Use mysql's GRANT query to give you permissions to access the database if you are accessing db from remote client.
seems port number missing in the url:
jdbc:mysql://localhost:<port>/mysql

Categories

Resources