0

尝试调用 mysql_pool.getConnection() 时,我总是遇到 NullPointerException(例如在登录方法中)

我在我的 Servlet 的 init() 中调用方法 initPool

package john.z.server;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;

import java.util.LinkedList;
import java.util.regex.*;
import java.security.GeneralSecurityException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import john.z.schafkopf.Player;
import john.z.schafkopf.SGame;
import john.z.server.crypto.Base64;
import john.z.server.crypto.PasswordSalts;
import john.z.server.crypto.Passwords;

import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties;
import org.json.*;
public class SchafkopfServer extends WebSocketServlet implements
        WebsocketListener {
    public static DataSource mysql_pool;
    LinkedList<Player> lobby;
    LinkedList<SGame> gamelobby;
    public static final String GREETING = "Schafkopf 0.1";
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        initPool();


    }
    public SchafkopfServer(){
        initPool();
        lobby = new LinkedList<Player>();
        gamelobby = new LinkedList<SGame>();
    }
    @Override
    protected StreamInbound createWebSocketInbound(String subProtocol,
            HttpServletRequest request) {
        // TODO Auto-generated method stub
        return new WSocketconnection(this);
    }

    public void initPool (){
        if (mysql_pool == null) {
            PoolProperties p = new PoolProperties();
            p.setUrl("jdbc:mysql://"+ System.getenv("OPENSHIFT_MYSQL_DB_HOST")+ ":" +System.getenv("OPENSHIFT_MYSQL_DB_PORT")+"/development");
            p.setDriverClassName("com.mysql.jdbc.Driver");
            p.setUsername("myusername");
            p.setPassword("andmyownsecretpassword");
            p.setJmxEnabled(true);
            p.setTestWhileIdle(false);
            p.setTestOnBorrow(true);
            p.setValidationQuery("SELECT 1");
            p.setTestOnReturn(false);
            p.setValidationInterval(30000);
            p.setTimeBetweenEvictionRunsMillis(30000);
            p.setMaxActive(100);
            p.setInitialSize(10);
            p.setMaxWait(10000);
            p.setRemoveAbandonedTimeout(60);
            p.setMinEvictableIdleTimeMillis(30000);
            p.setMinIdle(10);
            p.setLogAbandoned(true);
            p.setRemoveAbandoned(true);
            p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
                    + "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
            DataSource mysql_pool = new DataSource();
            mysql_pool.setPoolProperties(p);

        }
    }
    @Override
    public void receiveText(String message, WSocketconnection connection) {
        // TODO Auto-generated method stub
        initPool();
        Pattern pat = Pattern.compile("login\\s(\\S+)\\s(\\S+)");
        Matcher mat = pat.matcher(message);
        boolean found = true;
        if (mat.find()) {
            login(mat.group(1), mat.group(2), connection);
            found = false;
        }
        pat = Pattern.compile("register\\s(\\S+)\\s(\\S+)");
         mat = pat.matcher(message);
        if (mat.find()) {
            register(mat.group(1), mat.group(2), connection);
            found = false;
        }
        if (found){
            connection.appendtomessage("Did Nothing");
        }
        connection.flushbuffer();

    }
    public void register (String uname, String pass,WSocketconnection connection){
        Connection con = null;
        PreparedStatement st = null;

        try {

            con = mysql_pool.getConnection();
            st = con.prepareStatement("INSERT INTO  schafkopf_users (uname , password, salt) VALUES (?,?,?)");

            byte[] salt = PasswordSalts.nextSalt();
            byte[] pw = null;
            try {
                pw = Passwords.hashPassword(pass.toCharArray(), salt);
            } catch (GeneralSecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                connection.appendtomessage("ERROR: Internal Error");
                return;
            }
            st.setString(1, uname);
            st.setString(2, Base64.encode(pw));
            st.setString(3,Base64.encode(salt));
            connection.appendtomessage("register OK for name "+ uname + "\n");
            st.executeUpdate();


        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            connection.appendtomessage("ERROR: Internal DatabaseError: "+e.toString());
        } finally {
            // TODO Auto-generated catch block
            if (con != null)
                try {
                    con.close();
                } catch (Exception ignore) {
                }
            if (st != null)
                try {
                    st.close();
                } catch (Exception ignore) {
                }

        }
    }
    public void sendgamelobby (WSocketconnection con){
        StringBuilder build = new StringBuilder("gamelobby: ");
        synchronized(gamelobby){
            build.append( new JSONArray(gamelobby).toString());
        }
        build.append("\n");
        con.writemessage(build.toString());
    }
    public void buffergamelobby (WSocketconnection con){
        StringBuilder build = new StringBuilder("gamelobby: ");
        synchronized(gamelobby){
            build.append( new JSONArray(gamelobby).toString());
        }
        build.append("\n");
        con.appendtomessage(build.toString());
    }
    public void login(String username, String pass, WSocketconnection connection) {
        Connection con = null;enter code here
        PreparedStatement st = null;
        ResultSet result = null;
        try {
            if (mysql_pool == null){
                connection.appendtomessage("Still empty");
                initPool();
            }
            con = mysql_pool.getConnection();
            st = con.prepareStatement("SELECT password , salt FROM schafkopf_users WHERE uname=(?)");
            st.setString(1, username);
            result = st.executeQuery();
            byte[] pw = null;
            byte[] salt = null;
            if (result.next()) {
                try {
                    pw = Base64.decode(result.getString("password"));
                    salt = Base64.decode(result.getString("salt"));
                } catch (Exception E) {
                    connection.appendtomessage("ERROR: InternalError");
                    E.printStackTrace();
                    return;
                }

            } else {
                connection.appendtomessage("ERROR: Usernotexistent");
                return;
            }
            boolean matches = false;
            try {
                matches = Passwords.matches(pass.toCharArray(), pw, salt);

            } catch (GeneralSecurityException e) {
                // TODO Auto-generated catch block
                connection.appendtomessage("ERROR: InternalError");
                e.printStackTrace();
                return;
            }
            if (matches) {
                connection.appendtomessage(username + " login OK");

                Player newplayer = new Player(username);
                connection.addlistener(newplayer);
                lobby.add(newplayer);
            }else{
                connection.appendtomessage(username + " wrong password");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            connection.appendtomessage("ERROR: Internal error: "+ e.toString());
            return;

        } finally {
            // TODO Auto-generated catch block
            if (con != null)
                try {
                    con.close();
                } catch (Exception ignore) {
                }
            if (st != null)
                try {
                    st.close();
                } catch (Exception ignore) {
                }
            if (result != null)
                try {
                    result.close();
                } catch (Exception ignore) {
                }
        }

    }

    @Override
    public String getmsgprefix() {
        // TODO Auto-generated method stub
        return "S";
    }}

如果你们能帮助我,那就太好了

4

2 回答 2

1

您得到 aNullPointerException因为该字段被方法mysql_pool中的同名局部变量隐藏initPool()

 DataSource mysql_pool = new DataSource();
 mysql_pool.setPoolProperties(p);

所以实例变量永远不会被初始化,因此是null. 当您尝试调用方法或访问 上的字段时null,您会得到NullPointerException.

要修复它,请将上面的内容更改为

 mysql_pool = new DataSource(); // the instance field is being initialized
 ...
于 2013-05-23T02:24:51.510 回答
-2

是你的 mysql_pool 局部变量吗

例如

public void initPool (){
    if (mysql_pool == null) {
        PoolProperties p = new PoolProperties();
        p.setUrl("jdbc:mysql://"+ System.getenv("OPENSHIFT_MYSQL_DB_HOST")+ ":" +System.getenv("OPENSHIFT_MYSQL_DB_PORT")+"/development");
        p.setDriverClassName("com.mysql.jdbc.Driver");
        p.setUsername("myusername");
        p.setPassword("andmyownsecretpassword");
        p.setJmxEnabled(true);
        p.setTestWhileIdle(false);
        p.setTestOnBorrow(true);
        p.setValidationQuery("SELECT 1");
        p.setTestOnReturn(false);
        p.setValidationInterval(30000);
        p.setTimeBetweenEvictionRunsMillis(30000);
        p.setMaxActive(100);
        p.setInitialSize(10);
        p.setMaxWait(10000);
        p.setRemoveAbandonedTimeout(60);
        p.setMinEvictableIdleTimeMillis(30000);
        p.setMinIdle(10);
        p.setLogAbandoned(true);
        p.setRemoveAbandoned(true);
        p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
                + "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
        mysql_pool = new DataSource();
        mysql_pool.setPoolProperties(p);

    }
于 2013-05-23T03:08:51.943 回答