用户应该看到其他用户的聊天消息,而不必刷新屏幕

时间:2018-12-28 02:17:55

标签: java ajax

我正在使用JSP,Servlet和HTML创建一个Web聊天应用程序。如何让一个用户从其他用户那里获取新消息而无需刷新/重新加载?

我尝试了一些AJAX,但是它无法正常工作。

<body>
   <h2>Chat Messages</h2>
    <div class="myBox">
 <table>
  <tr>
<th>user</th>
<th>message</th>
<th>time</th>
  </tr>
    <%  //set the messages into an arraylist
ArrayList <Message> msgs = new ArrayList<Message>();
msgs = (ArrayList) request.getAttribute("messages");
String str = "my name";
System.out.println("str is of type " + str.getClass().getName());

System.out.println("Message is of type " + 
      msgs.get(0).getClass().getName());
for(Message mess : msgs)
{
    %>
    <tr class = "container">
    <td><%=mess.getFname() %></td>
    <td><%=mess.getMessage() %></td>
    <td class="time-right"><%=mess.getTime() %></td>
    </tr>
    <%
}
%> 
  </table>
   </div>


/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //get the session
    HttpSession session = request.getSession();
    String chatId;
    //if they do not have a the session for the chat, then set it
    System.out.println(request.getMethod());
    if(request.getMethod() == "GET"){
        System.out.println("Thats a get");
    }
    else{
        System.out.println("Thats not a get");
    }

    //if they accessed this with a get, meaning they chose it from their chats
    //session.getAttribute("roomID")  == null
    if(request.getMethod() == "GET"){
        chatId =  request.getParameter("room");
        session.setAttribute("roomID",chatId);
        System.out.println("the room is " + chatId);
    }
    //otherwise its just a refresh because they posted a message
    else{
        System.out.println("the room was not null");
        chatId = (String) session.getAttribute("roomID");
        System.out.println("The room id is " + chatId);
    }
    System.out.println("The chat that you are in now is " + chatId);
    ArrayList<Message> msgs = DBmanage.getMessages(chatId);

    //set that array list into the request and forward to the JSP
    request.setAttribute("messages", msgs);
    request.getRequestDispatcher("/html/Chatroom.jsp").forward(request, response);

}

消息已发送,但是发送到数据库,但是其他任何用户都需要刷新才能看到任何新消息。 ajax无法正常工作,实际上可能是因为我没有完全理解正确的语法。 我完全被困住了,需要这个来做作业!!! 非常感谢您的帮助!

0 个答案:

没有答案