Pushlets: Send
events from servlets to DHTML client browsers
Tutorial Details:
Pushlets: Send events from servlets to DHTML client browsers
Pushlets: Send events from servlets to DHTML client browsers
By: By Just van den Broecke
Discover how pushlets, a servlet-based notification mechanism, enables server-side Java objects to call back JavaScript code within a client browser.
hese days, developers increasingly turn to servlets and JavaServer Pages (JSPs) as Web-based frontends that integrate backend databases, Enterprise JavaBeans, or legacy applications. It is, however, difficult to keep client Web browsers up-to-date when the state of backend application data changes after the client has loaded the HTML page. For example, how do you keep one user up-to-date when she views the contents of a database table in her browser while another user simultaneously updates that same table on the server?
Indeed, applications such as live stock feeds, flight-arrival information, or weather-condition updates, in which the server streams or pushes live data, are difficult to create with servlets or JSPs.
How can we ensure these applications will be capable of notifying the browser after HTML page loading? Or, how can we selectively update parts of a page, such as updating only the stock whose price has changed? As seasoned Java developers, we often reflexively think of applets that use sockets or RMI/CORBA as the only server-to-client notification solution.
In this article we'll look at a solution that may better serve our purpose. First, I describe the current solutions for server-to-Web client notification. Next, I introduce pushlets as an alternative -- and possibly unconventional -- notification mechanism and then present a simple pushlet framework with some sample applications. Finally, I discuss some of the advantages and disadvantages of applying pushlets.
Note: This article's examples and complete source code can be viewed and downloaded from http://www.fluidiom.com:8080
Server-to-Web client notification: Current solutions
Before we delve into the pushlet concept, let's review the existing server-to-Web client solutions. Assume we have a Java Web or application server from which we want to notify client browsers. Possible solutions can be categorized as HTML refresh, server-side callbacks, and messaging.
HTML refresh
The simplest notification solution is the HTML refresh. By using tags in the header of the HTML document, the page automatically reloads every n seconds. If something has changed on the server since the last reload, we get the new content; otherwise, we get the original page. The following simple line, placed between and in an HTML page, does the trick:
While this solution is simple, we must still ask, how long should we make the refresh interval?
Server-side callbacks
In server-side callbacks, a server object calls back a Java-applet client using RMI (Remote Method Invocation) or CORBA (Common Object Request Broker Architecture). Usually the client first passes a remote reference of an RMI or CORBA object to the server. The server keeps a list of those references and calls them sequentially at the time of notification. This solution has been discussed in detail in other JavaWorld articles (see Resources ).
Messaging
In messaging, an applet is a client of a messaging server that pushes messages over a TCP/IP connection ( java.net.Socket ) or sends connectionless UDP messages ( java.net.DatagramSocket ), the latter possibly even with multicast ( java.net.MulticastSocket ). You can use messaging middleware (MOMs), such as SoftWired's iBus, IBM's MQSeries, and BEA Systems' WebLogic Events, or develop your own custom messaging with java.io.ObjectStream on top of TCP or UDP sockets. The Java Messaging Service (JMS) is an important standard for messaging.
Each of the above solutions has its advantages and disadvantages in complexity, security, performance, scalability, browser Java compatibility, and restrictions such as firewalls. The optimal solution strongly depends on the requirements of your application. For example, when users require a direct interaction with the state, such as in a shared whiteboard, server-side callbacks or messaging can be a powerful technique.
But we are still working within the confines of a browser. Unless the applet constitutes the entire client application, it is difficult to integrate the HTML content with the updates coming from the server. Considering this, how can we alter the content from within the applet when it gets the callback or message? A frequent solution is to refresh the page by calling AppletContext.showDocument(URL) within the callback method. This instructs the browser to change the page with the new URL.
Enter pushlets
Since HTML is a powerful layout language, wouldn't it be nice to be able directly to alter parts of the HTML content with incremental data coming from the server? This would be an ideal scheme for Web applications where content on the server changes dynamically and the required user-to-server interaction -- for example, that driven by HTML forms.
The pushlet mechanism I developed is lightweight and thin on the client; it requires no applets or plug-ins, directly integrates with scripting and HTML, and uses standard HTTP connections; and it can be deployed (in theory!) in any Java-servlet server. It is certainly not meant to replace the traditional solutions outlined above. On the contrary, pushlets may be another option in your toolbox. As a Java architect or developer, you can determine the trade-offs and choose what is best for your particular application.
Pushlet basics
So what are a pushlet and how does it work? In its basic form a pushlet is extremely simple. I will show the basics through a few examples. It's also time to see some code!
HTTP streaming
Pushlets are based on HTTP streaming, a technique sometimes used in multimedia viewing applications such as QuickTime or RealAudio. Instead of closing the HTTP connection after fetching an HTML page, the connection remains open while fresh data is pushed to the client.
Taking the idea of HTTP streaming, we could develop a JSP or servlet that continuously sends new HTML content back to the client in a timer loop, as seen in the example below:
<%
int i = 1;
try {
while (true) {
out.print(""+(i++)+"");
out.flush();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
out.print(""+e+"");
}
}
} catch (Exception e) {
out.print(""+e+"");
}
%>
To see this example in action, from the Pushlets page, click on Examples, then Basics. Then click Run from the HTML Push section. The above example is not terribly useful, since the pushed content is continuously appended to the page while our intention was to alter the loaded content (that is, to show only the actual value of the counter).
In our next example, we jump right into the pushlet mechanics. Again from the Pushlets Examples-Basics page, click Run from the JavaScript Push section. Notice that the page refreshes every 3 seconds. How is that done?
The JavaScript Push example consists of three files: push-js-stream.html , push-js-stream-pusher.jsp , and push-js-stream-display.html . The main page, push-js-stream.html , contains each of the two other files in HTML frames. Let's just follow the route of the events.
When requested, push-js-stream-pusher.jsp , a JavaServer Page, executes on the server. The file's main body is listed below:
7: <%
8: /** Start a line of JavaScript with a function call to parent frame. */
9: String jsFunPre = " ";
13:
14: int i = 1;
15: try {
16:
17: // Every three seconds a line of JavaScript is pushed to the client
18: while (true) {
19:
20: // Push a line of JavaScript to the client
21: out.print(jsFunPre+"Page "+(i++)+jsFunPost);
22: out.flush();
23:
24: // Sleep three secs
25: try {
26: Thread.sleep(3000);
27: } catch (InterruptedException e) {
28: // Let client display exception
29: out.print(jsFunPre+"InterruptedException: "+e+jsFunPost);
30: }
31: }
32: } catch (Exception e) {
33: // Let client display exception
34: out.print(jsFunPre+"Exception: "+e+jsFunPost);
35: }
36: %>
In line 21 above, we see a timer loop that prints HTML to the browser every 3 seconds. But wait, it's pushing JavaScript, not HTML! What does this mean? Effectively, it pushes a line such as .
What does it mean for the browser? The browser, with its JavaScript engine running, obediently executes each line coming in. It calls the parent.push() JavaScript function. Now the parent is the parent of the frame it is in, which is the push-js-stream.html file:
The push() function called from within the JSP frame ( pushlet
Read
Tutorial at: Click here to view the tutorial
Rate Tutorial: Pushlets: Send
events from servlets to DHTML client browsers
View Tutorial: Pushlets: Send
events from servlets to DHTML client browsers
Related
Tutorials:
Understanding JavaServer Pages Model 2
architecture - JavaWorld December
1999
Understanding JavaServer Pages Model 2
architecture - JavaWorld December
1999 |
Create dynamic images in Java servlets - JavaWorld May
2000
Create dynamic images in Java servlets - JavaWorld May
2000 |
Develop n-tier
applications
using J2EE - JavaWorld December 2000
Develop n-tier
applications
using J2EE - JavaWorld December 2000 |
Servlet 2.3: New
features exposed - JavaWorld January
2001
Servlet 2.3: New
features exposed - JavaWorld January
2001 |
Servlets in Apache Tomcat and BEA Systems' WebLogic Server - JavaWorld February 2001
Servlets in Apache Tomcat and BEA Systems' WebLogic Server - JavaWorld February 2001 |
Java Web Start to the rescue - JavaWorld July
2001
Java Web Start to the rescue - JavaWorld July
2001 |
Pushlets: Send
events from servlets to DHTML client browsers
Pushlets: Send
events from servlets to DHTML client browsers |
Use Web services
to integrate Web applications with
EISs
Use Web services
to integrate Web applications with
EISs |
Publish
Publish event-driven Web content with JSP custom tags |
Track wireless sessions with J2ME/MIDP
Track wireless sessions with J2ME/MIDP |
Discover and publish Web services with JAXR
Discover and publish Web services with JAXR |
Enhance your J2EE presentation layer
Enhance your J2EE presentation layer |
Handling Events in JavaServer Faces, Part 1
In this excerpt from the book, author Hans Bergsten looks at the JSF event model, using examples to help explain what\'s going on "under the hood." |
Primrose - Free J2EE Database Connection Pooling Software
Primrose
Primrose is a database connection pool, written in Java.
Current containers support are Tomcat 4 & 5, and JBoss 3.
There is also now a standalone version of primrose that can be used for applications not running inside a container.
|
Advanced form processing using JSP
Processing HTML forms using servlets, or more often, CGI scripts, is one of the most common operations performed on the Web today. However, that JavaServer Pages (JSPs) can play a significant role in sophisticated form processing is a little-known secret. |
Internet & Intranets: Java Servlets
What are servlets?
"Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to upd |
Servlet Essentials
This document explains the concepts of Java Servlets and provides a step-by-step tutorial for writing HTTP Servlets with complete source code for the example Servlets. The tutorial and the other chapters cover all facets of Servlet programming from a ... |
Accessing Database from servlets through JDBC!
Accessing Database from servlets through JDBC!
Java Servlets
J ava Servlets are server side components that provides a powerful mechanism for developing server side of web application. Earlier CGI was developed to provide server side capabilities |
Techniques used for Generating Dynamic Content Using Java Servlets.
Techniques used for Generating Dynamic Content Using Java Servlets.
Techniques used for Generating Dynamic Content
Common Gateway Interface (CGI)
For any web application high performance and timely delivery are key ingredients to competitive |
Brief Introduction to the Web Application development
Brief Introduction to the Web Application development
Brief Introduction to the Web Application development
Gone are the days of serving static HTML pages to the world. Now a days most website serves the dynamic pages based on the user and their |
|
|
|