java-tomcat数据库连接池未在websocket服务器终结点中提供连接

pftdvrlh  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(244)

我使用tomcat8作为服务器,使用javaweb应用程序,这是一个tic-tac-toe在线游戏。
我有一个服务器端点配置使用 javax.websocket.Server.ServerEndpoint 但是当我尝试导入其中的资源时 NullPointerException 当我试图建立联系的时候。当我从servlets获得连接时,它可以正常工作,但只有在server endpoint中才会为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();
}

}

下面是my 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();
               }

它工作,但我想知道为什么它不能给我通过连接池的连接。有人知道吗?

ct3nt3jp

ct3nt3jp1#

在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>

相关问题