0

I am trying to develop a web application that connects to a database. I am trying to connect to the database but it keeps on giving me a null pointer exception. I have tried pretty much everything and I can not seem to find the error. If someone can help me then that would be great!

Note that I can connect to the database through mysql workbench with those details written below. JDBC connector is added to build path and so is the servlet.

HTML

<form action="./servlets/Login" method="GET">
                    <div>
                        <label for="name">Username:</label>
                        <input type="text" name="name"/><br/>
                        <label for="pass">Password:</label>
                        <input type ="password" name="pass"/><br/><br/>
                        <label for="submit"></label>
                        <input type="submit" class="btn btn-primary btn-xl page-scroll" name="submit" value="Login">
                    </div>
                    </form>

Java that connects to the MySQL server

public class VerifyUser {

private static Connection connect = null;
  private static String host="127.0.0.1:3307";
  private static String database="activities";
  private static String username="root";
  private static String password="Hitesh123";
  //connecting to the database
  public static Connection getConnection(){
        if(connect ==null){
            try{
             Class.forName("com.mysql.jdbc.Driver");
              String conn_string="jdbc:mysql://"+host+"/"+database;
              Connection connect = DriverManager.getConnection(conn_string,username,password);
              return connect;
            }catch(Exception ex){
                 System.out.println("Cannot connect to databse"); 
                return null;    
                //ex.printStackTrace();
            }
        }else{
            return connect;
        }
    }
  public Admin checkAdmin(String user,String password){
      String sql="SELECT * from Admin WHERE Username=? AND PasswordHash=?";  
      Admin a=null;
        try( Connection connect = getConnection(); 
             PreparedStatement pstmt = connect.prepareStatement(sql);
            ){  
             pstmt.setString(1,user);
             pstmt.setString(2,MD5HashGenerator.getMD5Hash(password));
             try (ResultSet rs = pstmt.executeQuery();){
               while(rs.next()){
                  //int id=rs.getInt("AdminID");
                   int id=1;
                  String uname=rs.getString("Username");        
                  String pass=rs.getString("PasswordHash");     
                  a=new Admin(id,uname,pass);
                  break;

              }
             }
        }catch(SQLException ex){
            System.out.println("does not work");
            ex.printStackTrace();   
        }
        return a;

  }  

Error message

Cannot connect to databseMar 19, 2018 7:43:29 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Login] in context with path [/activities_connect] threw exception
java.lang.NullPointerException
    at main.bean.VerifyUser.checkAdmin(VerifyUser.java:80)
    at main.Login.doGet(Login.java:36)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

EDIT : Checked build path again and no change... added jars to Deployment Assembly and still no change..

8
  • Identify line# 80 in your VerifyUser.java file. Commented Mar 19, 2018 at 20:00
  • line 80 is PreparedStatement pstmt = connect.prepareStatement(sql); in the checkAdmin class Commented Mar 19, 2018 at 20:08
  • When your code reaches this part connect is null. Run it under debugger and you should see it. Commented Mar 19, 2018 at 21:24
  • you have return null; in your code. What do you expect it to do? Commented Mar 19, 2018 at 21:27
  • that is return null if it does not connect.... Commented Mar 19, 2018 at 21:37

2 Answers 2

0

The way, you try to obtain the connection shows typical rookie mistake, especially in Java, where we have checked exceptions. It is common for core or library exceptions to reveal the reason why it was thrown. Instead of printing some generic and unclear message and returning null (which i guess caused NullPointerException), log the actual exception message and focus on what could possibly go wrong.

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

5 Comments

I have logged it and have included it in my question. I cant figure it out by trying multiple things hence why I have come to this forum. No need to point out that its a rookie mistake...
@HiteshMankani you've included the NPE log in the question, but we already know that's caused by you returning null from getConnection(). Put that ex.printStackTrace() back into the getConnection() if you want help.
@Kayaman, the error i get is "java.lang.ClassNotFoundException: com.mysql.jdbc.Driver " but the jar file is in the build path...
@HiteshMankani but it's not in the classpath. You need the driver during runtime, it's not enough that you've got it during build time (in fact you don't need it during build time at all).
I did not want to belittle your programming skill to making clear point. Rather I meant that quickly written code for fastest result tends to skip really important things, that may be considered as interrupting (like explicite need of handling exception). Still, if the the exception would be at least logged, ClassNotFoundException would reveal actual problem much, much faster. @Kayaman answer is the right explanation.
0

That is mean, that your Connection connect = getConnection() returned null. Check that your database properties are correct.

4 Comments

I have checked that they are correct, as I wrote above, I have connected to the database with those properties through mysql workbench
So make sure that you have connector for MySQL. You can find which one is better fits you on maven repository: link
I have a connector and its added to the build path
I can't specify why it is null but your getConnection() method returns null. You can debug it to find the cause.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.