到 Google 资讯主页   
EasyJF首页   资料   源码   软件    论坛   网站    
   使用帮助    
    该信息为本站MyRSS系统缓存内容,部分图片及附件有可能无法正常使用.easyjf.comDevX Java信息无关,不对该信息负责.通过http://kb.csdn.net/keyword/java//../../java/Articles/200608/ea1ce886-9db9-40f5-b1c1-d533762c2026.html访问该信息的原始内容.
页面功能  【加入收藏】 【推荐给朋友】 【字体:  】 【关闭】   
Webtops: The Best of Desktop and Browser-Based Apps in One
作者: 来源:DevX Java信息  发布时间:2006-08-16 00:00:00.0

here is no denying the allure of browser-based applications: one common code base on the server, the virtual guarantee of a browser on the user's desktop, and simple installation. These advantages have in recent years fueled a mass migration of code to the server side and the near extinction of fat GUI clients. In turn, the limitations of HTML have led to a cornucopia of client-side technologies such as dynamic HTML, applets, Flash plug-ins, and more recently, AJAX (Asynchronous JavaScript and XML).

These tools have addressed some of the weaknesses inherent in browser-based applications, but they by no means offer a comprehensive solution. Applications become a hodgepodge of HTML, dynamic HTML, plug-ins, and servlets, and browser-compatibility issues continue to plague developers.

Two Java technologies, combined with AJAX-style communications, offer a comprehensive solution: Java Web Start and Java Desktop Integration Components (JDIC). Together, these tools may lead to the reemergence of rich GUI clients and a new generation of applications—called Webtops—that combine the best features of desktop and browser-based applications.

This article explores both technologies and forecasts their future in Web 2.0.

The History of Webtops

The term "Webtop" was coined as early as 1996 to characterize the migration of desktop applications to the browser. More recently, Sun used the term to describe a network-oriented desktop that is part of its Secure Global Desktop Software. The term has also been used to describe rich GUI clients that leverage new technologies to eliminate many of the code management and deployment issues that typically plague fat GUI clients.

This article uses the following definition of a Webtop application:

  1. Launched automatically from a browser hyperlink (i.e., no manual download, installation, or update process)
  2. Tight integration between the user's native browser and the Webtop application, including browser-oriented navigation tools (forward, backward)
  3. Seamless communication with a central server using HTTP
  4. Rich GUI (e.g., native look and feel, including smooth dynamic updates without requiring frequent page refreshes)

In the past, the only sure way to achieve all of these objectives was to create a browser-based application leveraging AJAX to address item four. Today, Sun's renewed focus on Java for the desktop, including the creation of www.javadesktop.org, is beginning to yield a treasure trove of practical Webtop-enabling technologies. Chief among these technologies are Web Start and the supporting Java Network Launch Protocol (JNLP) and JDIC. As you will see, JNLP and JDIC provide the foundation necessary to effectively deliver a practical Webtop application.



Web Start and JNLP

A successful Webtop application must eliminate the installation process—at least from the user's perspective—and provide the means to seamlessly deploy code updates to the user's machine. Of course, every solution requires that some code exist on the user's machine, and it must arrive there somehow. Browser-based solutions deliver code to the desktop via several channels, including the code in the browser itself, HTML, dynamic HTML, and plug-ins. For a Webtop, Web Start/JNLP is the solution.

Sun Microsystems introduced the Java Web Start framework with little fanfare in 2001. It provides the most essential feature for a Webtop: the application can be installed and launched directly from a simple hyperlink and updated automatically without user intervention. Web Start takes care of the details, automatically downloading and caching the application's jar files, updating jar files when needed, offering to provide desktop shortcuts, and handling communication details such as communication through a proxy server.

Web Start applications provide the same level of security to the user as a browser-based application. Like an applet, Web Start applications by default run in a sandbox. If the user trusts the application, however, the sandbox restrictions are lifted during installation and the application can run with the same privileges as any trusted desktop application.

JNLP is the protocol Web Start uses, although the terms 'Web Start' and 'JNLP' are often used synonymously. Most Java applications can be easily converted to run under Web Start by simply creating a .jnlp file and copying it, along with the application's jar files, to the server. Then, you can create an HTML page with a hyperlink pointing to the .jnlp file and your Web Start application will be ready to go.

The .jnlp file defines the characteristics of the application, such as the following:

  • Required jar files
  • Paths to the jar files
  • Whether the application can be used off-line
  • Whether shortcuts should be defined

Creating a .jnlp file is easy. A JNLP file typically is encoded in XML and includes sections for application information, security, and external resources (see Listing 1 for an example).


Listing 1. Typical JNLP File

<?xml version="1.0" encoding="utf-8"?> <!-- JNLP File for MyProjects Application --> <jnlp spec="1.0+" codebase="http://www.mammothsoftware.com/v2/" href="myprojects.jnlp"> <information> <title>MyProjects</title> <vendor>Mammoth Software LLC</vendor> <homepage href="../MyProjects.html"/> <description>Project Manager Application</description> <description kind="short">Project Manager Application</description> <icon kind="splash" href="images/MyProjectsSplash.gif" width="509" height="400" /> <icon href="images/mammoth.gif"/> <shortcut online="false"> <desktop/> <menu submenu="MyData"/> </shortcut> <offline-allowed/> </information> <security> <all-permissions/> </security> <resources> <property name="webStarted" value="true" /> </resources> <resources> <j2se version="1.5"/> <jar href="MyProjects.jar"/> <jar href="MyData.jar"/> </resources> <resources os="Windows"> <jar href="windows/jdic.jar"/> <nativelib href="windows/jdic_stub.jar"/> <nativelib href="windows/jdic-native.jar"/> </resource> <application-desc main class="com.mammothsoftware.app.myprojects.MyProjects2_0"/> </jnlp>

All information for the .jnlp file is contained within the <jnlp> tag. All URLs within the <jnlp> tag are relative to the codebase attribute. The <information> tag provides some basic information about the application: description, location of a custom splash screen, and shortcut information. The <offline-allowed> tag, when included, allows the application to be used off line.

The <security> tag is key; when it contains the <all-permissions/> child tag then the application will ask the user for full access to the user's machine. Therefore, the application's jar files must be signed with a certificate.

The <resources> tag provides a list of the resources the application requires, such as jar files and native files. Notice the references to jdic.jar and Windows native libraries (the next section discusses JDIC).

Lastly, the <application-desc> tag describes the main class used to launch the application.

Once the .jnlp file is ready, you drop the file on your server, place the resource files on the server in their correct location relative to the codebase attribute, and you're ready to go.

One final point: the Web server must be configured to support the JNLP MIME type. This is a simple task: just add the JNLP MIME type to a server configuration file.

Java Desktop Integration Components

Sun introduced the JDIC project in 2004 to address a primary weakness of Swing—its lack of effective integration with the native environment. Swing provides an assortment of pluggable native GUI elements, but they lack any real connection with the desktop environment, such as browser integration, application launch via a double click using the file extension, use of the system tray, etc.

JDIC rectifies this problem by providing an interface to native OS-specific features. Of course, the obvious question is 'what about write once, run anywhere?' Indeed, using JDIC today requires some minor compromises. The application must be deployed using different native libraries for each platform. Fortunately, Java Web Start automatically selects and downloads the proper native libraries to the user's machine—again, without requiring user intervention. And Sun is considering adding JDIC to Java SE, which will ease deployment considerably.

Your Webtop application requires one JDIC component in particular: the WebBrowser, which enables tight browser integration with your Webtop application. You can easily embed the user's installed browser directly into your application with just the following few lines of code:


private WebBrowser webBrowser = new WebBrowser();

private void loadStartingPage() {
    try {
        webBrowser.setURL(new URL("http://www.java.net"));
    } catch (MalformedURLException e) {
    System.out.println(e.getMessage());
}

Since JDIC provides a wrapper around the user's installed browser, rather than providing a full-fledged browser component, the download is quite small. Even better, the WebBrowser provides a WebBrowserListener that allows your application to listen for and intercept browser events:


import org.jdesktop.jdic.browser.WebBrowserListener;
import org.jdesktop.jdic.browser.WebBrowserEvent;

public class WebBrowserAdapter implements WebBrowserListener {
    public void downloadStarted(WebBrowserEvent e){
        System.out.println("Download Started");
    }
    public void downloadCompleted(WebBrowserEvent e){
        System.out.println("Download Completed");
    }
    public void downloadProgress(WebBrowserEvent e){}
    public void downloadError(WebBrowserEvent e){}
    public void documentCompleted(WebBrowserEvent e){}
    public void titleChange(WebBrowserEvent e){}
    public void statusTextChange(WebBrowserEvent e){}
}

The dowloadStarted event is especially powerful because you can easily intercept the event and then fire application-specific events. For example, when the user selects a hyperlink, you can cause an application-specific action to occur, such as displaying a menu or executing a desktop-type command. Alternatively, you can let the browser navigate to the selected hyperlink, or even navigate to different links depending on the user type and associated privileges. Thus, your application becomes richly context sensitive.

Figure 1 shows an example Webtop application with the integrated browser. In this example, when the user selects the link labeled "Switch to the Main View" the application opens a new data file and navigates to the data management portion of the application, shown in Figure 2.

Click to enlarge
Figure 1. Webtop Application with Integrated Browser

Click to enlarge
Figure 2. Typical Webtop Application Screen

Alternatively, when the user selects the link labeled "Help", the browser navigates to and displays an HTML help page. To implement this effect, you trap the downloadStarted event and examine the requested hyperlink. For certain hyperlinks, you cancel the download and execute a command instead.



Communicating with a Server, AJAX Style

Like a typical browser-based application, a Webtop application communicates with a central server to provide shared services, such as database access. When creating a browser-based application, you have two fundamental choices for server communication:
  1. Access the data via the middle tier and send HTML back to the browser
  2. Access the data from the client browser using AJAX and retrieve XML, which is then formatted into the browser using JavaScript on the client

AJAX has recently found favor among developers because it eliminates the need for frequent full page refreshes, enabling a more seamless and dynamic GUI. Nevertheless, the AJAX approach has disadvantages too—chief among them is the heavy reliance on JavaScript and its concomitant weaknesses. For example, to communicate via AJAX you write JavaScript like this:


if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
} 

Notice that each browser requires its own special code conditionalized by if statements. This, in fact, reflects the greatest difficulty with browser-based applications—for all but the simplest applications, you must write special code to manage incompatibilities and differences between all of the potential browsers that may exist on the user's desktop.

Your Webtop will use AJAX-style communications via Java. Web Start provides advantages here, too. Namely, in a corporate environment most users access the Internet through a proxy server. Using standard Java, communication through a proxy is not difficult. However, it requires a priori knowledge of the proxy server: the IP address and port it uses. You must provide this information to the Java runtime environment (JRE) either via the launching command line, for example:


java -Dhttp.proxyHost=myProxyServer.com -Dhttp.proxyPort=80 MyJavaApp

Or by setting system properties:


Properties systemSettings = System.getProperties();
systemSettings.put("http.proxyHost", "myProxyServer.com");
systemSettings.put("http.proxyPort", "80");
System.setProperties(systemSettings);

When Java Web Start launches an application, it uses a special JRE (javaws) that automatically acquires proxy information, typically from the user's browser settings, and applies the information as necessary. Thus, the developer doesn't need to require the user to discover and enter the proxy information into the application.

Sending and retrieving information AJAX-style from the server via HTTP is easy, as Listing 2 shows. In fact, standard Java SE includes a full suite of classes for implementing AJAX-style HTTP communications with a servlet.


Listing 2. Server Communications, AJAX-Style

public static String sendServletMsg(String content, URL url) { String response = ""; // URL connection channel. URLConnection urlConn; try { urlConn = url.openConnection(); // Indicate we want input. urlConn.setDoInput(true); // And we want to do output. urlConn.setDoOutput(true); // No caching urlConn.setUseCaches(false); // Set the content type. urlConn.setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); // Send POST output. DataOutputStream printout = new DataOutputStream(urlConn.getOutputStream()); printout.writeBytes(content); printout.flush(); printout.close(); // Get response data. BufferedReader input = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String str; while (null != ((str = input.readLine()))) { response += str; } } catch (IOException e) { log.warning("IO Exception in ServletUtils: " + e); } return response; }

The code in Listing 2 is actually synchronous, but you can make it asynchronous by simply executing the method in its own thread, allowing the user to continue to work with other features in the application.

The Richly Featured Desktop Client Comes Back

Most existing Java applications can be easily ported to run under Java Web Start, simply by creating a .jnlp file and signing and copying the requisite files to the server. JDIC puts Java applications on equal footing with typical desktop applications by providing access to native desktop features. Together, these powerful tools could lead to a new generation of Webtop applications and the reemergence of richly featured desktop clients.

Michael Bangham is president of Mammoth Software LLC. He has more than 20 years of programming experience and has been programming primarily in Java and C/C++ for the past 10 years.


DevX is a division of Jupitermedia Corporation
© Copyright 2005 Jupitermedia Corporation. All Rights Reserved. Legal Notices

 
相关文章
 
页面功能  【加入收藏】 【推荐给朋友】 【字体:  】 【关闭】   


EasyJF.com 2006 隐私政策 使用EasyJF前必读