Hi, Guys!
Actually I want to ask about servlet and ajax.
Sorry if I post in wrong room, I have search the room that suitable for my question, but the most suitable is here.
I'm developing a push notification for web using servlet + ajax.
I have done an tutorial from this pages. Yes, it is working.
But my problem is how to modify the program to push message privately (for specific user).
I have searched it, but some tutorial suggest to use websocket. So, by using websocket, I must start from the beginning.
Do you have any suggestion to modify this program, so the server can send data to spesific user?
Do I must modify only in client (ajax) file or both of server (servlet) and client?

Thank you in advance.

This is the code:

FileName: ShoutServlet.java

package del10.if10048;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.AsyncContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import javax.servlet.AsyncListener;
import sun.org.mozilla.javascript.internal.Context;

import del10.if10048.MyAsyncListener;
@WebServlet(urlPatterns = {"/shoutServlet"}, asyncSupported = true)
public class ShoutServlet extends HttpServlet{
    private List<AsyncContext> contexts = new LinkedList<>();

     protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
        final AsyncContext asyncContext = request.startAsync(request, response);

        asyncContext.setTimeout(10 * 60 * 1000);
     // attach listener to respond to lifecycle events of this AsyncContext
        asyncContext.addListener(new MyAsyncListener());

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<AsyncContext> asyncContexts = new ArrayList<>(this.contexts);
        String from = request.getParameter("from");
        String to = request.getParameter("to");
        String message = request.getParameter("message");

        String htmlMessage = "<p><b>" + from + "</b><br/>" +"<i>" + to + "</i><br/>"+ message + "</p>";
        ServletContext sc = request.getServletContext();
        if (sc.getAttribute("messages") == null) {
            sc.setAttribute("messages", htmlMessage);
        } else {
            String currentMessages = (String) sc.getAttribute("messages");
            sc.setAttribute("messages", htmlMessage + currentMessages);
        for (AsyncContext asyncContext : asyncContexts) {
            try (PrintWriter writer = asyncContext.getResponse().getWriter()) {
            } catch (Exception ex) {

and client side index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
        <!--  <form method="post" action="shoutServlet">-->
                    <td>Your name:</td>
                    <td><input type="text" id="from" name="from"/></td>
                    <td>To whom:</td>
                    <td><input type="text" id="to" name="to"/></td>
                    <td>Your shout:</td>
                    <td><input type="text" id="message" name="message" /></td>
                      <td><input type="button" onclick="postMessage();" value="SHOUT" /></td> 
                     <!--<td><input type="submit" value="SHOUT" /></td> -->
        <h2> Current Shouts </h2>
        <div id="content">
            <% if (application.getAttribute("messages") != null) {%>
            <%= application.getAttribute("messages")%>
            <% }%>

         function postMessage() {
             var xmlhttp = new XMLHttpRequest();
             xmlhttp.open("POST", "shoutServlet?u="+document.getElementById("to").value, true);
             xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
             var fromText = escape(document.getElementById("from").value);
             var toText= escape(document.getElementById("to").value);
             var messageText = escape(document.getElementById("message").value);
             document.getElementById("message").value = "";
            var messagesWaiting = false;
            function getMessages(){
                    messagesWaiting = true;
                    var xmlhttp = new XMLHttpRequest();
                        if (xmlhttp.readyState==4 && (xmlhttp.status==200||xmlhttp.status==500)) {
                            messagesWaiting = false;
                            var contentElement = document.getElementById("content");
                            contentElement.innerHTML = xmlhttp.responseText + contentElement.innerHTML;
                    xmlhttp.open("GET", "shoutServlet?t="+new Date(), true);
            setInterval(getMessages, 1000);

Edited by titusnainggolan: Forget the source code attachment

4 Years
Discussion Span
Last Post by titusnainggolan

I have searched it, but some tutorial suggest to use websocket. So, by using websocket, I must start from the beginning.

What do you mean by starting from the beginning when it's just a connection?


I mean, I must learn about websocket from the beginning maybe.
I think it is more difficult.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.