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<>();

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

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

    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<AsyncContext> asyncContexts = new ArrayList<>(this.contexts);
        this.contexts.clear();      
        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()) {
                writer.println(htmlMessage);
                writer.flush();
                asyncContext.complete();
            } catch (Exception ex) {
            }
        }
        response.sendRedirect("index.jsp");
    }
}

and client side index.jsp

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


         <script>
         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 = "";
             xmlhttp.send("from="+fromText+"&to="+toText+"&message="+messageText);
         }
            var messagesWaiting = false;
            function getMessages(){
                if(!messagesWaiting){
                    messagesWaiting = true;
                    var xmlhttp = new XMLHttpRequest();
                    xmlhttp.onreadystatechange=function(){
                        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);
                    xmlhttp.send();
                }
            }
            setInterval(getMessages, 1000);
        </script>       
</body>
</html>
Member Avatar for LastMitch

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.