java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z - java

I am trying to connect my Servlet to mysql database using data Source . But whenever I run my servlet I end up getting this exception :
java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z
org.apache.tomcat.dbcp.dbcp2.DelegatingConnection.isValid(DelegatingConnection.java:913)
org.apache.tomcat.dbcp.dbcp2.PoolableConnection.validate(PoolableConnection.java:282)
org.apache.tomcat.dbcp.dbcp2.PoolableConnectionFactory.validateConnection(PoolableConnectionFactory.java:356)
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:2306)
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2289)
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2038)
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1532)
Servlet.AbdulTayyebs.processRequest(AbdulTayyebs.java:36)
Servlet.AbdulTayyebs.doGet(AbdulTayyebs.java:57)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Here is my Content.xml
<Resource name="jdbc/abdultayyebs" auth="Container"
type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:4000/abdultayyebs?zeroDateTimeBehavior=convertToNull"
username="root" password="february1996" maxActive="5" maxIdle="2"
maxWait="1000"/>
Here is my web.xml
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/abdultayyebs</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth></resource-ref>
And here is my servlet AbdulTayyebs
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletConfig;
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 AbdulTayyebs extends HttpServlet {
DataSource ds=null;
#Override
public void init(ServletConfig config)throws ServletException{
try {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
ds = (DataSource)envContext.lookup("jdbc/abdultayyebs");
} catch (Exception e) {
throw new ServletException("Something went wrong while Initializing the Servlet",e);
}
}
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException {
PrintWriter write = response.getWriter();
try {
Others.Action a = Others.ActionFactory.CreateAction(request);
try(Connection c=ds.getConnection()){
String page = a.Execute(c,request,request.getSession(false));
request.getRequestDispatcher(page).forward(request, response);
}
}
catch (SQLException e) {
write.println(e);
}
catch (ServletException e) {
write.println(e);
}
catch (Exception e) {
write.println(e);
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
I also added the mysql jdbc driver in the lib folder of tomcat but even this didnt helped ? It would be highly appreciable if anybody can help me out

java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z
This means that the MySQL JDBC driver is outdated as such that it doesn't support Java 1.6's Connection#isValid() method.
Upgrade it. And make sure that you've only one MySQL JDBC driver JAR file in the runtime classpath.
See also:
Connect Java to a MySQL database

For me, the solution was not to upgrade my driver (JT400). Even the latest version (9.1) appears to not have implemented isValid() (it's commented out in the code?).
What worked for me was to provide a validationQuery to my database connection pool. E.g.:
validationQuery=SELECT current date FROM sysibm.sysdummy1

net.sourceforge.jtds.jdbc.JtdsConnection doesn't implement isValid()
So you need to specify a connection-test-query to ensure that isValid() method isn't called
Adding the following line to application.propertiesfile resolved the error for me.
spring.datasource.hikari.connection-test-query=SELECT 1

in my case, I upgraded ojdbc from verion 14 to 6. I had artifact ojdbc14, then I changed it to ojdbc6. I lost quite sometime here, as I thought 14 is a later version as 14>6. but 14 is meant for java 1.4. 6 means java6

I was getting the same thing using jt400 for DB2 , this worked out for me
validationQuery="SELECT 1 FROM SYSIBM.SYSDUMMY1"

This is what I read about isValid method (source).
The driver (here MySQL) tries to check if your connection is valid or not.
Not sure how it works (as it doesn't allow to connect even when my MySQL instance/service is up and running).
So, use the below string in your spring application.properties file
spring.datasource.hikari.connection-test-query=select 1 from dual
(or any test query, - select sysdate from dual)

For me, I added the validationQuery parameter within the database connection pool config.
<Resource name="jdbc/abdultayyebs" auth="Container"
type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:4000/abdultayyebs?zeroDateTimeBehavior=convertToNull"
username="root" password="february1996" maxActive="5" maxIdle="2"
maxWait="1000" validationQuery="SELECT 1"/>

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:

Servlet Database URL

I'm trying to have a servlet to connect and interact with a database. I'm very new at this topic, so there probably are a couple of big issues, but the main problem I'm stuck at is how to get the database URL.
This is the servlet (I'm trying to keep it as light as possible)
import java.io.*;
import java.text.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class qaServlet extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String firstName = request.getParameter("question");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/qaDatabase", "root", "");
//^HOW DO I GET THE RIGHT URL?^
PreparedStatement ps = con.prepareStatement("insert into faq values('1','question','sì');");
int i = ps.executeUpdate();
}
catch (Exception e2) {
System.out.println(e2);
}
out.close();
}
}
First, it is better to use e2.printStackTrace(); instead of System.out.println(e2); when debugging.
Second, as the exception has shown, the actual problem was missing JAR file with JDBC driver, which has to be either in the WEB-INF/lib folder of your application, or in Tomcat's lib folder.
When developing, don't forget to republish your project after adding the driver's JAR file.

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.NoClassDefFoundError: Could not initialize class javax.mail.internet.InternetAddress

I am trying to send an email using the JavaMail API. Here is my code on the servlet:
package com.lsp.web;
import com.lsp.service.Mailer;
import javax.ejb.EJB;
import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
#WebServlet(name = "contact", urlPatterns = {"/contact"})
public class ContactServlet extends SpringInjectedServlet {
#EJB
private Mailer emailBean;
#Override
public void init() throws ServletException {
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String customerEmail = req.getParameter("email");
String subject = req.getParameter("subject");
String body = req.getParameter("message");
String error = null;
String succMess = null;
try {
javax.mail.internet.InternetAddress ia = new javax.mail.internet.InternetAddress(customerEmail);
ia.validate();
emailBean.send(customerEmail, subject, body);
req.setAttribute("succMessage", succMess);
req.getRequestDispatcher("sent.jsp").forward(req, resp);
} catch (javax.mail.internet.AddressException ae) {
error = "您指出的邮箱地址不存在";
req.setAttribute("errorMessage", error);
req.getRequestDispatcher("contact.jsp").forward(req, resp);
}
catch (MessagingException mex) {
error = "发送失败";
req.setAttribute("errorMessage", error);
req.getRequestDispatcher("contact.jsp").forward(req, resp);
}
}
}
At the line where I check for the user address where:
javax.mail.internet.InternetAddress ia = new javax.mail.internet.InternetAddress(customerEmail);
ia.validate();
I got an exception.
java.lang.NoClassDefFoundError: Could not initialize class javax.mail.internet.InternetAddress
In pom.xml, I added these lines:
<!--JavaMail API-->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.1</version>
</dependency>
<!--EJB-->
<dependency>
<groupId>javax.ejb</groupId>
<artifactId>ejb-api</artifactId>
<version>3.0</version>
</dependency>
I am using Tomcat.
Could someone tell me why this happens and how I can solve the issue.
Thank you.
Please see: https://stackoverflow.com/a/28935760/1128668 You have included the mail-api.jar in your project. That's the API specification only. The fix is to replace this:
<!-- DO NOT USE - it's just the API, not an implementation -->
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
with the reference implementation of that api:
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
I know it has sun in the package name, but that's the latest version.
You get a java.lang.NoClassDefFoundError, which means that the JVM can't initialise the class, not that it can't find the class which would be a ClassNotFoundException. A NoClassDefFoundError can be caused by a ClassNotFoundException but that need not be the case.
In order to find the cause, stop the server, delete the log and start again. Then reproduce the error and try to find the first Exception and its cause in your log file. If you are lucky this is the cause for the NoClassDefFoundError.
You also might indicate in your question which server you are using. It might make a difference how to solve the error.
Adding the dependency at build time does nothing to make the dependency available to Tomcat at runtime. You need to add the javax.mail.jar file to the WEB-INF/lib directory of your application, or to Tomcat's lib directory.
Of course, you wouldn't have this problem if you were using a full Java EE application server instead of Tomcat... :-)

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

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

Categories

Resources