Quick work

This article was originally published in VSJ, which is now part of Developer Fusion.
Application designers must make some hard decisions when designing their graphical user interfaces (GUIs). Not only do they need to decide which API or library to use, but in modern networked applications they must also decide where to place and/or execute the GUI code. Traditional standalone applications have GUI code stored and executed on the client machine. Applets have GUI code that is loaded across the network and executed on the client when a web page is accessed. Each of these alternative configurations provides distinct advantages and presents particular challenges in implementation. In this article, we will consider two more alternatives.

Java Web Start/JNLP technology enables application level GUI code to be installed over the network; while web applications provide configurations in which all the GUI code is stored and executed on the server. To maintain continuity, we will be evolving the data access GUI application from the Part I of this article – DBUIApp – to these two new GUI configurations.

Client-side GUI Application installed from Server – Java Web Start

Starting with JDK 1.4, the Java Web Start technology is an integral part of the Java Runtime Environment (JRE), enabling a new mode of application deployment configuration. Unlike standalone applications, Java Web Start applications are stored on the server but installed and executed on the client. Also unlike applets, Java Web Start applications do not rely on and do not interact with a browser. Java Web Start applications are typically larger executables than an applet, and are often full-sized applications. In addition, Java Web Start applications do not have to derive from a specific class hierarchy (i.e. Applet or JApplet).

From a security perspective, Java Web Start applications are very much like applets (since it is still "downloaded-and-execute" code). This means that only applications that are stored in digitally signed JAR files, from a trusted source, will be able to access protected system resources. Java Web Start includes a set of APIs supporting user mediated file, clipboard, and printer access. Using this set of APIs, even untrusted applications (from non-signed JAR) can access files/clipboard/printer as long as the user explicitly permits the operation through an interactive prompt.

Another added benefit of Java Web Start over applets is the local caching of the executable code. Java Web Start applications can be configured to work off-line. The Java Web Start Application Manager (an integral part of Java Web Start) will manage the cached copy of the application, and will also update it should it find a newer version from the original network source.

In many ways, Java Web Start delivers the best of all worlds:

  • easy application installation and deployment
  • immediate application version update once detected, simplifying maintenance
  • secured deployment and remote installation via signed JARs
  • access to local files, clipboard, and printer when required via user mediation
  • ability to work without being connected to the network, on a cached copy of the application
  • supports Win32 systems, Linux, Solaris, and Mac OSX 10.1 and above
The details of these features are beyond the scope of this article (see my article Making a fresh start in VSJ May 2002 for detailed coverage of Java Web Start).

Taking our DBUIApp standalone application as an example, placing it into the Java Web Start architecture results in the configuration depicted in below.

DBUIApp Architecture
DBUIApp Architecture

Note that both the executable (vsjdbui.jar) and the Connector/J library (mm208.jar) are stored and maintained on the server side, while a cached copy is managed by the Java Web Start Application Manager. Execution of the application always occurs on the client side, typically from the locally cached copy of the executable and library.

Staging a Java Web Start Application

We will now modify the DBUIApp standalone application created in the previous article to become a Java Web Start application. This will require no change in the application source code, but we will need to create a configuration file for Java Web Start describing how to install and launch the application.

This configuration file is called a JNLP file, and the Java Web Start Application Manager will consult it when launching our DBUIApp application. JNLP stands for Java Network Launching Protocol and API. It is a technology developed under the JCP (Java Community Process) called JSR-056 (JSR is Java Specification Request, a deliverable in the JCP). You can get a copy of the latest specification from here.

Many popular web servers do not have built-in JNLP mime-type support. This support is necessary for things to work, since it triggers the Java Web Start Application Manager application on the client when the user clicks on the URL of a JNLP file.

Luckily, Tomcat 5 already handles jnlp mime type. If you look into the <install dir>/conf/web.xml file that Tomcat 5 uses by default, you will see the following already defined:

<mime-mapping>
	<extension>jnlp</extension>
	<mime-type>application/x-java-jnlp-file</mime-type>
</mime-mapping>
Here is the content of our JNLP file, vsjdbui.jnlp:
<?xml version="1.0" encoding="utf-8"?>
<jnlp spec="1.0+" codebase=
	"http://localhost:8080/webstart"
	href="apps/vsjdbui.jnlp">
	<information>
	<title>VSJ DB UI App via
	Java Web Start</title>
	<vendor>Visual Systems Journal, UK
	</vendor>
	<homepage href=
	"http://localhost:8080/index.html" />
	<description>Visual Systems Journal
	DB UI App via Java Web Start
	</description>
	<description kind="short">VSJ DB
	UI App JNLP</description>
	<icon href="img/vsjlogo.gif"/>
	<offline-allowed/>
	</information>
	<security>
	</security>
	<resources>
	<j2se version="1.4+"/>
	<jar href="jars/vsjdbui.jar"/>
	<jar href="jars/mm208.jar"/>
	</resources>
	<application-desc
	main-class="uk.co.vsj.DBUIApp" />
</jnlp>
The highlighted code above shows how you specify the JAR files required (vsjdbui.jar and mm208.jar) for the application, points out the main class to start the application with (uk.co.vsj.DBUIApp), and indicates the minimal level of JDK that is required to execute the code (1.4 or higher). The Java Web Start Application Manager application will take care of the rest for us.

Next, we need to create an HTML file that contains an embedded hyperlink to the JNLP file – saving the user the need to key in the URL directly. The index.html file in the /code/webstart directory of the code distribution does exactly this, it contains:

<HTML>
<HEAD>
</HEAD>
<BODY>
<H1>VSJ DB UI App via Java Web Start</H1>
<P><A HREF="apps/vsjdbui.jnlp">
<IMG SRC="img/webstart.gif">
</A>
</BODY>
</HTML>
The assumed directory structure for this Java Web Start application is shown below:

Directory structure of the Java Web Start Application
Directory structure of the Java Web Start Application

The vsjdbui.jar and mm208.jar are exactly the same code archives as the standalone DBUIApp application. You need to copy these two JAR files to the webstart\jars directory.

The webstart.gif image is used in the index.html page as a "click and start" button, while the vsjlogo.gif image is used by the Java Web Start Application Manager to create an icon for the cached copy of the application.

To test this application, startup Tomcat 5. Start a browser and point the URL to:

http://<tomcat host>:8080/webstart/index.html
You will be greeted with our index.html file as shown below:

The index.html file
The index.html file

Click on the VSJ logo image, and Java Web Start will run, and the DBUIApp application will be loaded from the network and execute on your local machine. The figure below shows the JDK 1.4.2 Java Web Start Application Manager running.

The JDK 1.4.2 Java Web Start Application Manager
The JDK 1.4.2 Java Web Start Application Manager

The Java Web Start Application Manager gives you a choice of installing a shortcut on your desktop to directly access the DBUIApp application. In fact, the application is now cached locally on your PC. If you click on the desktop Java Web Start icon, the DBUIApp can be executed without downloading any new code again (that is, of course, unless you're online and there is a newer version of the program available over the network). The figure below shows the offline launching capability of Java Web Start.

Offline launching capability of Java Web Start
Offline launching capability of Java Web Start

Java Web Start enables designers to store and maintain client-side GUI applications on the server. For our final configuration, we will see GUI code that is stored, maintained, and executed completely on the server side. This mode of operation is becoming more and more popular due to the ubiquity of web-based information and e-commerce systems. We are, of course, talking about web applications.

Server-side GUI – web applications

In a web application, the GUI is managed completely from the server side. Typically it is created in HTML and displayed on the client side by a browser. Since sending different HTML to the browser will display a different GUI, pages can be dynamically generated by the server depending on user's request and/or interactions. The figure below illustrates this server side GUI handling.

Server side GUI handling
Server side GUI handling

We can see in the illustration above that XML/XSLT may also be used in place of HTML. Popular browsers such as Internet Explorer 6 fully support XML/XSLT stylesheets on the client. Although the output from the XSLT transform typically is still HTML.

One of the most popular technologies used to generate dynamic HTML pages is Java Server Pages (JSP). We will move our DBUIApp to the server side by creating a JSP to display the user data.

The figure below shows the architecture we will use for this web application, a MVC (Model View Controller) styled design:

Model View Controller architecture
Model View Controller architecture

The request is directed to the controller DBUIServlet. This servlet performs the actual database access via the DataLoader class (model in MVC). The servlet uses the DataLoader class to obtain the row data and attaches it to the ServletRequest object. The request is then forwarded to a (configurable) JSP page where it will be rendered as HTML. The name of the JSP page we will create is called DBUIdisp.jsp (view in MVC).

We have used Tomcat 5 throughout, but any Servlet 2.4 and JSP 2.0 compliant application server may be used. The easiest way to create our controller servlet is to subclass the javax.servlet.GenericServlet abstract class. This allows us to override and implement only the methods that we are interested in. It completely relieves us of the tedium of implementing the required ServletConfig and ServletContext interfaces. Specifically for DBUIServlet, we are only implementing the init() method, and the service() method.

Tomcat ensures that init() is called once when the servlet's instance is initially loaded, and the service() method called each and every time the servlet is invoked by an incoming request. Just like the lifecycle management in DBUIApplet, we obtain the JDBC data source within the servlet's init() method.

package uk.co.vsj;
import javax.servlet.*;
import java.io.*;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class DBUIServlet extends
	GenericServlet {
	DataSource ds = null;
	public void init() throws
	ServletException {
	try {
		InitialContext initCtx =
			new InitialContext();
		if (initCtx == null)
		throw new ServletException(
		"DBUIServlet.init():
			InitialContext is null");
		String dsname=getInitParameter(
			"Datasource");
		System.out.println(
		"DBUIServlet.init(): looking
		up data source – " + dsname);
		ds = (DataSource)
			initCtx.lookup(dsname);
	} catch (Exception ex) {
		ex.printStackTrace();}
	if (ds == null)
	throw new ServletException(
	"DBUIServlet.init():
	Cannot find datasource");
}
Note that in Tomcat 5, and all Servlet 2.4 compliant containers, JDBC connections are obtained through JNDI resource lookups as illustrated above. The container provides the JNDI "emulation" necessary. Not only does this enable our code to be directly usable between different containers (since JNDI is a well specified standard interface), but it also allows the servlet container (typically an application server such as Tomcat, BEA Weblogic, Websphere, etc) to optimise the handling of the physical database connections (i.e. via connection pooling).

The service() method is called once for each incoming request. We create a DataLoader object in this method, and load the customer's data into a Vector. This Vector is then attached as an attribute (named "rows") of the incoming request by the servlet, and the request is forwarded to a JSP page (configured in the web.xml file as a servlet initial parameter to be jsp/DBUIdisp.jsp) for GUI display handling.

public void service(ServletRequest
req, ServletResponse resp) throws
ServletException, IOException {
	RequestDispatcher reqDisp =
		getServletContext().
		getRequestDispatcher(
	getInitParameter("DataJSP"));
	if (reqDisp != null) {
		DataLoader dl =
			new DataLoader(ds);
		dl.loadData("select *
			from customer");
		req.setAttribute("rows",
			dl.getRowData());
		reqDisp.forward(req, resp);
	}
}
The destroy() method is used when the servlet instance is taken out of commission by the container. It should release all resources and reset any variables that may be affected by the init() method. We simply reset the JDBC data source reference in this case.
public void destory() {ds = null;}
Instead of loading the JDBC driver via Class.forName(), the DataLoader class needs some minor modifications to make it work with JDBC data sources. The code modification is confined to the constructor, and is highlighted below:
public DataLoader(DataSource ds) {
	try {
		conn = ds.getConnection();
		stmt = conn.createStatement();
	}
	catch (SQLException ex) {
		System.err.println(
			"cannot connect.");
		System.err.println(ex);
	}
}
The DBUIdisp.jsp page is responsible for locating the "rows" attribute from the request (attached previously by the DBUIServlet) and then iterating through it to display the customer table values. It generates an HTML page as output for rendering on the client's browser.

Here, we are using Tomcat 5's new features to get the work done. Tomcat 5 supports JSTL 1.0 (The JSP Standard Tag Library) and EL (JSP 2.0's standard expression language), which makes the work of rendering tabular data in HTML particularly simple. Note how the entire JSP is completely free of embedded Java "scriptlet" coding. Here is what DBUIdisp.jsp looks like:

<%@ taglib
uri="http://java.sun.com/jstl/core_rt"
prefix="c" %>
<html>
<head></head>
<body>
<h1>Server Side UI on Web App</h1>
<table border="1" width="400">
<c:forEach var="row"
	items="${requestScope.rows}">	
<tr>
<td align="center">${row[0]}</td></tr>
</c:forEach>
</table>
</body>
</html>
The deployment descriptor for the web application, web.xml, contains the servlet definition and servlet mapping that is required. Note how we setup the two initial parameters for the servlet – the JNDI resource name for the JDBC data source, and the URL of the JSP to forward the request. Also note the <resource-ref> element that refers to the JDBC data source: a JNDI resource that is configured at the server level.
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
version="2.4">
<display-name>VSJ DB UI</display-name>
<distributable />
<servlet>
<servlet-name>dbui</servlet-name>
<servlet-class>
uk.co.vsj.DBUIServlet
</servlet-class>
<init-param>
<param-name>Datasource</param-name>
<param-value>
java:comp/env/jdbc/VSJDBUI
</param-value>
</init-param>
<init-param>
<param-name>DataJSP</param-name>
<param-value>/jsp/DBUIdisp.jsp
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dbui</servlet-name>
<url-pattern>/ListUsers</url-pattern>
</servlet-mapping>
<resource-ref>
<res-ref-name>jdbc/VSJDBUI
</res-ref-name>
<res-type>javax.sql.DataSource
</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable
</res-sharing-scope>
</resource-ref>
</web-app>
Since the container, Tomcat 5, manages the JNDI emulation (and resource pooling, etc.), we need to configure the jdbc/VSJDBUI resource in the Tomcat configuration (conf/server.xml) file. We need to configure the resource within the "/vsjuidb" servlet context. Here is what needs to be added to the server.xml file:
<Context path="/vsjdbui"
docBase="vsjdbui"
debug="5" reloadable="true"
crossContext="true">

<Resource name="jdbc/VSJDBUI"
	auth="Container"
type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/VSJDBUI">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.
BasicDataSourceFactory
</value>
</parameter>
<parameter>
<name>driverClassName</name>
<value>org.gjt.mm.mysql.Driver</value>
</parameter>
<parameter>
<name>url</name>
<value>jdbc:mysql://localhost/vsjcust
</value>
</parameter>
<parameter>
<name>username</name>
<value>root</value>
</parameter>
<parameter>
<name>password</name>
<value></value>
</parameter>
<parameter>
<name>maxActive</name>
<value>100</value>
</parameter>
<parameter>
<name>maxIdle</name>
<value>30000</value>
</parameter>
<parameter>
<name>maxWait</name>
<value>100</value>
</parameter>
</ResourceParams>
</Context>
You will need to change the username and password parameter to reflect your mySQL access account.

In the webapps\vsjdbui\WEB-INF directory of the source distribution, we have a COMPILE.BAT batch file for compiling the servlet code. You'll need to modify the path of the servlet-api.jar file to reflect your Tomcat 5 installation.

Note – at the time of writing, you must install JSTL 1.0 support separate from Tomcat 5 before the DBUIdisp.jsp will work. This involves:

  1. Download the latest version of JSTL 1.x from jakarta.apache.org/taglib
  2. Place all the tld files into the WEB-INF directory of the vsjdbui web application
  3. Place the standard.jar and jstl.jar files into the WEB-INF/lib directory of the vsjdbui web application
Subsquent versions of the Tomcat 5 container may eliminate this requirement.

With all this in place, start Tomcat 5 (using <install dir>/bin/startup script). Then use a browser to access the servlet URL:

http://<host of Tomcat>:8080/vsjdbui/ListUsers
You should see the server-side UI displaying the user database information as shown below:

User database information
User database information

Creating web applications using a web tier application server such as Tomcat 5 enables us to create an application GUI that is stored and executed on the server side. This makes the application accessible anywhere a browser is available, and facilitates the maintenance and version/release management of the system.

A Comparison

In today's networked software systems, the question "Where in the system is the GUI?" is no longer as easy to answer as it once was. Designers must make an important architectural decision in order to answer it.

The table below is a summary listing the benefits and limitations of each of the configurations that we have covered in these two articles:

Benefits and limitations
Deployment Configuration GUI Code Stored GUI Code Executed Version Update Security
standalone app. client client manual full access
Applet server within browser on client automatic, always load code from network sandboxed, unless explicitly signed and trusted by user
Java Web Start server (or cached on client) client automatic, load code from network when new version detected sandboxed, or user mediated with JNLP API, can also have explicitly signed JAR containing trusted code
web application server server, but rendered as HTML by browser on client maintained completely on the server side no resource access to local client computer required, full access on server side resources

The ubiquity of the Java platform, and the ability to transfer objects between platforms in a "write once, run anywhere" manner provide us with a wide spectrum of networked GUI deployment possibilities.


Sing Li is a consultant, trainer and freelance writer specialising in Java, web apps, distributed computing and peer-to-peer technologies. His recent publications include Early Adopter JXTA, Professional JINI and Professional Apache Tomcat, all published by Wrox.

You might also like...

Comments

About the author

Sing Li United States

Sing Li has been writing software, and writing about software for twenty plus years. His specialities include scalable distributed computing systems and peer-to-peer technologies. He now spends ...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Beware of bugs in the above code; I have only proved it correct, not tried it.” - Donald Knuth