I have a form which submits posts requests to a Servlet. I created a class DbConnection that manages authentication against a MySQL database which works perfectly well, when I test it with a static main method. When I used this class in my Servlet, it keeps giving me this error .
What is wrong with my code?
Here is the DbConnection class.
package com.cloud.db;
public class DbConnection {
private Connection conn;
private String user = NAME;
private String passwd = SOME_PASSWORD;
private Statement stmt;
private ResultSet result;
private PreparedStatement auth;
public DbConnection() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cloudbase", user, passwd);
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
}
public boolean authenticate(String usrname, String pwd) throws SQLException {
PreparedStatement stm = conn.prepareStatement("select * from users where email=? and password = ?");
stm.setString(1, usrname);
stm.setString(2, pwd);
ResultSet result = stm.executeQuery();
if (result.next()) {
return true;
} else {
return false;
}
}
}
Here is my servlet
package com.cloud.db;
import com.cloud.*;
import java.sql.*;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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("/auth")
public class Auth extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Auth() {
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
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String email = request.getParameter("email");
String passwd = request.getParameter("pwd");
DbConnection connect = new DbConnection();
try {
new DbConnection().authenticate("[email protected]", "password");
} catch (SQLException e) {
System.out.println("Error :" + e.getMessage());
}
}
}