1

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());
        }
    }
}
3
  • Etat HTTP 500 - type Rapport d''exception message description Le serveur a rencontré une erreur interne qui l''a empêché de satisfaire la requête. exception java.lang.NullPointerException com.cloud.db.DbConnection.authenticate(DbConnection.java:25) com.cloud.db.Auth.doPost(Auth.java:46) javax.servlet.http.HttpServlet.service(HttpServlet.java:644) javax.servlet.http.HttpServlet.service(HttpServlet.java:725) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) Sorry for the French im French native. Thats the error generated when i submit form Commented Sep 15, 2014 at 16:32
  • Which line in your code is DbConnection.java:25 and Auth.java:46? Commented Sep 15, 2014 at 16:34
  • DbConnection.java line 25 i have: PreparedStatement stm = conn.prepareStatement("select * from users where email=? and password = ?"); and auth.java line 46 i have : new DbConnection().authenticate("[email protected]", "google"); Commented Sep 15, 2014 at 16:37

4 Answers 4

1

You can do it in this way also

public class ConnectionProvider {
    public static Connection getConnection() throws SQLException {
      Connection connection = null;
      connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/cloudbase"
                                                                        ,user,passwd);
      return connection;
    }

   public void authenticate(Connection connection,String usrname,String pwd) 
       throws SQLException {
    String query = "select firstName from users where email=? and password = ?";
    try {
        PreparedStatement stm = connection.prepareStatement(query);
        stm.setString(1, usrname);
        stm.setString(2, pwd);
        ResultSet result = stm.executeQuery();
        if (resultSet.next()) {
            do {
               System.out.println("Welcome, "+resultSet.getString("firstName"));
            } while(resultSet.next());
        }
       else{
           System.out.println("Username or id doesnot exist");
     }
    } catch (SQLException e) {
        System.out.println("Error :" + e.getMessage());   
    }
    finally{
       connection.close();
}

}

Then in your Servlet

protected void doPost(...) throws ServletException, IOException {
    String email = request.getParameter("email");
    String passwd = request.getParameter("pwd");
    Connection connection = ConnectionProvider.getConnection();
    new ConnectionProvider().authenticate(connection,email ,passwd);    

}
Sign up to request clarification or add additional context in comments.

Comments

1

Based on what you posted I'd say the problem is here:

conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cloudbase",user,passwd);
stmt = conn.createStatement();

The DriverManager.getConnection is returning null and, null.create... is throwing the NPE.

How can you verify that: Put a sysout after conn = ... and see if the connection is null How to fix that: 1) make sure the driver class is in the classpath and it was loaded. 2) Before using an object, make sure it was initialized.

Comments

1

The biggest difference between running the code locally and in tomcat is the location of the JDBC driver, so the most likely problem is that Tomcat can't find the JDBC driver. Tomcat expects to find a driver in $CATALINA_HOME/lib. There are instructions for setting up a MySQL datasource here.

Currently your exception-handling obscures what is going on. The original problem happens in the DBConnection constructor, but since the exception gets caught, the authenticate method goes ahead and runs with a null connection, resulting in a NullPointerException.

Tomcat should be writing the exception generated in the DBConnection constructor to the console, so you can look there to find the original problem. To fix the exception-handling, you could change the DbConnection code to something like:

public boolean authenticate(String usrname,String pwd) throws SQLException {
    Connection conn = DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/cloudbase",user,passwd);
    try {
        PreparedStatement stm = conn.prepareStatement(
        "select * from users where email=? and password = ?");
        stm.setString(1, usrname);
        stm.setString(2, pwd);
        ResultSet result = stm.executeQuery();
        return result.next();
    } finally {
        try {
            conn.close();
        } catch (SQLException e) {
            // use a logger instead of stdout
            log.info("close caused exception", e); 
        }
    }
}

This makes sure that the exception thrown is the one that caused the original problem.

Comments

1

you have not loaded mysql driver,this is why drivermanager is returning null.In JDBC, we must have to register Driver(Mysql Driver in your case).

  Class.forName("com.mysql.jdbc.Driver");
  Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cloudbase", user, passwd);
  /* your remaining code ....
   ...*/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.