Serving Dynamic WAP Content                   With Java

     In this article I will show you how easy it is to start creating dynamic content for WAP-enabled mobile phones using the Wireless Markup Language (WML) and Java Server API. Rather than list and explain all of the WML tags we will examine a sample application that will demonstrate some of the main language features.

 

A Brief Introduction to WAP and WML

    WML, the Wireless Markup Language, is designed for mobile applications. WML is a markup language that is based on XML (eXtensible Markup Language). 
WML  is part of the WAP (Wireless Application Protocol) solution for deploying information and applications to mobile units in an efficient fashion. WML considers the unique requirements of mobile units, and is designed to address issues such as small display size, small memory resources, optional keyboards, and unique network characteristics like low-bandwidth and high latency.  "Wireless Application Protocol (WAP) is a result of continuous work to define an industry wide standard for developing applications over wireless communication networks. The WAP Forum, originally founded by Ericsson, Motorola, Nokia, and Unwired PlanetWML was formed to create the global wireless protocol specification that works across differing wireless network technology types, for adoption by appropriate industry standards bodies.
    In this article I will show you how easy it is to start creating dynamic content for WAP-enabled mobile phones using the Wireless Markup Language (WML) and Sun Microsystems' Java Server API.

    WAP applications, which will be hosted on normal Web servers, can be written in WML and WMLScript. But you can also write them using existing Web technologies. Dynamic WML documents can be generated by CGI scripts, servlets, JavaServer Pages, Active Server Pages, Perl, Tcl, and so forth. In other words, you can implement your own first WAP service in Java, with the help of the WAP technologies described earlier. In this section, I am going to show you how WAP applications can be easily developed in Java using servlets and JSP.
    The main issues undertaken by a typical snippet, be it a Java servlet, that is capable of performing backend processing as well as generating results for a WML-enabled client dynamically are:
  • Retrieving the values of WML variables from the calling or referring context.
  • Specifying the correct content type of the WML deck to be generated.
  • Overriding specific header information, such as the caching mechanism, as necessary.
  • Generating valid WML content to form a well-defined WML deck.

1. The WAP Architecture

    The WAP standard defines two essential elements: an end-to-end application protocol and an application environment based on a browser. The application protocol is a communication protocol stack that is embedded in each WAP-enabled wireless device (also known as the user agent). The server side implements the other end of the protocol, which is capable of communicating with any WAP client. The server side is known as a WAP gateway and routes requests from the client to an HTTP (or Web) server. The WAP gateway can be located either in a telecom network or in a computer network (an ISP). Figure 1 illustrates an example structure of a WAP network.

    In Figure1, the client communicates with the WAP gateway in the wireless network. The WAP gateway translates WAP requests to WWW requests, so the WAP client is able to submit requests to the Web server. Also, the WAP gateway translates Web responses into WAP responses or a format understood by the WAP client.

 2. The WAP Programming Model 

    The WAP programming model is similar to the Web programming model with matching extensions, but it accommodates the characteristics of the wireless environment. Figure 2 illustrates this model. 

    As you can see, the WAP programming model is based heavily on the Web programming model. But how does the WAP gateway work with HTML? In some cases, the data services or content located on the Web server is HTML-based. Some WAP gateways could be made to convert HTML pages into a format that can be displayed on wireless devices. But because HTML wasn't really designed for small screens, the WAP protocol defines its own markup language, the Wireless Markup Language (WML), which adheres to the XML standard and is designed to enable powerful applications within the constraints of handheld devices. In most cases, the actual application or other content located on the Web server will be native WAP created with WML or generated dynamically using Java servlets or JSP. 
    In HTML, there are no functions to check the validity of user input or to generate messages and dialog boxes locally. To overcome this limitation, JavaScript was developed. Similarly, to overcome the same restrictions in WML, a new scripting language known as WMLScript has been developed. 

WAP and Java

    The normal way to serve WAP content is to have a WAP gateway server sitting between the mobile phone network and a standard web server. One reason for this is that WML is compiled or "tokenized" to conserve bandwidth. But the Nokia WAP Toolkit contains its own WML compiler and so it can talk directly to an HTTP server (in our case the servletrunner utility).
    WAP applications, which will be hosted on normal Web servers, can be written in WML and WMLScript. But you can also write them using existing Web technologies. Dynamic WML documents can be generated by CGI scripts, servlets, JavaServer Pages, Active Server Pages, Perl, Tcl, and so forth. In other words, you can implement your own first WAP service in Java, with the help of the WAP technologies described earlier. In this section, I am going to show you how WAP applications can be easily developed in Java using servlets and JSP.
1.  WML and Servlets

    Dynamic WML documents for wireless devices can be easily developed using Java servlets. Once you know the WML syntax, building WAP applications using Java servlets can be an easy task.
    A servlet processes a client request that is passed from the web server. In a WAP-based application environment, the web server receives the client (i.e., WAP device) request from a remote WAP gateway via the Internet. Alter-natively, the WAP gateway and the web server can reside on a single machine. The setup and infrastructure regarding the connectivity of the various components is cov-ered in greater detail in part VIII. Recall that the application-level protocol used in the communication between the WAP gateway and the web server is HTTP. The serv-let must understand an HTTP request message that is redirected to it from the web server, as well as generate an HTTP response message to be returned to the client via the web server. This is exactly what a servlet is doing in a web-based application environment. However, one major difference lies in the content it generates. In servicing a web-based client, the servlet generates HTML content that the client can interpret. In servicing a WAP-based client, the servlet generates WML con-tent so that the client can understand. Hence, in addition to any server-side processing an application may require, a servlet must generate an appropriate HTTP response message, which consists of the response header information such as the MIME content type and caching information, as well as the body of the response. The response body that is intended for a WAP cli-ent is a WML deck. Both the header information and the body content are generated as an output stream by the servlet.

 

GENERATING OUTPUT TO WAP CLIENTS
    To generate an HTTP output stream, we can use a servlet that is derived from HttpServlet, which defines interfaces and classes that    we can use to handle HTTP requests and create HTTP responses. Refer to appendix F for a listing of the interfaces and classes in the HttpServlet API specification. This section will show the specific methods an HttpServlet object uses to set the header information and to output the response body to a WAP client. Writing the response header information, the methods for setting or overriding an HTTP header are included in the HttpServletResponse object of an HttpServlet. We will revisit two relevant methods in this section. For a list of HTTP response headers that can be used in an HTTP response message, 

Writing the response header information

setContentType()

      For the user agent to interpret the received content correctly, we need to set the con-tent- type header field of the response message to the user agent. The servlet uses the setContentType() method to accomplish this. A valid content type of a WML message for a WAP browser is text/vnd.wap.wml. The following statement sets the appropriate content type for a response contain-ing a WML deck. The HttpServletResponse instance, response, outputs the generated content:

  response.setContentType("text/vnd.wap.wml");

 
setHeader() and setDateHeader()

    To set a header field with a string value, use the setHeader() method. Use setDateHeader() to add a header with a date value. The following statement sets the value of the Cache-Control header field to no-cache, signaling to the receiving proxy server not to cache the received mes-sage content. response.setHeader("Cache-Control", "no-cache");

Writing the response body

    After setting the header information, the servlet is responsible for generating all the relevant content in the response body that constitutes a valid WML deck. Recall from the servlet uses a writer stream (PrintWriter) object or an output stream (ServletOutputStream) object to generate output data to a client. To obtain a stream object, the servlet uses one of the following declarations depending on the type of stream you choose:

PrintWriter out = response.getWriter();
ServletOutputStream out = response.getOutputStream();

Subsequently, use the print() method or the println() method to write the output messages. The following servlet code shows how a writer stream generates the XML pro-logue that is found in a typical WML deck:  

"PrintWriter out = response.getWriter();"
out.println out.println ("<!DOCTYPE wml PUBLI\"-//WAPFORUM//DTD 
     WML 1.1//EN\"");
out.println ("\"http://www.wapforum.org/DTD/wml_1.1.xml\">");

   Creating a WAP application using a servlet We will now look at a servlet example that writes a response header and generates a simple WML deck. HelloServlet generates a message that appears in a WML browser:

Here is an Example  source code for HelloServlet.java

/* Generate a greeting: HelloServlet.java */

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class HelloServlet extends HttpServlet

{

public void init(ServletConfig config) throws ServletException {

super.init (config);

}

public void doGet (HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException

{

doPost (request, response);

}

public void doPost (HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException

{

response.setContentType("text/vnd.wap.wml");

PrintWriter out = response.getWriter();

out.println ("<?XML version=\"1.0\"?>");

out.println ("<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML1.1//EN\"");

out.println ("\"http://www.wapforum.org/DTD/wml_1.1.xml\">");

out.println("<wml>");

out.println("<card id=\"start\">");

out.println("<p>");

out.println("Hello, here's a dynamically generated greeting!");

out.println("</p>");

out.println("</card>");

out.println("</wml>");

out.close();

}

}

Code comments

  • Handles incoming HTTP GET requests. It consists of only one statement: a call to doPost(). The effect is to redirect HTTP GET requests to doPost()
  • Hence, weneed to write the client request servicing code only in doPost() since in our appli-cation, we intend to handle both types of requests in a similar manner. Originally handles only incoming HTTP POST requests. 
  • In our application, it is also called from within doGet() to handle incoming HTTP GET requests.Prints an output stream that consists of the XML prologue required in a WML deck.

Invoking A Java Servlet

    Although you can invoke a servlet by entering its URL directly in the browser inter-face, it is more often the case that a servlet is invoked from a WML card. You can also pass parameter values from the calling WML card to the servlet. In this section, we will present two other common ways to kick off a servlet.  

  • Calling a servlet from a card

To call a servlet from a card, use the WML <go> or <a> element.

Using the WML <go> element

To see how the WML <go> element works, we will use our HelloServlet example. The following code uses the <go> element to invoke HelloServlet when Accept is clicked:  

    In our example, if a client invokes the servlet using the HTTP GET method, the request is first passed to the doGet() method, which in turn calls the doPost() method to service the request. In this way, we need only to furnish the code for doPost(), which handles POST requests directly and the GET requests via redirection. If no appropriate service method can be found in the servlet, the typical error code issued by the origin server is HTTP Error 405.

 

Using the WML <a> element

The WML deck shows how a servlet can be invoked using the WML <a> element:

Figures 24.6 and 24.7 show what the WML code looks like using UP.Browser.

In general, there is no difference between the use of <go> and <a> unless you need to pass parameters to the referenced servlet as will be discussed next.

 

  • Passing parameter values

     The way to pass parameters from the calling document to the servlet depends on how the servlet is invoked.

Using explicit query string

    One straightforward means to pass parameter values to the referred servlet is to append the variable’s name and value pairs as a query string after the URL of the servlet. Here are four ways of using a query string to pass the values of two parameters, myname and mypwd:

  • Supplying parameter values to the Logon servlet via the browser interface:

    http://localhost/servlet/Logon?myname=susan&mypwd=wap

  • Supplying parameter values to the Logon servlet via the <a> element:

 <a href="http://localhost/servlet/Logon?myname=susan&amp;mypwd=wap">

    My login

 </a>

  • Supplying parameter values to the Logon servlet via the <go> element:

<go href="http://localhost/servlet/Logon?myname=susan&amp;mypwd=wap" />

  • Supplying parameter values to the Logon servlet via the onpick event of the   <option> element:    

<option

onpick="http://localhost/servlet/Logon?myname=susan&amp;mypwd=wap" />

My login

</option>

Using the <postfield> element

    Another way of passing parameter values from a WML deck to a servlet is through the WML <postfield> element, which is used with the <go>element. This code invokes a servlet with the user-input values of two variables, Name and Passwd, using the <postfield> element for each value to be passed to the servlet:

<do type="accept" label="servlet">

<go href="http://myHost:port/servlet/HelloServlet" method="post">

<postfield name="myname" value="$Name" />

<postfield name="mypwd" value="$Passwd" />

</go>

</do>

Code comments

  •     Assigns the label servlet to the Accept button of the phone interface. Pressing this key will kick off the task specified in the <go> element. Causes the current card to pass control to HelloServlet via an HTTP POST method.  
  • Specifies the name that the servlet must use to retrieve the corresponding value. Here, Name and Passwd are variables in the card’s context, but myname and mypwd are not visible within the card. 
  • The latter two variables can be retrieved from the refer-enced URL (i.e., HelloServlet) specified in the <go> element.
  • Processing Client Requests

    The way a servlet processes a request from a WML client is identical to the way it handles a request from an HTML client. Typically, a servlet is initialized when it is invoked. It then processes individual requests using the appropriate service method such as doGet() or doPost().

Retrieving header information

    Just as there are HttpServletResponse methods that a servlet can use to set HTTP header information, there are methods that a servlet can use to retrieve HTTP. There are four HttpServletRequest methods capable of retrieving informa-tion about the headers in an incoming request:

  •  getHeader("header_name") returns the value of the specified header as a string.
  • getHeaders("header_name") returns all the possible values of the speci-fiedheader as an array of strings.
  • getDateHeader("header_name") returns the value of the specified headeras a long number, indicating the number of milliseconds elapsed since midnight, Jan. 1, 1970, UTC. It can be converted into a Java Date object.
  • getIntHeader("header_name") returns the value of the specified header as an integer.
2.  WML and JSP

    Java Server Pages lets you embed Java statements within HTML documents. When JSP is invoked, it is compiled into a Java servlet and executed by the server to create a dynamic HTML document. In the case of WAP, however, you want to create dynamic WML documents. Therefore, developing WAP applications using JSP can be done easily once you know the syntax of WML.

JAWAP
    JAWAP (which was initially known as JAFFA) is Ericsson's Java Framework for WAP. It is based on RMI and servlets. I personally found JAWAP to be a bit complex to use; for example, you have to develop several classes to get a simple application up and running. Further, it doesn't seem to be stable. Using servlets or JSP to develop WAP applications is much easier than using JAWAP.
Web server configuration
   When a regular Web browser receives a page, it has to distinguish between HTML, image data, audio, and video. To enable that, with every response from the Web server, a piece of header information with every file comes down to the browser. This piece of information is known as MIME, which stands for Multipurpose Internet Mail Extension. Some of the common MIME types include text/html for HTML files and image/gif for gif files.

To enable the Web server to serve WAP documents, it needs some new MIME types. The types that WAP requires are:

  • text/vnd.wap.wml for .wml files (WML source files)

  • application/vnd.wap.wmlc for .wmlc files (WML compiled files)

  • text/vnd.wap.wmlscript for .wmls files (WMLScript source files)

  • application/vnd.wap.wmlscriptc for .wmlsc files (WMLScript compiled files)

  • image/vnd.wap.wbmp for .wbmp files (wireless bitmaps)

   Adding these MIME types varies from server to server. Check the documentation for the Web server you are running, and you'd be surprised how easy it is to add these new MIME types. In Apache, the preceding MIME types should be added to the httpd.conf fil.

Summary

    Wireless networks are mainly used for voice communication. Wireless operators, however, are interested in delivering data over wireless networks. Having become a new buzzword, WAP (Wireless Application Protocol) is designed specifically for delivering Internet data over wireless networks. This article introduces you to WAP and its related technologies (WML, WMLScript, and so forth), and shows you how to develop wireless applications using JavaTM technolog. we recapture the main tasks involved in generating dynamic content using server-side technology. Specifically, we see how a Java servlet can be invoked from a WML card as well as the ways of passing parameter values to the servlet. To generate WML output to a WAP client, the servlet needs to set the cor-rect content type, and in order that the client interprets the incoming WML response as intended, the developer is responsible for ensuring in his code the generation of a valid WML deck.

 

Reference