错误:java项目的NullPointerException,如何解决?

时间:2016-12-02 15:38:28

标签: java mysql jsp nullpointerexception tomcat7

当我为查询用户和密码运行一个简单的java项目时,我会抛出此错误消息:

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)

以下是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>

以下是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;
    }

}

以下是UserDAO.java

package DB;

import java.util.*;

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

以下是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;
    }

以下是DAOFactory.java

package DB;

import DB.*;
public class DAOFcatory {

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

但是,当我评论来自UserDAOImpl.java的代码时:

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

我得到了顶部导航栏,但没有信息。它太奇怪了。我猜它不是连接数据库,也许当我尝试使用指向内存中没有位置的引用时(null)就好了正在引用一个对象。但我找不到null。 Userid是不确定的,也许这是一个线索。

1 个答案:

答案 0 :(得分:0)

我相信您的连接存在问题。

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

如果getConnection抛出SQLException - 它可能正在做 - 当你抓住它时,你会private Connection conn;未初始化。当您在this.conn.close();关闭它时,您在空引用上调用.close()

如果您能够在此阶段查看正在打印的堆栈跟踪(在错误日志等中),您应该会看到连接失败的原因。

以下示例演示了相同的行为:

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);
    }
}

由于在hello初始化(hello = "hi";)之前抛出了异常,因此代码会打印出“null”&#39;最后。