Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any Spring based web push like notification, where I can get notification updated in the web page without page refresh?

Is there any Spring based framework to send notifications to the web page. I have seen http://www.w3schools.com/html5/tryit.asp?filename=tryhtml5_sse I am also looking into something that can support most of the browsers. Is there any framework or add-on in Spring for this functionality for the server-side code? And any jquery framework to support this for the browser?

TIA.

like image 608
Daemonthread Avatar asked Aug 16 '12 17:08

Daemonthread


2 Answers

I have used the "long polling" method. You basically make an ajax request to the server for data on page load. The server waits until data is available before it responds. On the client and server, you can make the request timeout every 30 seconds or so to avoid having too many threads running on the server. The client just reissues the request after timeout.

This site provides a good introduction to long polling using jQuery.

Spring doesn't really have any explicit features that support this (e.g. pooling the polling threads) AFAIK, but you may look into the new async support in Spring MVC 3.2

like image 158
stephen.hanson Avatar answered Oct 17 '22 15:10

stephen.hanson


You can write your own servlet as below, for further information refer link. As this works with servlet this might work with spring mvc controllers also.

import java.io.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;




public class sse extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
    try
    {
        System.out.println("SSE Demo");
        response.setContentType("text/event-stream");

        PrintWriter pw = response.getWriter();
        int i=0;
        while(true)
        {

            i++;
            pw.write("event: server-time\n\n");  //take note of the 2 \n 's, also on the next line.
            pw.write("data: "+ i + "\n\n");
            System.out.println("Data Sent!!!"+i);
            if(i>10)
            break;
        }
        pw.close();

    }catch(Exception e){
        e.printStackTrace();
    }
}

public void doGet(HttpServletRequest request,HttpServletResponse response)  
{
    doPost(request,response);
}

}
like image 25
Jigar Parekh Avatar answered Oct 17 '22 15:10

Jigar Parekh