我在我的java网络应用程序中使用Tomcat 8作为服务器,它是一款非常棒的在线游戏。
我有一个使用javax.websocket.Server.ServerEndpoint
类配置的服务器端点,但当我尝试导入其中的资源时,当我尝试连接时,它会给我NullPointerException
。它从我的servlet获得连接时工作正常,但只在服务器端点给我null。有错误的行在下面注释:
此处还有包含所有文件的存储库(如果它有帮助:https://github.com/EduardValentin/TicTacToe-WebApp---Java-Servlets/tree/master/Web%20Client/src/java
@ApplicationScoped
@ServerEndpoint("/websocketendpoint")
public class MatchMaker {
private final SessionHandler sessionHandler = SessionHandler.getInstance();
@Resource(name = "jdbc/TicTacToeDb")
private DataSource dbResource;
@OnOpen
public void onOpen(Session session,EndpointConfig config) throws IOException{
System.out.println("Open Connection ...");
}
@OnClose
public void onClose(){
System.out.println("Close Connection ...");
}
@OnMessage
public void onMessage(String message,Session session) throws IOException, SQLException{
System.out.println("Message from the client: " + message);
String[] parts = message.split("\\|");
String typeOfOperation = parts[0];
String from = null;
System.out.println(typeOfOperation);
switch(typeOfOperation) {
case "JOIN":
String playerUsername = parts[1];
System.out.println(playerUsername + " yayaya");
PlayerModel newPlayer = new PlayerModel(playerUsername,session);
if(sessionHandler.playersInQueue() == false){
// Nu sunt jucatori care asteapta in coada ,deci nu are cu cine sa joace
sessionHandler.addInQueue(newPlayer);
} else {
PlayerModel opponent = sessionHandler.removeFromQueue(); // Ia cel mai vechi jucator ce asteapta la coada
opponent.setOpponent(playerUsername);
newPlayer.setOpponent(opponent.getUsername());
sessionHandler.addPlaying(newPlayer, opponent);
String first;
if(Math.random() >= 0.5) {
first = newPlayer.getUsername();
} else {
first = opponent.getUsername();
}
sessionHandler.sendMessageTo(playerUsername,"PLAYING|"+opponent.getUsername()+"|"+first);
sessionHandler.sendMessageTo(opponent.getUsername(),"PLAYING|"+newPlayer.getUsername()+"|"+first);
}
break;
case "MOVE" :
from = parts[1];
String to = parts[2];
String squareNr = parts[3];
System.out.println("From:" + from + " | To: " + to + " | Move: " + squareNr);
sessionHandler.sendMessageTo(to, "MOVE|"+squareNr);
break;
case "WON" :
from = parts[1];
to = parts[2];
System.out.println(from + " won the game.");
// we need to save the game to database
String insertQuery = "INSERT INTO games(won,lost,game_date) VALUES (?,?,TO_DATE(?,'day-mon-yyyy hh24:mi:ss'))";
try(Connection con = (Connection) dbResource.getConnection()){ // HERE I GET NULL POINTER EXCEPTION WHEN I TRY TO GET CONNECTION
PreparedStatement ps = con.prepareStatement(insertQuery);
ps.setString(1, from);
ps.setString(2, to);
DateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2016/11/16 12:08:43
ps.setString(3,dateFormat.format(date));
ps.executeUpdate();
ps.close();
}
sessionHandler.removeFromPlaying(to);
sessionHandler.removeFromPlaying(from);
break;
default :
System.out.println("Invalid message");
}
}
@OnError
public void onError(Throwable e){
e.printStackTrace();
}
}
这是我的context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/TicTacToeWeb">
<Resource name="jdbc/TicTacToeDb" auth="Container"
type="javax.sql.DataSource"
username="admin" password="superduperpwd"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/tictactoedb" maxActive="15" maxIdle="3" />
编辑:好像我没有使用连接池,我只是从驱动程序管理器连接,如:
try {
Class.forName("com.mysql.jdbc.Driver");
} catch(ClassNotFoundException e) {
System.out.println("Class not found "+ e);
}
System.out.println("JDBC Class found");
try( Connection con = (Connection) DriverManager.getConnection (
"jdbc:mysql://localhost/tictactoedb","admin", "superduperpwd")){
PreparedStatement ps = con.prepareStatement(insertQuery);
ps.setString(1, from);
ps.setString(2, to);
DateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2016/11/16 12:08:43
ps.setString(3,dateFormat.format(date));
ps.executeUpdate();
ps.close();
}
它有效,但我想知道为什么它不能通过连接池给我连接。有谁知道吗?
答案 0 :(得分:0)
在web.xml中放置资源引用是否有帮助?
<resource-ref>
<res-ref-name>jdbc/TicTacToeDb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>