0

mysql_pool.getConnection() を呼び出そうとすると、常に NullPointerException が発生します (たとえば、ログイン メソッドで)

サーブレットの 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

NullPointerExceptionフィールドがメソッド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 に答える