gpt4 book ai didi

java - Tomcat7/JBoss 2 NullPointerException 与 MySQL- 数据库

转载 作者:行者123 更新时间:2023-11-28 23:56:06 26 4
gpt4 key购买 nike

尝试调用 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";
}}

如果你们能帮帮我就好了

最佳答案

你得到一个 NullPointerException 因为字段 mysql_poolinitPool() 中同名的局部变量隐藏了方法

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

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

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

 mysql_pool = new DataSource(); // the instance field is being initialized
...

关于java - Tomcat7/JBoss 2 NullPointerException 与 MySQL- 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16704642/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com