Skip to content

Instantly share code, notes, and snippets.

@junlapong
Forked from viralpatel/HelloServlet.java
Created January 29, 2022 02:14
Show Gist options
  • Save junlapong/32860474e27575cbbb586b1d613f3400 to your computer and use it in GitHub Desktop.
Save junlapong/32860474e27575cbbb586b1d613f3400 to your computer and use it in GitHub Desktop.
HTML5 Server-Sent Events + Java Servlet example
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();
for (int i = 0; i < 20; i++) {
writer.write("data: "+ System.currentTimeMillis() +"\n\n");
writer.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
writer.close();
}
}
<!DOCTYPE HTML>
<html>
<head>
<title>Server-Sent Events Servlet example</title>
<style>
body {
font-family: sans-serif;
}
</style>
</head>
<body>
Time: <span id="foo"></span>
<br><br>
<button onclick="start()">Start</button>
<script>
function start() {
var eventSource = new EventSource("HelloServlet");
eventSource.onmessage = function(event) {
document.getElementById('foo').innerHTML = event.data;
};
</script>
</body>
</html>
<?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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment