`
zha_zi
  • 浏览: 592964 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

HTML5 Server-Sent Events With Java Servlets Example

 
阅读更多

Since the dawn of modern web applications, push notifications have gained significant traction in industry. Instead of pooling data from server it has now become common that server should notify client.

Ajax is so pervasive these days it is almost seen on every web page we visit. This is all good if you want to refresh a part of page every few seconds. But things get ugly if you want tens or hundreds of requests a second. Pooling webserver is too expensive in such cases. With that in mind HTML5 has introduced a nifty cool feature “Server-Sent Events”.

1. Introduction to Server-Sent Events

The Server-Sent Events are the new APIs for opening an HTTP connection for receiving push notifications from a server in the form of DOM events. Consider below javascript code:

//...
var eventSource = new EventSource("/some/data.html");
 
eventSource.onmessage = function(event) {
 
    alert(event.data);
 
};
//...

The above code can be executed in any modern browser (ofcourse the server-side script /some/data.html needs to be implemented first). We create an object of class EventSource. We pass a server URL which implements Server-sent events protocol. And finally we add a handler function on .onmessage. Every time server sends a message, the handler is called and the event object will have the data.

No need for pooling. The javascript handler will be asynchronously called.

The server needs to specific. First the response content type must be set to text/event-stream. And the data needs to be sent in following format.

...
data: This is some data
 
data: a quick brown fox
 
data: jumps over a lazy dog.
...

You got the idea. Lets quickly create a Java Servlet based application with Client code for Server-sent event.

2. Server-Sent Events, Hello World Servlet

For our hello world example, we create an html page that has a button to start server-sent event. The server will send us a timestamp every second which we just display on page.

index.jsp

<!DOCTYPE HTML>
<html>
<body>
    Time: <span id="foo"></span>
     
    <br><br>
    <button onclick="start()">Start</button>
 
    <script type="text/javascript">
    function start() {
 
        var eventSource = new EventSource("HelloServlet");
         
        eventSource.onmessage = function(event) {
         
            document.getElementById('foo').innerHTML = event.data;
         
        };
         
    }
    </script>
</body>
</html>

In above javascript code we created an event source for “/HelloServlet” path. On each message we just prints the data in span “foo”.

Now lets check Servlet code which sents the Server-Sent Events.

HelloServlet.java

package net.viralpatel.servlets;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class TestServlet extends HttpServlet {
     
 
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
     
        //content type must be set to text/event-stream
        response.setContentType("text/event-stream");  
 
        //encoding must be set to UTF-8
        response.setCharacterEncoding("UTF-8");
 
        PrintWriter writer = response.getWriter();
 
        for(int i=0; i<10; i++) {
 
            writer.write("data: "+ System.currentTimeMillis() +"\n\n");
 
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        writer.close();
    }
}

The servlet is quite simple. Content type must be set to “text/event-stream” and the character encoding must be UTF-8.

Also each message that we send must ends with \n\n.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>ServerSentEvent_HttpServlet_example</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <display-name>HelloServlet</display-name>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>net.viralpatel.servlets.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/HelloServlet</url-pattern>
    </servlet-mapping>
</web-app>

Output
html5-server-sent-events-java-servlet

Source code: https://gist.github.com/viralpatel/7007662

3. Multiple Events in Server-Sent Events

In above example we tracked a single event. The servlet sent only single data entity. In real world, you might want to send a number of events and want to track same on client side.

For example, consider below Javascript snippet.

var eventSource = new EventSource("HelloServlet");
 
 
eventSource.addEventListener('up_vote', function(event) {
     
        document.getElementById('up').innerHTML = event.data;
         
    }, false);
 
 
eventSource.addEventListener('down_vote', function(event) {
     
        document.getElementById('down').innerHTML = event.data;
         
    }, false);

In above code we used addEventListener() method of EventSource to add a handler function. We added handler to event “up_vote” and “down_vote”. Whenever any of this event changes, we need to update the count on html page.

The server must send the data in format:

...
event: up_vote
data: 10
 
event: down_vote
data: 5
 
event: up_vote
data: 12
 
event: down_vote
data: 9
 
...

The Java Servlet code for this example should be:
HelloServlet.java

package net.viralpatel.servlets;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class HelloServlet extends HttpServlet {
 
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
 
        PrintWriter writer = response.getWriter();
        int upVote = 0;
        int downVote = 0;
        for (int i = 0; i < 20; i++) {
 
            upVote = upVote + (int) (Math.random() * 10);
            downVote = downVote + (int) (Math.random() * 10);
 
            writer.write("event:up_vote\n");
            writer.write("data: " + upVote + "\n\n");
 
            writer.write("event:down_vote\n");
            writer.write("data: " + downVote + "\n\n");
 
            writer.flush();
             
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        writer.close();
    }
 
}

In above servlet code, we randomly incremented two ints upVote and downVote. Also we sent these ints to client with:

writer.write("event:up_vote\n");
writer.write("data: " + upVote + "\n\n");

Notice single \n in event and double \n\n in data.
You should get following output when the servlet is executed.
custom-event-server-sent-events-servlet

3.1. The EventSource API

In the examples above we used the onmessage event to get messages. But other events are also available:

Events Description
onopen When a connection to the server is opened
onmessage When a message is received
onerror When an error occurs

4. Browser compatibility

As of Oct 2013 – Internet explorer is your enemy :) Server-sent events are supported in all major browsers (Firefox, Opera, Chrome, Safari.) except for Internet Explorer.

分享到:
评论

相关推荐

    Java-for-the-Web-with-Servlets_JSP_and-EJB.pdf

    《Java for the Web with Servlets, JSP, and EJB》是一本全面介绍如何使用 Java 进行 Web 应用程序开发的专业书籍。本书不仅涵盖了 Servlet 2.3、JSP 1.2 和 EJB 2.0 等核心 Java 技术,还涉及了客户端编程语言 ...

    Ajax-Flight-Booking-System-JavaServlets_App.zip

    Ajax-Flight-Booking-System-JavaServlets_App.zip,基于Java Servlet、Java Server页面(JSP)的模型视图控制器(MVC)架构的土耳其航空公司(Web应用)的企业级航班预订系统。实现了对用户的认证和授权。该web应用...

    Murach-s-Java-Servlets-and-JSP, 3rd.pdf

    Murach's Java Servlets and JSP, 3rd Very good introduction on servlet and jsp.

    Java-Servlets-and-Java-Server-pages-JSP.rar_Java Servlet JSP

    Java Servlets 和 Java Server Pages(JSP)是Java Web开发中的核心技术,用于构建动态网站和Web应用程序。本书“Java Servlets and Java Server Pages JSP”深入探讨了这两个关键概念,旨在提供详尽的内容来帮助...

    Java_for_the_Web_with_Servlets

    ### Java for the Web with Servlets: A Comprehensive Overview #### Introduction "Java for the Web with Servlets, JSP, and EJB: A Developer’s Guide to J2EE Solutions" by Budi Kurniawan is a ...

    Murach's Java Servlets and JSP 2nd Edition 源代码

    《Murach's Java Servlets and JSP 2nd Edition》是一本深受欢迎的Java Web开发教程,涵盖了使用Servlets和JSP进行动态网页编程的核心知识。源代码是学习过程中的重要辅助材料,它能帮助读者深入理解书中的实例,...

    Sun - Core Servlets and JavaServer Pages.pdf

    《Sun - Core Servlets and JavaServer Pages》这本书是关于Servlets和JavaServer Pages(JSP)的国际畅销书。Servlets是Java编程语言中的一个核心部分,用于创建动态Web应用程序,而JavaServer Pages则是一种基于...

    servlets-examples.rar_servlets-examples

    "servlets-examples.rar_servlets-examples"压缩包包含了一系列Servlet的示例代码,这些例子对于学习和理解Servlet的工作原理以及如何在实际项目中应用Servlet至关重要。 Servlet的核心概念主要包括以下几点: 1. ...

    核心Servlet和JavaServer页面Core Servlets and JavaServer Pages

    介绍了servlet和JavaServer Pages(JSP)在创建电子商务站点,动态网站和启用Web的服务中的作用。

    Core Servlets and JavaServer Pages

    《Core Servlets and JavaServer Pages》是一本专为IT专业人士准备的经典教材,它深入浅出地介绍了Servlet和JavaServer Pages(JSP)技术,这两项技术是构建动态、交互式Web应用的基础。这本书的核心在于将理论知识...

    server-jre-8u131-linux-x64.tar.gz

    标题中的"server-jre-8u131-linux-x64.tar.gz"是一个适用于Linux操作系统的64位Java开发工具包(JDK)的压缩文件,版本为8更新131(8u131)。这个文件是Oracle公司提供的,用于在Linux服务器上部署Java应用程序和Web...

    Java for the Web with Servlets,JSP,and EJB,A Developer's Guide to J2EE Solutions

    Java for the Web with Servlets, JSP and EJB is the one book you need to master Java web programming. It covers all the technologies needed to program web applications in Java using Servlets 2.3, JSP ...

    killbill-java-plugin-two-servlets

    killbill-java-plugin-两个servlet 用两个... 然后,您可以在/var/tmp/bundles/plugins/java/two-servlets/1.0安装插件( target/killbill-java-plugin-two-servlets-*.jar )。 Servlet的端点: : : / servlets_one

    01-SQL-Server-2005.zip_java web管理

    【标题】"01-SQL-Server-2005.zip_java web管理" 涉及的关键技术点主要集中在Java Web开发和SQL Server 2005数据库的使用上,这二者是构建企业级事务管理系统的核心技术。下面将详细阐述这两个领域的知识。 **Java ...

    Beginning Java with WebSphere

    And, from the server-side, this book covers servlets, JavaServer Pages (JSPs), database accessibility (JDBC), custom tags, and concludes with JavaServer Faces (JSFs). This book concentrate on base ...

    中文-Head_First_servlets_JSP_2

    《Head First Servlets & JSP》是学习Java Web开发领域中的两门核心技术——Servlets和JSP的经典教材,尤其适合初学者。这本书以其独特的教学方式,通过丰富的图表、幽默的插图以及寓教于乐的方式,使枯燥的技术知识...

    cas-server-3.3-release.zip

    熟悉Java Servlets和HTTP协议也有助于理解CAS如何与Web应用交互。 在实际应用中,可能还需要考虑安全性问题,例如SSL/TLS加密、防止重放攻击、以及如何管理用户权限和审计日志。对于大型企业环境,可能还需要考虑...

    Java Servlets和java swing

    5. **JSP(Java Server Pages)集成**:Servlets通常与JSP结合,Servlet负责业务逻辑,JSP负责展示视图。 **Java Swing** Java Swing是Java Foundation Classes (JFC)的一部分,提供了丰富的GUI组件库,用于构建...

    E-Commerce-Java-Servlets:面向IT404高级Java编程课程的学分项目

    该项目名为“E-Commerce-Java-Servlets”,显然是一个针对IT404高级Java编程课程设计的学分项目,旨在让学习者深入理解和实践使用Java Servlets开发电子商务应用程序。Servlets是Java平台上的一个核心技术,用于扩展...

    cas-server-webapp-4.0.0.war.zip

    WAR(Web Application Archive)文件是Java EE中用于打包Web应用的标准格式,它包含了Servlets、JSPs、静态资源(如HTML、CSS、JavaScript)以及Web应用的配置文件。"cas-server-webapp-4.0.0.war"包含的是CAS...

Global site tag (gtag.js) - Google Analytics