This question already has answers here:
ClassNotFoundException: com.mysql.jdbc.Driver. JDBC MySQL driver for web application [duplicate]
(3 answers)
Closed 4 years ago.
I have created a login and registration page but when CREATE ACCOUNT button is clicked the data is not getting stored into the data base. It gives a exception saying
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver"
I have added the mysql jar file in my project.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/loginandregister")
public class loginandregister extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String options=request.getParameter("button");
System.out.println(options);
PrintWriter pw=response.getWriter();
if(options.equals("LOGIN")) {
String username=request.getParameter("loginid");
String password=request.getParameter("loginpassword");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/loginclass","root","root");
PreparedStatement login=conn.prepareStatement("select * from user_info where username=? and userpassword=?");
login.setString(1, username);
login.setString(2, password);
ResultSet rs=login.executeQuery();
if(rs.next()) {
pw.println("Welcome");
pw.println("Welcome"+username);
}else {
pw.println("Error");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
if(options.equals("CREATE ACCOUNT")) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/loginclass","root","root");
PreparedStatement register=conn.prepareStatement("insert into user_info values (?,?,?,?,?,?)");
String firstname=request.getParameter("fname");
String lastname=request.getParameter("lname");
String email=request.getParameter("email");
String phone=request.getParameter("phone");
String uname=request.getParameter("uname");
String pass=request.getParameter("password");
register.setString(1, firstname);
register.setString(2, lastname);
register.setString(3, email);
register.setString(4, phone);
register.setString(5, uname);
register.setString(6, pass);
register.executeUpdate();
}// try
catch (Exception e) {
e.printStackTrace();
}//catch
}// if create acc.
}// dopost
}//class
I think you need to add the jar in your tomcat directory's lib folder. Add the jar there and do a restart of the server.
This might do it for you.
Related
My code to test db connection from eclipse is given below
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.*;
#WebServlet("/TestDbServlet")
public class TestDbServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user="user01";
String pass="pass01";
String jdbcUrl = "jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC";
String driver = "com.mysql.cj.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);
}
}
am getting 404 error when i run this on server .I have added mysql-connector-java8.0.11.jar to lib folder of webinf.am using tomcat9 with java14 .
Normally, if you are getting a 404 error it means that the page is not found (Probably if your url isn't correct), if there is an error in the doGet Method "The connection to the database part" the server will respond with a 500 error.
https://www.codejava.net/java-ee/servlet/solved-tomcat-error-http-status-404-not-found
Let me know if that helped.
I am trying to connect servlet to mysql database in netbeans 8 and jdk 8 and glassfish server. i have also included mysqlconnector jar file in libraries but am getting
class not found exception at Class.forName("com.mysql.jdbc.Driver")
piece of my code
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
public class sqltest1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String user = request.getParameter("user");
String pass = request.getParameter("pass");
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo", "root", "root");
PreparedStatement pst = conn.prepareStatement("Select user,pass from login where user=? and pass=?");
pst.setString(1, user);
pst.setString(2, pass);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
out.println("Correct login credentials");
}
else {
out.println("Incorrect login credentials");
}
}
}
Try reAdding jar file into java build path and clean than recompile.
Your code looks fine.
Check mysql driver jar on your classpath and also verify proper mysql driver jar.
I am trying to add the form data to the database in java -- using jQuery model form dialog to create a form -- but I cannot see any data in my database.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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 newUserServlet
*/
#WebServlet("/newUserServ")
public class newUserServlet extends HttpServlet {
Connection connection;
#Override
public void init() throws ServletException {
try{
Class.forName("org.gjt.mm.mysql.Driver");
//my database connection url
connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","kavuri654");
}catch(Exception e){
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username =request.getParameter("name");
String email =request.getParameter("email");
String password =request.getParameter("password");
PrintWriter out =response.getWriter();
out.println("<h3>added<h3>");
try{
String selectQuery="insert into test.newuser(name,email,password)"+"values(?,?,?)";
PreparedStatement preparedstatement=connection.prepareStatement(selectQuery);
preparedstatement.setString(1, username);
preparedstatement.setString(2, email);
preparedstatement.setString(3, password);
int i =preparedstatement.executeUpdate();
if(i>0){
System.out.println("one row is added");
}
connection.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
I created a servlet to handle the request sent from the web client. In this servlet, I added the database connection details and I am reading the form data using request object and by using setter methods values are being stored into the database. I am able to add the details to the form but the form data is not stored in database. What should I do to store my form data into the database.
There would be some reasons.
Firstly check if your data "arrive" to this Servlet.
If 1 is ok then you should commit your statement : connection.commit()
Your servlet is ok. First I've created a mysql database test and added the table newuser:
create table newuser (
name varchar(255),
email varchar(255),
password varchar(255)
)
Then I've created a maven jetty project with your code in it. Then I opened following url in the browser:
http://localhost:8899/newUserServ?name=testname&email=testemail&password=testpwd
And voila - the record appeared in the table.
I am trying to create a simple servlet (tomcat) that accesses a database, then a USDA web service. I've successfully deployed/tested the database connectivity. When I added the web service access, eclipse reports the problem: AwdbWebService_Service cannot be resolved to a type.
The hour is late... I just don't see why this won't resolve as a service instance.
The error is tripped by this line:
AwdbWebService_Service lookup = new AwdbWebService_Service(wsURL,new QName("http://www.wcc.nrcs.usda.gov/ns/awdbWebService","AwdbWebService"));
Here is the code:
package localdomain.localhost;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URL; //added for usda webservice
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Logger;
import javax.annotation.Resource;
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;
import javax.xml.namespace.QName; // added for usda webservice
import usda.nrcs.wcc.awdbWebService.*;
#WebServlet(value = "/MyServlet")
public class MyServlet extends HttpServlet {
// use this for usda reservoir station values later
static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
protected final Logger logger = Logger.getLogger(getClass().getName());
#Resource(name = "jdbc/mydb", lookup = "jdbc/mydb")
private DataSource dataSource;
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
logger.info("Init");
System.out.println(getClass().getName() + ".init");
}
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
PrintWriter writer = resp.getWriter();
writer.println("<html>");
writer.println("<head><title>MyServlet</title></head>");
writer.println("<body><h1>MyServlet</h1>");
writer.println("<h2>DataSource</h2>");
Connection conn = null;
try {
writer.println("Datasource: " + dataSource + "<br/><br/>");
conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery("select 1");
while (rst.next()) {
writer.println("Resultset result: " + rst.getString(1) + "<br/><br/>");
}
rst.close();
stmt.close();
conn.close();
writer.println("SUCCESS to access the datasource");
// Now try accessing usda
URL wsURL = new URL("http://www.wcc.nrcs.usda.gov/awdbWebService/services?wsdl");
AwdbWebService_Service lookup = new AwdbWebService_Service(wsURL,new QName("http://www.wcc.nrcs.usda.gov/ns/awdbWebService","AwdbWebService"));
m_webService = lookup.getAwdbWebServiceImplPort();
} catch (Exception e) {
e.printStackTrace(writer);
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
writer.println("</body></html>");
}
}
For those following this thread:
The package statement at the start of the java classes I generated with wsimport begins with:
package gov.usda.nrcs.wcc.awdbWebService
My import statement however looked like this:
import usda.nrcs.wcc.awdbWebService.*;
In essence I placed the source # the wrong level and defined the build config to point incorrectly for the package references in the java classes. I removed the build reference, moved the tree to begin pointing on the gov level. Now that there wasn't a mismatch, the unresolved type error vanished.
I'm trying to respond to a get request in java using a database. But it throws some error which I don't know a clue how to fix it.
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
try{
//Accessing driver from the JAR file
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
//Connect to Clockie's database
Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/database", "root", "root");
//Here we create our query
String sql = "" +
"SELECT * " +
"FROM profiles " +
"WHERE profileId = '27'";
PreparedStatement statement = con.prepareStatement(sql);
ResultSet result = statement.executeQuery();
String xmls = "";
result.next();
xmls = result.getString("firstName") + " "+result.getString("lastName");
System.out.println(xmls);
resp.getWriter().println(xmls);
}
catch(Exception e){
System.err.println(e.getMessage());
}
}
}
Everything is fine though, if I set the doGet code block inside the a main method? I'm new to Java pls help!
EDIT:
the exception is "com.mysql.jdbc.Driver";
Print out the full stack trace using e.printStackTrace(); in your catch block.
You may not have the mysql-connector jar which contains com.mysql.jdbc.Driver on your classpath. Check your classpath by printing it out using:
System.out.println("classpath = " + System.getProperty("java.class.path"));