HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML

Java Unplugged, by Kristian Cibulskis

The Web is moving to wireless and Java is making it happen! How is a wireless environment different from the Web? What languages are used for wireless devices and what features do they have? Most important, what role does the Java 2 Enterprise Edition (J2EE) play in a wireless architecture?

Wireless vs Web
There are several key differences between clients in a Web world and those in a wireless world. For example, in the wireless world network connections have a lower bandwidth and a higher latency than a typical Internet connection. Also, wireless connections are unstable and unpredictable since they're built on a wireless network - a fact you're likely familiar with from your cell phone service! The Wireless Access Protocol (WAP) was created to address network computing in this restricted environment. It defines two key aspects of wireless communication: an end-to-end application protocol and an application environment.

Figure 1: Wireless architecture
Figure 1

As shown in Figure 1, the WAP's end-to-end application protocol is built on three major components: an application server, a WAP gateway and a wireless device. The WAP gateway is responsible for routing and translating WAP data on the wireless network to and from HTTP data on a TCP/IP-based network such as the Internet. Some WAP gateways even convert HTML to languages that WAP-enabled devices can understand in a process called transcoding. The end-to-end aspect of the WAP protocol consists of four layers carried by various bearers or providers. Figure 2 compares the WAP protocol stack with a typical Internet one.

Figure 2: WAP and Internet protocol stacks
Figure 2

In addition to the end-to-end application protocol, the WAP specification also defines the application environment. This environment consists of a WML browser for rendering content and a script interpreter for executing applications on the user device. The Wireless Markup Language (WML) defines the content to be rendered by the browser using WMLScript as the scripting language. This is analogous to the Internet environment in which HTML is rendered by the browser and JavaScript is the scripting language.

The application environment was included in the WAP specification to ensure that the myriad of WAP-enabled devices can execute the same applications. No doubt you're familiar with browser compatibility problems on the Internet. Imagine if every cell phone manufacturer created their own proprietary browser - there would be hundreds maybe thousands of different browsers. What a mess!

WML and WMLScript
WML is similar to HTML in its structure and elements. However, two major distinctions are worth mentioning. The first is that WML is a subset of XML and all the rules regarding standard XML apply. This means that the entire WML document must be well formed and adhere to a DTD that describes all WML documents. The second is that WML provides extremely limited control over presentation. If you thought HTML was restrictive, wait until you start playing with WML. These severe restrictions allow for flexibility on the rendering device. Only the lowest common denominator can be assumed across all client devices. It's not just missing attributes in WML tags. Even the rendering of individual tags can appear radically different on different phones. The model for WML rendering, however, is quite similar to Java's approach. Each platform has the freedom to determine how to render a particular widget, as long as it achieves the intended functionality in a manner consistent for that platform. Although the language definition and functionality is rigid to ensure compatibility, the implementation is loosely defined to enable support for a wide variety of devices.

WMLScript is analogous to JavaScript as it's executed on the client browser. WMLScript provides a basic set of libraries to perform string manipulation, math functions, URL facilities and interaction with the WML browser. Additional libraries are being developed that allow the WMLScript programmer to access telephony aspects of the device, such as dialing a phone number or accessing the phonebook. WMLScript's purpose is to provide a richer user environment over static WML.

The easiest way to begin learning both WML and WMLScript is to work with an example. Listing 1 is an extremely simple business model: purchasing your favorite java-based product, such as a cup of coffee or a latte. A user can select the items for purchase, calculate the total and check out. The basic application flow is shown in Figure 3. The code was developed and simulated under Nokia's WAP SDK (see "References" for links).

Figure 3: Application Flow
Figure 3

Let's look at the code for the main WML page in Listing 1.

  • Lines 1-2: Standard XML syntax that indicates this document is XML and conforms to the DTD specified at http://www.wapforum.org/DTD/wml_1.1.xml.

  • Line 3: The root of a WML document is the <wml> element, similar to the <html> element of an HTML document. Since it's an XML document, it must be well formed. Without the <wml> element and the corresponding element at line 39, the document won't be processed.

  • Line 4: The basic working unit of a WML document is a card. A WML document, or deck, can be composed of one or more cards. Each card is completely self-contained and represents an individual interaction with the user. Due to the high latency inherent in wireless connections, a collection of related cards is transmitted in one deck to improve overall performance for the end user.

    Each card must have a unique identifier specified by the ID attribute. A title for the card can be specified as well. The title is usually displayed across the top of the screen, but that can change due to the creative liberty the browser takes during rendering. The newcontext attribute indicates that each time this card is entered, any variable or state should be reset. Since this first card is a splash screen, it's a good place to reset any variables that may be lingering in the context of the browser.

    The final attribute is set in line 4 in the ontimer attribute. The value for the ontimer attribute is a URL, which can be either a complete location, such as http://java.sun.com, or simply a bookmark that references another card in this deck, such as #main. In this case, when a timer expires within this card, the user will be directed to the card identified as "main."

  • Line 5: This single line sets the timer referred to in line 4. The value for this tag indicates a length of time in tenths of a second until the timer expires. Once the timer expires, the ontimer event is triggered.

  • Lines 6-13: This looks like standard HTML. The display tags of WML are extremely similar to HTML, although they're severely restricted when it comes to adjusting the display of data. For example, there's no tag to set the vertical alignment of the columns within a table. However, if you're familiar with HTML, you can probably jump right into writing WML display logic.

    Although HTML and WML provide functionality for displaying images, the WML specification only allows for WBMP image types. Many freeware converters and plug-ins can convert existing image files into WBMP format. However, since most phones are monochromatic, images that are converted from a high-resolution color source may need some tweaking in order to display nicely.

  • Line 15: This is the beginning tag for the main card in our application.

  • Lines 17-18: Here are our first input elements. Unlike HTML, there's no need for a <form> tag to enclose your input fields. Later on we'll see how these elements make it into the next request. For now, these input elements set the value of local variables within the browser context. The name of the variable is indicated by the name attribute in the input tag. These variables can be displayed elsewhere on the page with the syntax $(variablename). To display a single dollar sign, a double dollar sign ($$) is used.
    It's worth mentioning the format attribute for an input tag. This attribute indicates to the rendering device what sort of character patterns are acceptable as input. For example, the format mask in line 17 indicates that an arbitrary number of alphanumeric characters may be entered, whereas the format mask in line 18 indicates that only four characters may be entered. Format masks may also contain characters to be inserted into the input field. These characters are indicated by prefixing the character with a \ in the format mask. For example, the format mask "NNNNN\-NNNN" could be used to format a zip code entry field by supplying a dash between the first five numbers and the last four numbers during entry.

    The final attribute used for input elements is the title element. It's often used when entry for an input field actually takes place on a special edit screen. The WML browser can display this title on that screen for identification purposes.

  • Lines 19-25: The <select> element, also similar to HTML, provides a selection list that enables multiple selections as determined by the multiple attribute. In this example we want our clients to be able to purchase more than one item at a time, so the multiple attribute is set to true. Enclosed within the select element are the various choices or options to be displayed. The text within the element is displayed to the user, while the value attribute indicates the value assigned to the variable that's defined by the name attribute in the select tag. For a multiple selection element the values will all be placed into this variable with semicolon delimiters.
  • Line 26: This line displays the contents of the totalPurchase variable. Since we haven't defined it yet, the rendering agent will display a blank value. We'll update this variable using WMLScript in just a bit.

  • Lines 27-29: The <do> tag is one of the few action tags available in WML. The type attribute indicates what sort of action is required. This value determines which physical button should be linked to this action. You don't have much control over which button is chosen. On most phones the accept type used in this example is linked to the OK button on a mobile phone. Other types include prev, help and delete. Enclosed within the <do> tag is the action to be performed - in this case, to navigate to another URL. This is actually a call to a WMLScript function, so we'll hold off.

  • Lines 30-36: We have another <do> tag here with the same action type, which is perfectly legal; the user agent determines how to render it. On many cell phones it's rendered by providing a menu to select which action to perform when the button linked to this type is pressed. Here we're navigating to a different URL. The method attribute indicates whether we're performing a GET or a POST operation to this URL. And a new tag is enclosed within the <go> tag. The <postfield> tag is used to add data to a request string. The name/value pairs are provided as attributes to the <postfield> tag, and it's up to the WML browser to properly add these to the request as a query string in the case of a GET or as data fields for a POST.
At this point we have a nearly functional application. The only mysterious functionality is the URL defined in line 28, which doesn't look like a standard HTML or WML page location. This location is actually the syntax for calling a WMLScript function. The first part of the location, JavaCafe.wmls, identifies the location of the WMLScript library in which the function is contained. The second part of the URL, #calculateTotal, identifies the function we want to call. The final part of the URL, ('$(purchase)'), passes along the value of the variable purchase as a parameter to this function. The actual syntax of WMLScript is fairly similar to JavaScript, so let's look at Listing 2 to see what the JavaCafe.wmls code is doing.
  • Line 1: It declares the method signature for this function. The keyword extern indicates that this function may be called from outside this package, similar to the public keyword in Java. Our function takes a single parameter named inputPurchase. It's not necessary to declare the type of the parameter since WMLScript is a weakly typed language. Data is converted automatically from one data type to another on the fly by the script execution engine.

  • Lines 2-4: Declare and initialize three variables. Again, variables are weakly typed so no data types are required. The function call in the initialization of the purchase variable translates the escaped character string required by HTTP back into a standard string. For example, %20 is translated back into a space character.

  • Lines 5-17: This simple "for" loop iterates over the values in the purchase variable that are separated by semicolons. The elements method counts the number of elements in the string separated by the provided delimiter. The elementAt method returns the nth element of the string delimited by the provided delimiter. The "if" block is then used to calculate the total price of the order.

  • Line 18: This is the key of the entire script. The call to WMLBrowser.setVar sets the value of a variable in the scope of the WML browser to the supplied value. Here we're changing the value of the totalPurchase variable, which is displayed in line 25 of JavaCafe.wml. The String.format method, which is similar to the C function printf, is used to perform basic message formatting.

  • Line 19: The call to WMLBrowser.refresh() causes the WML browser to redisplay the current card with the latest variable information. However, this refresh is performed on the browser side. No trip back to the server is required.

A look at this example shows the similarities between WML/WMLScript and HTML/JavaScript to be fairly obvious. Although WML/WMLScript doesn't provide as much functionality as HTML/JavaScript, the basic purpose of each technology remains the same. WML and HTML are used for displaying a page of information, while WMLScript and JavaScript allow for a more interactive user experience within a page. However, one question remains: How do we generate dynamic content for the WML decks?

JSPs, Servlets and Wireless Devices
Although there are many variations within J2EE architectures, in general, JSPs develop presentation-oriented dynamic content and servlets process user input and perform conditional navigation. Ideally, all your business logic would be located outside the JSPs and servlets in either EJBs or pure Java classes. Once the business logic tier is written, different presentation layers, such as WAP, can provide the interface to the business logic.

This paradigm is extremely applicable in current Internet technology. Many businesses operate transactional HTML sites. If their business logic is kept separate from the presentation logic, providing a new presentation layer such as WAP while still using a common layer for business functionality is a fairly straightforward process.

A few simple changes need to be made to enable our JSP/Servlet engine to serve up JSPs to a wireless device. The first set of changes must be made to the Web server that serves up the output of the JSP/Servlet engine in order to recognize the new MIME types for the content being displayed. Table 1 shows the typical MIME types.

To set the proper MIME type the next change must be made to the pages or decks. We can rename JavaCafe.wml from Listing 1 to JavaCafe.jsp and simply add the following code after line 2:

<%@ page contentType="text/vnd.wap.wml" %>
After these changes, your JSP/Servlet engine shouldn't have a problem serving up JSPs to a simulated WAP device. Of course, to serve up these responses to an actual WAP device you'd need a WAP gateway that linked your network to the cellular network. However, the JSP/Servlet engine setup would remain the same.

Using servlets in this model is just as simple. For example, the Check Out action (see Listing 3) directs the user to a servlet, then returns a simple WML deck with a Thank You message that includes the user's name. The user's name was retrieved as a field posted in the request to this URL. It's a simple modification to change this servlet to interact with any existing Java purchase logic. However, keeping in line with the clean separation of business and presentation logic, this servlet could also make calls to the business tier to perform the required business logic for checkout, then redirect to a JSP page to produce the presentation to be returned to the mobile user.

Table 1: WAP MINE types

Industry Support
Nearly every application server on the market is moving to support wireless in some fashion. At the most basic level, any Web server or JSP/Servlet engine can become WAP-enabled simply by defining the MIME types discussed above. However, many application servers are beginning to offer transcoding-type services. Transcoding services provide a semi- to fully automatic way to convert existing HTML or XML pages to WML. The idea is that by using a transcoding application server, your existing site will be available to any wireless device with a minimal amount of modification to existing code. Many application server vendors are also partnering with wireless vendors to provide a complete end-to-end wireless technology stack in a single solution.

The Internet revolution has spawned billions if not trillions of dollars in new revenue streams. This is due in large part to the huge number of previously isolated people who are now empowered by the PC and the Internet to communicate in an easy and effective manner. Wireless technology extends the Internet's entry point beyond the PC. The number of wireless phones is predicted to surpass the number of land-based phones within the next three years. Most of them will be connected to some sort of wireless data service, which in turn will be connected to the Internet. The impact of this vast number of Internet clients is unimaginable. However, the implementation success that Java has had in the B2B and B2C space easily translates over to the wireless paradigm. In terms of scalability, reliability and maintainability, all the J2EE features can still be used in nearly the same way. Although it's certain that wireless architectures will evolve over time, Java will be there to help blaze the way.


  1. Nokia's WAP information center, free SDK available: www.nokia.com/corporate/wap
  2. Home of the WAP specification: www.wapforum.org
  3. Great repository of information on wireless technology: www.AnywhereYouGo.com
  4. Another excellent wireless developer portal site: www.phone.com
Kristian Cibulskis is an architect at Sapient Corporation in Boston, where he works with the Enterprise Java competency group. He holds a BS in computer science from Cornell University. He can be contacted at: [email protected].


Listing 1 

1: <?xml version="1.0"?> 
3: <wml> 
4:   <card id="splash" title="JavaCafe" newcontext="true" 
5:     <timer value="30"/> 
6:     <p> 
7:     <table columns="2"> 
8:       <tr> 
9:         <td><img src="duke.wbmp" alt="duke"/></td> 
10:         <td><small>Welcome to the JavaCafe</small></td> 
11:       </tr> 
12:     </table> 
13:     </p> 
14:   </card> 
15:   <card id="main" title="JavaCafe"> 
16:     <p> 
17:     UserId: <input name="userid" title="UserId:" format="*M"/> 
18:     Pin: <input name="pin" title="PIN:" format="NNNN" /> 
19:     Purchase: 
20:     <select name="purchase" title="Purchase" multiple="true"> 
21:       <option value="COFFEE">Coffee</option> 
22:       <option value="MOCHA">Mocha</option> 
23:       <option value="LATTE">Latte</option> 
24:       <option value="TEA">Tea</option> 
25:     </select> 
26:     Total: $(totalPurchase) 
27:     <do type="accept" label="Calculate Total"> 
28:       <go href="JavaCafe.wmls#calculateTotal('$(purchase)')"/> 
29:     </do> 
30:     <do type="accept" label="Check Out"> 
31:       <go href="http://localhost:7001/Checkout" 
32:         <postfield name="userid" value="$(userid)"/> 
33:         <postfield name="pin" value="$(pin)"/> 
34:         <postfield name="purchase" value="$(purchase)"/> 
35:       </go> 
36:     </do> 
37:     </p> 
38:   </card> 
39: </wml>
Listing 2 

1: extern function calculateTotal(inputPurchase) { 
2:   var total = 0; 
3:   var purchase = URL.unescapeString(inputPurchase); 
4:   var currentItem; 
5:   for (var i=0; i<String.elements(purchase, ";"); i++) { 
6:     currentItem = String.elementAt(purchase, i, ";"); 
8:     if(currentItem == "COFFEE") { 
9:       total += 1.25; 
10:     } else if(currentItem == "MOCHA") { 
11:       total += 2.25; 
12:     } else if(currentItem == "LATTE") { 
13:       total += 2.00; 
14:     } else if(currentItem == "TEA") { 
15:       total += 0.85; 
16:     } 
17:   } 
18:   WMLBrowser.setVar("totalPurchase", 
       String.format("$%5.2f",total) ); 
19:   WMLBrowser.refresh(); 
20: } 

Listing 3 

1: import javax.servlet.*; 
2: import javax.servlet.http.*; 
3: import java.io.*; 
4: public class Checkout extends HttpServlet { 
5:   public void doPost(HttpServletRequest req, HttpServle- 
     tResponse res) 
6:        throws IOException { 
7:     // Must set the content type first 
8:     res.setContentType("text/vnd.wap.wml"); 
9:     // Now we can obtain a PrintWriter 
10:     PrintWriter out = res.getWriter(); 
11:     out.println("<?xml version=\"1.0\"?>"); 
12:     out.println("<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD 
        WML 1.1//EN\""+ 
13:     out.println("<wml>"); 
14:     out.println("<card id=\"checkout\" title=\"JavaCafe\" >"); 
15:     out.println("<p align=\"center\">Thank You "+ 
        req.getParameter("userid") +"!</p>"); 
16:     out.println("</card>"); 
17:     out.println("</wml>"); 
18:   } 
19: } 


All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.