【问题标题】:How should I get all the messages from my database and return it我应该如何从我的数据库中获取所有消息并返回它
【发布时间】:2021-08-19 00:52:15
【问题描述】:

我正在使用 Java 制作一个聊天应用程序,并将所有消息发送到特定的聊天室。问题是我不知道如何将它们全部放在一个数组或其他东西中,以便可以一次将其全部返回给用户。我试过只做一个while循环来保持返回一个数组,但它只返回一次。我想尝试将所有值附加到一个数组中,但我不确定该怎么做。我见过的所有示例,只是将现有数据(如现有数组)添加到另一个现有数组中。请帮忙,我不知道该怎么办。

这是我的代码

@RequestMapping(value={"/get/messages", "xyz"}, method={RequestMethod.POST,RequestMethod.PUT, RequestMethod.GET})
public String[] getMessages(@RequestBody GETMessages getMessages) throws JSONException, IOException {
    String chatroomID = getMessages.getChatroomID();
    String sessionID = getMessages.getSessionID();

    String username = getUserFromSessionID(sessionID);

    int userStatus = getUserStatusFromSessionID(sessionID);
    int userChatStatus = getUserChatStatusFromUsername(username, chatroomID);

    if(userStatus == 0 || userStatus == 2){
        if(userChatStatus == 0){
            Connection connection = null;
            Statement st = null;
            ResultSet rs = null;


            String message = "";
            String user = "";
            String timeday = "";
            try{
                Class.forName("com.mysql.cj.jdbc.Driver");
                connection = DriverManager.getConnection("jdbc:mysql://HOST/DBNAME", "USERNAME", "PASSWORD");
                st = connection.createStatement();
                rs = st.executeQuery("SELECT * FROM messages WHERE chatroom = '" + chatroomID +"'");

                while(rs.next()){
                    message = rs.getString(2);
                    user = rs.getString(3);
                    timeday = rs.getString(5);
                    String combined = message + "~" + "user" + "~" + timeday;
                    String[] returnMessage {combined}
                    System.out.println(combined);
                    return(returnMessage);
                }
                String[] returnedMessage = {""};
                return(returnedMessage);
            }
            catch(Exception ex){
                System.out.println("Expection : " + ex.toString());
                String[] returnMessage = {"Expection : " + ex.toString()};
                return(returnMessage);
            }
        }else if(userChatStatus == 1){
            String[] returnMessage = {"You are still pending to join this chatroom"};
            return(returnMessage);
        }else if(userChatStatus == 3){
            systemReport(username, "Tried to access chatroom: " + chatroomID + " while being banned from the chat");
            String[] returnMessage = {"You are banned from this chat"};
            return(returnMessage);
        }else{
            String[] returnMessage = {"We are having issues verifying you are allowed to access this chat"};
            return(returnMessage);
        }

    }else if(userStatus == 1){
        systemReport(username, "Tried to acces chatroom: " + chatroomID + " while banned");
        String[] returnMessage = {"You are not allowed to acces  the server"};
        return(returnMessage);
    }else{
        String[] returnMessage = {"We are having issues making sure your allowed to login"};
        return(returnMessage);
    }
}

【问题讨论】:

  • 如果我知道了,您可以使用 ArrayList docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/… 并且每次迭代都使用 add 将此字符串添加到该数组列表,然后您使用该数组列表以更好的方式取回所有消息使用preparedstatment docs.oracle.com/en/java/javase/11/docs/api/java.sql/java/sql/… 作为易受sql 注入攻击的语句,这从安全角度来看并不好
  • @justsomeone 那是我的 API 用户不会真正访问 SQL 语句只是将数据发送到一个 url
  • 如果 chatroomID = "\';Drop DATABASE;";如果您的连接有特权,它当然会删除所有数据库
  • 它是一个 API,他们无法执行任何命令阅读我的文档以了解我的意思,它不是 Long docs.anonyomail.com/docs/api
  • @justsomeone 我刚刚明白你的意思让我测试一下

标签: java mysql jdbc


【解决方案1】:

在循环结果集时填充List

…
List< String > messages = new ArrayList<>() ;
while( rs.next() ){
    message = rs.get… ;
    messages.add( message ) ;
}
return List.copyOf( messages ) ;

从循环中删除 return 语句。调用return 结束循环。

如果你必须返回一个数组而不是一个列表:

return messages.toArray( new String[0] ) ;

【讨论】:

  • 这无关,但你对我的聊天应用程序应该使用什么 GUI 库有什么建议吗(不是 javaFX,我讨厌它)
  • @FaDeRockYT 是的,这是一个切线,在 Stack Overflow 上寻求图书馆推荐也是题外话。将此类问题提交给姊妹站点 Software Recommendations Stack Exchange。对于 Java 桌面应用程序,您可以选择 Swing、SWT 和 JavaFX。对于 Java 中的 Web 应用程序,可以使用 Vaadin Flow 或许多模板引擎中的任何一种。对于移动应用,我什至都没有跟上。
  • 谢谢先生,我刚刚试了一下,效果很好,非常感谢您的帮助!
猜你喜欢
  • 2019-08-20
  • 2019-10-16
  • 2015-08-27
  • 1970-01-01
  • 2021-11-07
  • 2013-03-06
  • 1970-01-01
  • 1970-01-01
  • 2020-11-07
相关资源
最近更新 更多