【发布时间】: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 我刚刚明白你的意思让我测试一下