ClassNotFoundException oracle.jdbc.driver.OracleDriver only in servlet, using Eclipse [duplicate] - java

This question already has answers here:
How to add JAR libraries to WAR project without facing java.lang.ClassNotFoundException? Classpath vs Build Path vs /WEB-INF/lib
(5 answers)
Closed 7 years ago.
The code below fails on the line:
Class.forName("oracle.jdbc.driver.OracleDriver");
with the error:
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
The two printlns print:
Wed_Jun_22_11:18:51_PDT_2005
false
This makes me think the class exists and can be found. Also this exact same class works in an a non-servlet application.
I have rebooted everything multiple times and regenerated the application/servlet multiple times. All values have been hard coded to make it simple and short.
private static Connection getDBConnection() throws Exception {
System.out.println(oracle.jdbc.driver.OracleDriver.BUILD_DATE);
System.out.println(Class.class.desiredAssertionStatus());
//load the driver
Class.forName("oracle.jdbc.driver.OracleDriver");
return DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl", "SYSTEM", "pass");
}
full servlet that fails:
package servletClass_3;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class OneMoreBookStore
*/
#WebServlet("/OneMoreBookStore")
public class OneMoreBookStore extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
private static Connection getDBConnection() throws Exception {
System.out.println(oracle.jdbc.driver.OracleDriver.BUILD_DATE);
System.out.println(Class.class.desiredAssertionStatus());
//load the driver
Class.forName("oracle.jdbc.driver.OracleDriver");
return DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl", "SYSTEM", "pass");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
Connection con = getDBConnection();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
This application works:
package servletClass_3;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnect {
private static Connection getDBConnection() throws Exception {
System.out.println(oracle.jdbc.driver.OracleDriver.BUILD_DATE);
System.out.println(Class.class.desiredAssertionStatus());
//load the driver
Class.forName("oracle.jdbc.driver.OracleDriver");
return DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl", "SYSTEM", "pass");
}
public static void main(String[] args) {
try
{
Connection con = getDBConnection();
System.out.println("connection worked");
con.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
I'm using:
Eclipse JavaEE 1.4.2
Tomcat 7
jdk1.7
Oracle 11g R2
Windows 7 64bit

Probably you aren't deploying the oracle driver with your application.
You have several options:
You can place the driver jars in your WEB-INF/lib folder
You export it with your application. -> Right Click on Project -> Build Path-> Configure Build Path... -> Order and Export -> Check the drivers.
Place the driver jars in a shared or library extension folder of your application server. (You should go with option one or two though.)

You must include the ojdbc6.jar file in the Deployment Assembly of the Project...
select the web project which contains the jsp file...
select Project tab in the menu bar in Eclipse
select properties in the drop down menu
select Deployment Assembly
Add your ojdbc6.jar file in it.

Try this, change the oracle.jdbc.driver.OracleTypes to oracle.jdbc.OracleTypes

Related

How to add Mysql JDBC to servlet project on Intellij idea MacOs Tomcat

To add it I tried sevral methods that I found online but none of them worked for me.
Here is how I try to import the driver:
1- I tried the method in the answer : Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project
2- I go to File ==> Project Structure==> Libraries then I add the mysql connecter .jar
Here is my Java class for the connection :
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
public class DbConnection {
private static Connection connection;
static {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/supermarche", "root","password");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Connection getConnection() {
return connection;
}
}
my Servlet
package com.marcheli.shoping;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import user.Client;
import user.ManagementUser;
import java.io.IOException;
public class main extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ManagementUser manage = new ManagementUser();
//the class ManagementUser use the getConnection() method and performe operation in DB
Client c = manage.signUp(new Client("h","12334","email#sj",
"072737","ksk","jd"));
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
In my web Browser, When I visit the URL for this Servlet I get this errors(it tells me the JDBC is not found):
java.lang.ExceptionInInitializerError
user.ManagementUser.signUp(ManagementUser.java:14)
com.marcheli.shoping.main.doGet(main.java:18)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:683)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:792)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
cause mère
java.lang.RuntimeException: java.lang.ClassNotFoundException:
com.mysql.jdbc.Driver dao.DbConnection.(DbConnection.java:16)
user.ManagementUser.signUp(ManagementUser.java:14)
com.marcheli.shoping.main.doGet(main.java:18)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:683)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:792)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
EDIT
I tried also to add the connector to my Artifact:

can't connect to mysql through eclipse - java.lang.ClassNotFoundException: com.mysql.jdbc.Driver [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 6 years ago.
i've tried connecting my java servlet project in eclipse with my mysql server, and it gives me this error - java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
now, i've downloaded the latest connector jdbc from the mysql website, and i've put it in my java class path, and turned on the option.
also, i did checked the Driver class really is exist in the jar i downloaded, and it was.
i checked in google for hours for this problem, and couldnt find the solution.
here's my code, hopfully you guys can help me
LoginServlet.java
package androidLogin;
import java.io.IOException;
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 com.mysql.jdbc.Connection;
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("GET METHOD");
Connection con = DBConnectionHandler.getConnection();
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
DBConnectionHandler.java
package androidLogin;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.mysql.jdbc.Connection;
public class DBConnectionHandler {
Connection con = null;
public static Connection getConnection() {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");//Mysql Connection
con =(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/loginuser", "host", "13241234");//mysql database
if(con!=null){
System.out.println("connected successfully");
}
} catch (SQLException | ClassNotFoundException ex) {
System.out.println(ex);
// Logger.getLogger(DBConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("not connected to database");
}
return con;
}
}
please help guys, i'm really desperate.
If you're running your Servlet in tomcat or any other container, make sure that mysql jar is in servlet container class path
Checkout these answers also:
ClassNotFoundException com.mysql.jdbc.Driver
classpath, eclipse and java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver during Dynamic Web Project creation in java

I am designing a registration page using MVC design pattern. I have made a class file which will input the parameters into the database using sql commands but i am getting
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Here is the code
package src.service;
import java.sql.*;
public class RegisterService {
public void addToDatabase(String name, String id, String email, String password){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Get a connection to the database
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/chillmaarodb", "root", "rsystems");
// Create a statement
Statement myStatement = myConn.createStatement();
String sql = "insert into userid values(" + id + ", '" + name + "', '" + email + "', '" + password + "')";
myStatement.executeUpdate(sql);
}
catch (Exception e){
e.printStackTrace();
}
}
}
I have imported the driver in my lib folder of the project, imported it in build path, imported it in tomcat server in the folder tomcatv7>lib by creating a lib folder. Still it is showing the same error. Kindly help.
You need to setup the DB Connection in server.xml
follow this tutorial :
http://examples.javacodegeeks.com/core-java/mysql-connector-for-java-how-to-install-in-eclipse-and-tomcat/
and
https://www.mulesoft.com/tcat/tomcat-mysql
as well as you need to download MySQL Connector from:
http://dev.mysql.com/downloads/connector/j/
and copy the jar file to "C:\tomcat7\lib"
You should add MYSQL JDBC LIBRARY to your project
and also import
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
This worked for me---
This solution is only for Dynamic web projects.
Steps--
1)Create a Dynamic Web project
2)I added the "mysql-connector-java-5.1.48-bin" jar in WebContent/WEB-INF/lib folder.
2) Create a tomcat server
3)inside src create a demo servlet--
package com.luv2code.testdb;
import java.io.IOException;
import java.io.PrintWriter;
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 java.sql.*;
/**
* Servlet implementation class TestDbServlet
*/
#WebServlet("/TestDbServlet")
public class TestDbServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// setup connection variables
String user = "springstudent";
String pass = "springstudent";
String jdbcUrl = "jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC";
String driver = "com.mysql.jdbc.Driver";
// get connection to database
try {
PrintWriter out = response.getWriter();
out.println("Connecting to database: " + jdbcUrl);
Class.forName(driver);
Connection myConn = DriverManager.getConnection(jdbcUrl, user, pass);
out.println("SUCCESS!!!");
myConn.close();
}
catch (Exception exc) {
exc.printStackTrace();
throw new ServletException(exc);
}
}
}
4)Just right click and run as run on server select ur tomact server
Remember before all these you need to create ur db schema,
here i have used mysql workbench.
Mysql part is not covered in this answer.
If this does not work, try adding the msql connector jar inside tomcat/lib folder

How to import JDBC driver into Dynamic Web Project?

I have a local MySQL database. When I created a simple Java project, with one class which contained only main, I successfully retrieved some data from the database using JDBC connector jar, imported with Build path -> Add external jars, and it worked perfectly.
Then I tried to use a similar approach, but now in a Dynamic Web Project, in which I am using Servlets, but I get java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/ePay.
I have been looking for several hours into the answers of similar questions, and here is where I have tried to put the JDBC MySQL connector so far:
Directly into Java Resources folder
Into lib folder which is within Java Resources
Into WebContent/WEB-INF/lib/
Do I need web.xml or context.xml? I read a tutorial in which they were used, tried to implement the explained example, but I still had the same problem.
I am working on Linux Mint 17, using Tomcat 7 into Eclipse IDE.
Here is the photo of my project structure:
Here are the relevant classes:
package dbObjects;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Entity {
protected Connection getConnection() throws SQLException {
String pass = "mypass";
String userDB = "root";
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost/ePay", userDB, pass);
return conn;
}
protected ResultSet getResultSet(String sql) throws SQLException {
Connection conn = getConnection();
Statement st = conn.createStatement();
return st.executeQuery(sql);
}
}
The user class:
package dbObjects;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
public class User extends Entity {
private long idUser;
private String userName;
private String pass;
private String fullName;
private String email;
private Date dateOfBirth;
private String address;
public User(long idUser, String userName, String pass, String fullName,
String email, Date dateOfBirth, String address) {
super();
this.idUser = idUser;
this.userName = userName;
this.pass = pass;
this.fullName = fullName;
this.email = email;
this.dateOfBirth = dateOfBirth;
this.address = address;
}
public User(long idUser) throws SQLException {
super();
this.idUser = idUser;
setUserById(idUser);
}
private void setUserById(long idUser) throws SQLException {
ResultSet resultSet = getResultSet("SELECT * FROM User WHERE idUser = " + idUser);
while(resultSet.next()) {
System.out.println(resultSet.getInt("idUser"));
userName = resultSet.getString("username");
pass = resultSet.getString("pass");
fullName = resultSet.getString("fullname");
email = resultSet.getString("email");
dateOfBirth = resultSet.getDate("dateOfBirth");
address = resultSet.getString("address");
}
}
#Override
public String toString() {
return userName;
}
}
And the servlet which I am trying to run:
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
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 dbObjects.User;
/**
* Servlet implementation class HomeServlet
*/
#WebServlet(description = "Home page shown to user", urlPatterns = { "/HomeServlet" })
public class HomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HomeServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
User user = null;
try {
user = new User(1);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PrintWriter pw = response.getWriter();
pw.println(user);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
There are two ways to use and reference a jar file in an eclipse project.
One is at compile time and for compilation purposes. To make your project compile, you need to add your required libraries in the classpath. In eclipse, right click to your project, hover on 'Build Path', then select 'Configure Build Path'. In the dialog go to 'Libraries' tab and there you can see which jars/libraries you have. If you need to add more, you can use the buttons at the right side of the dialog. There you should select 'Add external jars' and select the MySql JDBC Driver from your file system.
The other one is at run time. This is when you deploy your web application to an application server. Now everytime your application needs to load a class from an external jar, it will look for the jar in the application server's class loader. The classloader conatins the paths to the available jar files in your application server, in configured resources and in your deployed application in the WEB-INF/lib/ folder. You can configure which place the classloader will check first.
In your very specific case, you need to add the MySQL JDBC Driver in any of classloader paths (since I asume your project compiles already) so you can either add the jar to Tomcat's /lib directory or to your application's /WEB-INF/lib/ directory. After that just redeploy or restart tomcat and you should be able to use MySQL JDBC connections.
UPDATE:
Also, when using a DriverManager interface to create a JDBC Connection, remember to always create an instance of your JDBC driver first in order to load it into your Classloader. You can see this in the MySQL JDBC Driver documentation. Ej:
Class.forName("com.mysql.jdbc.Driver").newInstance();
Call this line before using DriverManager.getConnection(...) and you should now be able to create and use your JDBC Connections.
Your mysql jdbc driver should be placed into your tomcat's directory:
catalina_base/webapps/app_name/WEB-INF/lib/
Make sure to start/restart your server after placing your new mysql jdbc driver jar file there.
just place your driver jar file into WEB-INF/lib folder.

class not found exception com.mysql.jdbc.driver [duplicate]

This question already has answers here:
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
(13 answers)
Closed 7 years ago.
File structure of my project is:
-src
|
-pkg
|
-CoreServlet.java(servlet)
-Main.java
-Core.java(jdbc code is here)
core.java class:
package com.pkg;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class core{
private Connection connect = null;
private Statement statement =null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
String qwerty;
public void readDataBase() {
String userName = "ansh";
String password = "12345";
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/glbitm", userName,password);
statement = connect.createStatement();
resultSet = statement.executeQuery("select * from teachers");
resultSet.next();
qwerty = resultSet.getString(1);
} catch (Exception e) {
System.out.println(e);
}
}
}
coreServlet.java class :
package com.pkg;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class coreServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
core dao = new core();
dao.readDataBase();
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<head><title>Hello World</title></head>");
pw.println("<div>"+dao.qwerty+"</div>");
pw.println("<body>");
pw.println("<h1>Hello World</h1>");
pw.println("</body></html>");
}
}
When I am accessing dao.qwerty in my coreServlet.java in my tomcat server. I am getting class not found exception com.mysql.jdbc.driver and value of dao.qwerty is printed as null. Where I am doing wrong ?
You need to add the mysql connector in classpath.
http://mirrors.ibiblio.org/pub/mirrors/maven2/mysql/mysql-connector-java/5.1.4/mysql-connector-java-5.1.4.jar
This connector jar acts as a mediator between database and the application for the flow of data. You can extract the class files from jar and see the details.
The java.lang.ClassNotFoundException is thrown when your code attempts to execute the following line
Class.forName("com.mysql.jdbc.Driver").newInstance();
This is a checked exception which always needs to be either caught inside a try/catch or if try/catch is not implemented, then this exception needs to be declared in the method.
There have been multiple resolutions provided in this thread, but from my experience if you are able to connect to your database from eclipse using data source explorer, then most likely reason is "mysql-connector-java-5.1.28-bin.jar" is not copied into the your tomcat's lib directory.
The mysql connector for java can be downloaded from http://dev.mysql.com/downloads/connector/j/
You have not set the mysql-connector in your path.Set that first and everything else will be done
What is JConnector ?
Java does not know SQL so every statement you want to execute using the sql driver will get converted to sql constructs and the result that is returned my mysql is also converted into java understandable constructs.
hope it helps

Categories

Resources