Search code examples
javamysqljspnullpointerexceptiontomcat7

an error:NullPointerException for java project, how to fix it?


While I run a simple java project for query user and password, I get throw this error message:

type Exception report

message: java.lang.NullPointerException

description The server encountered an internal error that prevented it from fulfilling this request.
java.lang.NullPointerException
DB.DataBaseConnection.close(DataBaseConnection.java:34)
DB.UserDAOImpl.queryAll(UserDAOImpl.java:84)
org.apache.jsp.QueryAll_jsp._jspService(QueryAll_jsp.java:100)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)

Here is QueryAll.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="DB.*" %>
<%@ page import="java.util.*" %>    
    <title>QueryAll</title>
  <% request.setCharacterEncoding("utf-8"); %>
  <body>

   <% 
   UserDAO userDAo=DAOFcatory.getUserDAOInstance();
   //set new user
  List<User>  all=userDAo.queryAll();
   Iterator<User> iter=all.iterator();
    %>
    <table border="1" bgcolor="#c0c0c0" align="center">
     <tr>
      <td>Id</td>
      <td>Username</td>
      <td>Password</td>
   </tr>
    <% 
   while(iter.hasNext()){
   User user1=iter.next();
   %>
  <tr>
  <td><%=user1.getUserid() %></td>
    <td><%=user1.getUsername()%></td>
      <td><%=user1.getPassword() %></td>
  </tr>
  <% 
  }
    %>
     </table>

Here is DataBaseConnection.java:

package DB;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DataBaseConnection {
    private final String driver = "com.mysql.jdbc.Driver";
    private final String url = "jdbc:mysql:localhost:3306/javaweb";
    private final String user = "root";
    private final String pwd = "root";
    private Connection conn;

    public DataBaseConnection() {
        try {
            Class.forName(driver);
            this.conn = DriverManager.getConnection(url,user,pwd);
        } 
        catch (ClassNotFoundException e){
            e.printStackTrace();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public Connection getConnection() {
        return this.conn;
    }

    public void close(){
        try {
            this.conn.close();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

User.java:

package DB;

public class User {

    private int userid;
    private String username;
    private String password;
    public int getUserid() {
        return userid;
    }
    public void setUserid(int userid) {
        this.userid = userid;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

}

Here is UserDAO.java:

package DB;

import java.util.*;

public interface UserDAO {  
    //query by all
    public List<User> queryAll() throws Exception;

Here is UserDAOImpl.java:

package DB;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import DB.User;
import DB.DataBaseConnection;

public  class UserDAOImpl implements UserDAO{
    public List<User> queryAll() throws Exception {
        List<User> all = new ArrayList<User>();
        String sql = "select * from user";
        PreparedStatement pstmt = null;
        DataBaseConnection dbc = null;

        try {
            dbc = new DataBaseConnection();
            pstmt = dbc.getConnection().prepareStatement(sql);

            //query database
            ResultSet rs = pstmt.executeQuery();
            while(rs.next()) {
                User user = new User();
                user.setUserid(rs.getInt(1));
                user.setUsername(rs.getString(2));
                user.setPassword(rs.getString(3));
                //add data to List
                all.add(user);
            }
            rs.close();
            pstmt.close();
        }
        catch(Exception e) {
            e.printStackTrace();
            throw new Exception("Erro:operation abnormal");

        }
        finally {
    dbc.close();
        }
    return all;
    }

Here is DAOFactory.java:

package DB;

import DB.*;
public class DAOFcatory {

    public static UserDAO getUserDAOInstance() {
        return new UserDAOImpl();
    }
}

However, when I Comment the code from UserDAOImpl.java:

throw new Exception("Erro:operation abnormal");and dbc.close();

I get the Top navigation bar, but not information.It's so odd.I guess it not connection the database, maybe also that occur when I try to use a reference that points to no location in memory (null) as though it were referencing an object. but I can't found null. Userid is uncertainty , maybe this a clue.


Solution

  • I believe there is a problem with your connection.

    public DataBaseConnection() {
        try {
            Class.forName(driver);
            this.conn = DriverManager.getConnection(url,user,pwd);
        } 
        catch (ClassNotFoundException e){
            e.printStackTrace();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }
    

    If getConnection throws an SQLException - which it presumably is doing - when you catch it you leave private Connection conn; uninitialised. When you come to close it at this.conn.close(); you are calling .close() on a null reference.

    If you're able to view the stack trace which is being printed (in an error log etc.) at this stage, you should see why the connection is failing.

    The following example demonstrates the same behaviour:

    public class Blah
    {
        public String hello;
    
        public Blah()
        {
            try
            {
                fail();
                hello = "hi";
            } 
            catch (IOException e)
            {
                System.err.println("Exception caught!");
            }
        }
    
        private void fail() throws IOException
        {
            throw new IOException();
        }
    
        public static void main(String[] args)
        {
            Blah blah = new Blah();
            System.out.println(blah.hello);
        }
    }
    

    Because an exception is thrown before hello is initialised (hello = "hi";), the code prints 'null' at the end.