Я создаю приложение веб-чата с использованием JSP, сервлетов и HTML.Как заставить одного пользователя получать новые сообщения от другого без обновления / перезагрузки?
Я пробовал 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 не работает, правда, вероятно, потому что я не совсем понимаю правильный синтаксис.Я полностью застрял и нуждаюсь в этом для школьного задания !!!Большое спасибо за любую помощь!