Programmer's Guide Nokia WAP Server API 1.0
http://www.nokia.com Material code: WSRN10060WW0028 VERSION 1.0 November 18, 1999
Copyright © Nokia Corporation 1999. All Rights Reserved. Please send your comments and suggestions to: Nokia Group Finland P.O. Box 207, FIN-00045 NOKIA GROUP, FINLAND Tel. 00800 6654 2927 (00800 nokiawap), +358 9 692 7156 Fax. 00800 6054 2927, +358 9 692 6894 Internet mail address:
[email protected] http://www.nokia.com This document is provided "as is" without warranty of any kind, either express or implied, including, but not limited to, the implied warranties of merchantability, fitness for a particular purpose, or non-infringement. Nokia will not, in any event, be responsible for possible errors in this document or for any damages, incidental or consequential (including, but not limited to monetary losses), that might arise from the use of or inability to use the document or the information in it, even if Nokia has been advised of the possibility of such damages. The document could include technical inaccuracies or typographical errors. Nokia welcomes customer comments as part of the process of continuous development of the document. Any such comments shall become the property of Nokia without any duty of compensation or obligation to use. Changes are periodically added to the information herein; these changes will be incorporated in the new editions of the document. Nokia may at any time make improvements and/or changes in the product(s) and/or the program(s) described in the document. This document is part of the Nokia WAP Server. Reproduction, distribution or transmission of part or all of this documentation in any form without the prior written permission of Nokia is prohibited. Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. Java, Sun and Sun Microsystems are trademarks of Sun Microsystems, Inc. Windows NT is a trademark of Microsoft Corporation. Other product and company names mentioned herein may be trademarks or trade names of their respective owners, and are mentioned for identification purposes only.
Copyright © Nokia Corporation 1999. All Rights Reserved.
Contents
1 Introduction ............................................................................ 1 1.1 1.2 1.2.1 1.3 1.4 1.5
Overview of the WAP architecture...................................................... 1 Nokia WAP Server..................................................................................... 2 Purpose and scope.................................................................................... 2 Background ................................................................................................. 2 Terminology ................................................................................................ 3 References................................................................................................... 3
2 Overview of Java Servlets for the Nokia WAP Server........ 5 2.1 2.2 2.3 2.4 2.5 2.6
Motivation for server side programming with Java Servlets ...... 5 Servlet architecture overview ............................................................... 6 What a servlet is for the Nokia WAP Server .................................... 7 Why write servlets directly for the Nokia WAP Server ................. 7 Installing a servlet for the Nokia WAP Server ................................. 8 Tools for the Nokia WAP Server service development ................10
3 Servlet samples ..................................................................... 11 3.1 3.2
HelloWorld sample .................................................................................11 Connector sample ...................................................................................12
4 Features in the Nokia WAP Server API.............................. 15 4.1 4.2 4.3 4.3.1
Java Servlet API .......................................................................................16 WAP Service API......................................................................................17 Server Extension API ..............................................................................19 Server extension sample.......................................................................20
5 Servlets in the Nokia WAP Server...................................... 23 5.1 5.2 5.2.1 5.2.2 5.3 5.3.1 5.3.2 5.3.3
The life cycle of a servlet......................................................................23 Security ......................................................................................................24 WAP security protocol (WTLS) ............................................................24 Nokia WAP Server user authentication ...........................................25 Session tracking.......................................................................................26 Services for session tracking via the HttpSession interface...........................................................26 WML code..................................................................................................27 Other optional ways to implement session tracking...................28
Nokia WAP Server API 1.0
ii
Programmer's Guide 5.4 5.4.1 5.4.2 5.4.3 5.4.4 5.5 5.5.1 5.6 5.6.1 5.6.2 5.6.3 5.7 5.8
Error handling ..........................................................................................28 Service errors............................................................................................29 Servlet errors ............................................................................................29 Nokia WAP Server errors ......................................................................29 WAP protocol error.................................................................................29 Performance..............................................................................................30 Threading ...................................................................................................30 Servlets working together ....................................................................30 Servlet chaining.......................................................................................31 Mapping servlets to handle specific MIME types.........................33 Locating other servlets and server extensions...............................34 Pre-installed servlets .............................................................................35 WAP MIME types ....................................................................................37
6 Using javax.servlet.http interfaces with WAP protocol ... 39 6.1 6.2 6.3 6.4 6.5
Nokia WAP Server API 1.0
WSP protocol has two modes .............................................................39 WAP is message-based (not stream-based)...................................40 Response delivery in WAP....................................................................40 Wireless world has limited bandwidth.............................................41 WSP session ..............................................................................................42
1 Introduction
WAP services can be created in many ways. A simple approach is to place static WAP (WML and WML Script) content on an existing web server or a Nokia WAP Server. However, utilizing the Nokia WAP Server’s Application Programming Interfaces provides remarkable benefits for advanced WAP development. This document is directed at application developers interested in implementing versatile, dynamic services by utilizing the open programming interfaces provided by the Nokia WAP Server. This document gives an overview and specification of the programming APIs for the Nokia WAP Server. This chapter contains a short introduction to the WAP architecture and Nokia WAP Server product. Chapters 2 and 3 give an overview of programming for Nokia WAP Server and a sample program. Chapters 4 and 5 go into the details of the Nokia WAP Server application development, and the last chapter discusses the technical aspects related to WAP protocols that a programmer might find useful when fine-tuning a WAP service. The accompanying "Nokia WAP Server API reference" contains detailed interface, class and method definitions for the API. The reference material is distributed as HTML files with this document. More information about WAP can be found at http://www.wapforum.org. More information about the Nokia WAP Server can be found at http://www.nokia.com/corporate/wap.
1.1
Overview of the WAP architecture The WAP Architecture has many components. The essential ones are the WAP terminal, wireless network, WAP gateway and origin server. The following figure shows one example of an end-to-end WAP architecture.
Nokia WAP Server API 1.0
2
Programmer's Guide Datacom network Application server
Telecom network
WAP terminals
SMS, CSD, GPRS, ...
Operator network
SMS-C, IP
Company Intranet WAP gateway
Web Server
For details of the WAP architecture, see the WAP Architecture Specification [2].
1.2
Nokia WAP Server 1.2.1
Purpose and scope
The Nokia WAP Server, a software product running on Windows NT, connects Wireless Application Protocol (WAP)-enabled terminals to content and applications hosted by web servers or any other servers on the Internet or a private Intranet. It is targeted at companies that offer wireless services both internally to their employees and externally to their customers and business partners. The Nokia WAP Server enables WAP terminals to receive information from web servers and other sources, bringing the services at customers', employees' and partners' fingertips anytime and anywhere. Full standard compliance, easy management, and expandability have been the driving design goals of the Nokia WAP Server. Being a committed promoter of open industrial standards and leading manufacturer of WAPenabled mobile phones, Nokia is uniquely positioned to provide the market with a fullfeatured WAP server based on an open, extensible architecture.
1.3
Background Because Java Servlets have achieved a strong position in web application development, the same concept was selected to make it easy for developers to start developing WAP applications for the Nokia WAP Server.
Nokia WAP Server API 1.0
Introduction
3
The reader of this document is assumed to have a basic knowledge of Java Servlet development. The Java Servlet API and other servlet developer information is available at http://www.javasoft.com. The Java Servlet API 2.0 reference material is included in the [installation directory]\docs directory.
1.4
1.5
Terminology WAP gateway
A general entity in the WAP architecture between a WAP terminal in a telecom network and an origin server in a data network. The WAP gateway makes a protocol transformation from WAP to HTTP.
Nokia WAP Server
A Nokia product that acts both as an origin server and a WAP gateway.
Servlet
Servlets are software modules that conform to the Nokia WAP Server API. These modules can be plugged into the Nokia WAP Server.
Bearer Adapter
A piece of software that provides the Nokia WAP Server with network connectivity.
WPS
Wireless Protocol Stack
WSP
Wireless Session Protocol. The session layer in WPS.
WTP
Wireless Transaction Protocol. The transaction layer in WPS.
WTLS
Wireless Transport Layer Security. The security layer in WPS.
MSISDN
Mobile subscriber ISDN. (Telephone number or address of device)
References [1]
Java Servlet API, Javasoft, http://www.javasoft.com
[2]
WAP Architecture Specification, WAP Forum, http://www.wapforum.org
[3]
Wireless Session Protocol Specification, WAP Forum, 30-April-1998
[4]
RFC 2068, "Hypertext Transfer Protocol - HTTP/1.1", Fielding, R., et.al.
Nokia WAP Server API 1.0
4
Programmer's Guide
Nokia WAP Server API 1.0
2 Overview of Java Servlets for the Nokia WAP Server
2.1
Motivation for server side programming with Java Servlets Developing advanced online services to be used either through a web browser or a WAP terminal usually requires server side programming. Various technologies are nowadays used to handle clients' requests and to generate dynamic content such as shopping carts and customised home pages. Technologies such as Common Gateway Interface (CGI) scripts written in Perl or C/C++ have been widely used in the development of dynamic services. Nowadays, however, Java Servlets are becoming commonly used as an efficient platform-independent replacement for (CGI) scripts. The main benefits of using Java Servlets for server side programming are e.g.: ■
■
■
■
Persistency. Instead of creating a separate process for each request, servlets are typically loaded only once by the server and servlets can maintain services such as database connection between requests (persistent). Performance. Due to the persistency, servlets perform better than CGI. Portability. Servlets provide the benefits of the Java language: it is easy to code due to the object model and it is platform-independent (Java Servlets alreadywritten for web servers can be easily modified to be deployed also on the Nokia WAP Server). Connectivity. Java Servlets can act as middleware to enterprise Java Beans (through RMI, IDL) and other resources also via protocols other than HTTP.
For further information on the use of Java Servlets for server side programming and integration with various environments, see [1].
Nokia WAP Server API 1.0
6
2.2
Programmer's Guide
Servlet architecture overview The servlet architecture in the Nokia WAP Server is similar to the Java Servlet concept defined by Sun Microsystems Inc., which is widely used on web servers for server side programming. The basic interaction is based on a request-response model. The following figure shows the overall architecture.
Request mgmt URL mapping, Content encoding, Caching, Authentication, Access control
Java Servlet interface
WAP Protocol
Wireless bearer & WAP Protocol
WAP Server interfaces
Nokia WAP Server
Java Servlet interfaces
WAP Request (URL), WAP Response (WML)
Servlet
WAP Architecture terminology WAP Terminal
Wireless network
WAP Gateway
Origin Server WAP Service
The architecture has three major parts: WAP Terminal. The mobile user is using a user agent program on the WAP terminal. Typically, the user agent is a WAP Browser for viewing WML pages and executing WMLScripts. The WAP Terminal uses the WAP protocol in the wireless network to connect to a WAP gateway. Nokia WAP Server is communicating with WAP terminals in the wireless network with WAP protocols. When receiving a WAP request from the terminal, the Nokia WAP Server creates a HttpServletRequest and forwards it to the correct servlet. The Nokia WAP Server takes care of some of the underlying functionality like managing the servlets and their configurations, managing the requests, forwarding the request to the correct servlet, decoding the WAP request for the servlet, encoding the WML and WMLScript responses and encoding the HTTP headers for the WSP protocol. In addition to these, the server can perform user authentication, access control, response caching, etc. WAP Service. A servlet receives a request as an HttpServletRequest object from the mobile user via the Nokia WAP Server, processes the request and uses the provided HttpServletResponse to send the response to the mobile user.
Nokia WAP Server API 1.0
Overview of Java Servlets for the Nokia WAP Server
7
In addition to the Java Servlet interfaces, a WAP service can use other services provided by the Nokia WAP Server. A WAP service can also use other servlets to complete its tasks.
2.3
What a servlet is for the Nokia WAP Server As presented above, a Nokia WAP Server servlet is a piece of software that receives requests from WAP terminals via the Nokia WAP Server and returns responses to them. A servlet can serve many purposes. Some examples are: ■
■
■
WAP Connector. A servlet provides WAP connectivity to existing application servers. These could be e.g. e-mail systems, process control, logistics, fleet management, etc. WAP Filter. Pre- or postprocessor for HTTP services. This type is suitable for integrating to existing web-based services or creating filters that can perform specific tasks for other servlets. WAP Application. Application that handles WAP requests and typically provides the reply as a WML response. In this document, a WAP application is a servlet that provides the service directly without an external origin server.
Nokia WAP Server servlets can also be used to enhance the Nokia WAP Server's functionality and provide services for other servlets. This kind of servlets that implement interfaces in the Server Extension API are called server extensions.
2.4
Why write servlets directly for the Nokia WAP Server WAP services can be implemented in many ways. One way to develop WAP services is to write the application for a web server. In this case, the Nokia WAP Server works as a WAP gateway, using HTTP to connect to the application on the web server. This model works without any additional software on the Nokia WAP Server, and the service is located completely on the web server. However, this approach does not utilise all the information and services that could be used in the development of advanced, secure and user friendly WAP applications. The Nokia WAP Server provides a platform that can be used to write applications directly on top of the Nokia WAP Server. The major differences to web server application authoring are: ■ ■
WAP-specific user and protocol information is available to the servlet. Powerful WAP- and Nokia WAP Server-specific functionality is available (bearers, information push, response delivery confirmation).
■
Nokia WAP Server provides end-to-end security.
■
Web server is not required.
Nokia WAP Server API 1.0
8
Programmer's Guide ■
No additional HTTP communication is required from the Nokia WAP Server to an origin server.
In addition to this, Nokia WAP Server servlets offer an easy environment for communicating directly with origin servers that offer some application domain-specific protocol instead of HTTP. For information on implementing various back-end protocols with Java technology, see [1].
2.5
Installing a servlet for the Nokia WAP Server NOTE: The user interface screen shots in this chapter are subject to change. Once a WAP service is created as a Java Servlet, it must be installed and configured for the Nokia WAP Server. This includes several steps: 1
Install the servlet with the Nokia WAP Server Manager, which is the management user interface of the Nokia WAP Server. Provide the initial configuration information and the Java classes that implement the servlet.
2
Map a specific URL to the installed servlet and define the necessary access control to possibly limit access to your servlet.
Nokia WAP Server API 1.0
Overview of Java Servlets for the Nokia WAP Server
3
4
9
Configure the servlet. The Nokia WAP Server Manager provides a generic user interface to modify the configurable properties of servlets.
The servlet is now available for WAP terminal users. The servlet can then be accessed with a WAP terminal by selecting a URL that is mapped to the servlet.
For information on how to configure servlets with Java Archive (JAR) files, see the Nokia WAP Server Administration Guide.
Nokia WAP Server API 1.0
10
2.6
Programmer's Guide
Tools for the Nokia WAP Server service development Servlets for the Nokia WAP Server can be developed with any Java tools that conform to Sun Java JDK 1.2. The Java Servlet Development Kit is available from Sun Microsystems Inc. at http://java.sun.com/products/servlet/. Note: You have to set the classpath to the jsdk.jar and to the wapsrv.jar to be able to compile servlets that utilise the interfaces in the WAP Service API. The classpath could look e.g. like the one in the following example: c:\jsdk2.0\lib\jsdk.jar;c:\progra~1\nokia\nokiaw~1\servle ts;c:\progra~1\nokia\nokiaw~1\lib\wapsrv.jar For testing the servlet or any WAP service, a WAP terminal or some WAP terminal simulator is required. Nokia provides a software product called The Nokia WAP Toolkit that can be used to test WAP services. The Nokia WAP Toolkit contains a development environment for WML and WMLScript content creation and it has a WAP terminal simulator with a full-featured WAP browser that can be used to browse, run and debug the WAP content.
The Nokia WAP Toolkit is available at http://www.forum.nokia.com, the Nokia WAP Developer Forum's web site.
Nokia WAP Server API 1.0
3 Servlet samples
3.1
HelloWorld sample The following class presents a basic sample of a WAP service implemented as a servlet. As the sample illustrates, writing servlets producing WML content is very much like writing servlets for generating HTML content. Thus, all the knowledge regarding Java Servlets available in various sources can easily be applied to the development of servlets for the Nokia WAP Server. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** * HelloWorldServlet - a very simple servlet */ public class HelloWorld extends HttpServlet { String m_text; // the initialization parameter is read during // the initialization of the servlet public void init(ServletConfig config) throws ServletException { super.init(config); m_text = config.getInitParameter("text"); if (m_text == null) { m_text = "This is a simple test servlet."; } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println("<wml>"); out.println("
"); out.println("");
Nokia WAP Server API 1.0
12
Programmer's Guide out.println(m_text); out.println("
"); out.println(""); out.println(""); // Remember to close the out object out.close(); } public String getServletInfo() { return "The simple HelloWorld servlet."; } }
Note: The above sample is the same one that is pre-installed in the standard Nokia WAP Server 1.0 package.
3.2
Connector sample The following servlet illustrates an imaginary application that initialises an application server connection during servlet.init() and uses the application server during the request processing. The Nokia WAP Server has been configured so that it requires authentication before the request reaches the servlets. The sample service is a connector type of servlet that connects to an existing system that controls doors and locks in an office building. The door locking system provides a monthly changing PIN-code to prevent unauthorized entry to building outside office hours. The WAP service provides the authorized users the currently correct PIN-code for the selected door. The user navigates to a WML page that either contains a list of possible doors or that asks the user to supply the door ID with a WML input form. The servlet then responds with the correct PIN.
import import import import import import import
java.io.*; java.util.*; javax.servlet.*; javax.servlet.http.*; com.xcomp.DoorService.*; com.nokia.wap.server.*; samples.WMLTool;
public class WapService extends HttpServlet { // Initialization of a connection to a DoorService system DoorService doors; public void init(ServletConfig config) throws ServletException { doors = new DoorService (config.getInitParameter("ServerAddress")); doors.openConnection(); } public void doGet(HttpServletRequest req,
Nokia WAP Server API 1.0
Servlet samples
13
HttpServletResponse res) throws ServletException, IOException { String user = req.getRemoteUser(); // Authenticated user Hashtable ht = HttpUtils.parseQueryString(req.getQueryString()); String door = (String)ht.get("doorId"); int pin = doors.FetchCurrentPIN(user, door); StringBuffer response = new StringBuffer(); if (pin > 0) { response.append("Welcome, the current PIN to this door is:"); response.append(pin); } else { response.append("Sorry, correct PIN can not be provided now."); } // Create the response by using the WMLTool sample WMLTool.Deck deck = new WMLTool.Deck( new WMLTool.Card("card1", "Door Service")); deck.getCard(0).add(new WMLTool.Paragraph(response)); res.setContentType(WMLTool.WML_MIME_TYPE); res.getWriter().print(deck); res.getWriter().close(); } }
The following chapter describes in more detail the interfaces used in the sample.
Nokia WAP Server API 1.0
14
Programmer's Guide
Nokia WAP Server API 1.0
4 Features in the Nokia WAP Server API
The Nokia WAP Server APIs have been designed to make service authoring easier and to reduce the learning effort required of web service developers. Developers familiar with Java Servlet programming for web servers can get into WAP development directly. The Java Servlet concept is also open for additional functionality. When needs for more advanced WAP services occur, an existing servlet can be extended to use the additional services available in the WAP Service API, which has been desiged to provide developers with an opportunity to use the full potential of WAP. The following figure shows the logical groups of the interfaces that are available for servlet authoring.
Java Servlet interfaces
Servlets
Nokia WAP Server
Servlet
WAP Service API WAP Server interfaces
Server mgmt API
Java Servlet API
Servlet
Basic WAP Application
WAP Application
AckListener Server Extension API
Servlet
Server Extension
SomeExtension Interface
Java Servlet API. A set of standard interfaces defined by Sun that are implemented by the Nokia WAP Server and used by the WAP services. WAP Service API. A set of Nokia WAP Server-specific interfaces that provide access to advanced information and functionality in the Nokia WAP Server. The interfaces are implemented by the Nokia WAP Server and used by the WAP services.
Nokia WAP Server API 1.0
16
Programmer's Guide Server Extension API. A set of interfaces defined by the Nokia WAP Server. A servlet may provide an implementation of one of the defined interfaces and thus customize the server operation to meet specific needs. These servlets are called Server extensions. Servlet. A standard Java interface that must be implemented by all servlets. The Interface is defined as part of the Java Servlet API. AckListener may be implemented by a servlet in order to get detailed information about the response status. This interface is defined as part of the WAP Service API. Server Management API is a programming interface that provides e.g. servlet installation and configuration services to allow e.g. installation program creation for WAP services written as servlets. In practice, that can be implemented as a script that utilises the commands available via the Nokia WAP Server Command Prompt [see details of the use of the Command Prompt in the Nokia WAP Server Administration Guide].The following sections present the interfaces, their purpose and the functionality of each interface.
4.1
Java Servlet API The Nokia WAP Server provides a full implementation of the Java Servlet concept defined by Sun. The Nokia WAP Server implements the HTTP related Java Servlet interfaces on top of the WAP protocols. The Nokia WAP Server implements Java Servlet interfaces as specified for Java Servlet API 2.0. A detailed specification of the interfaces can be found in the [installation directory]\docs directory. The Nokia WAP Server contains the following interfaces and classes: Defined in the javax.servlet package: Interface Interface Interface Interface Interface Class Class Class Exception Class
ServletConfig ServletContext ServletRequest ServletResponse SingleThreadModel GenericServlet ServletInputStream ServletOutputStream ServletException UnavailableException
Defined in the javax.servlet.http package: Interface Interface Interface Interface Interface Class Class
HttpServletRequest HttpServletResponse HttpSession HttpSessionBindingListener HttpSessionContext HttpServlet HttpSessionBindingEvent
Interfaces and classes in the Java Servlet API 2.0 that can be used directly from the javax.servlet.http package: Class Cookie // Can be used as such from javax.servlet.http Class HttpUtils // Can be used as such from
Nokia WAP Server API 1.0
Features in the Nokia WAP Server API
17
javax.servlet.http
Every servlet must implement the servlet interface in order to be identified as a valid Nokia WAP Server servlet. There are some basic differences in the underlying WAP protocols that may affect WAP service development when the Java Servlet API is used. For details, see Chapter 6 and the enclosed Nokia WAP Server API Reference in the[installation directory]\docs directory.
4.2
WAP Service API This group of interfaces provides access to advanced information and functionality in the Nokia WAP Server. It is not required to use any of the interfaces listed in this group when creating a WAP service. However, the interfaces provide application developers with information and services that enable the development of user friendly and secure applications. The interfaces are accessed via the ServletRequest.getAttribute() or via the ServletContext.getAttribute(), depending on the interface. The following interfaces are found in the com.nokia.wap.server package. Interface
Description
Used by
WapRequest
Provides WAP-specific information about a WSP request. E.g. protocol configuration, bearer, WSP session. Provides services to manage the requests, e.g. abort() the request.
A WAP service that needs more information about the request than the HttpServletRequest can provide or wants to e.g. abort a request.
WapServer
Provides services to register and locate server extension interfaces.
A servlet author who wants to register a server extension interface to make it known by the Nokia WAP Server or wants to locate an implementation of a server extension.
Nokia WAP Server API 1.0
18
Programmer's Guide
Interface
Description
Used by
AckListener
Provides detailed information about the status of a response created by the servlet. E.g. successful delivery to the terminal.
A WAP service that needs to know if the response is really delivered or not. This could be used e.g. for billing purposes. The AckListener implemented by a servlet is registered to the Nokia WAP Server using the WAPServer interface during the servlet.init() procedure.
ShortMessaging
Provides functions for sending textual and binary non-WAP short messages (SMS) with the Nokia WAP Server bearers.
A WAP service that wants to notify the user with SMS or send binary messages to the terminal, e.g. ringing tones.
HttpManager
Provides HTTP protocol functionality for HTTP client including caching.
A WAP developer needing to make an HTTP service request to an origin server.
AlarmManager
Provides access to the Nokia WAP Server alarm information. Via this interface, a servlet can get the active alarms in the system and acknowledge them.
A WAP service that wants to get and acknowledge alarms. This interface is commonly used together with the AlarmHandler extension.
BearerManager
Provides information about available bearers.
A WAP service that needs to select the bearer for e.g. push purposes.
UserDirectory
Provides information about the Nokia WAP Server users, user groups and details about individual users.
A WAP service that needs user identification or other user information.
New interfaces may be added in the future releases of the Nokia WAP Server. For a detailed description of the above mentioned interfaces, see the enclosed Nokia WAP Server API Reference.
Nokia WAP Server API 1.0
Features in the Nokia WAP Server API
4.3
19
Server Extension API The Nokia WAP Server provides an open architecture for WAP development. The Server Extension API is a group of interfaces defined by the Nokia WAP Server that are used by the Nokia WAP Server itself or by servlets. A servlet may provide an implementation of one of the defined interfaces and thus customize the server operation to meet specific needs. All server extensions must provide the Servlet interface. It is used to load, initialize and destroy the servlet instance. Servlets providing an implementation of some interface in the Server Extension API may provide an empty service() method in the Java Servlet API, because the servlet does not provide any direct service for requests and thus the service() method is never called. A URL mapping to the servlet does not need to exist. For example, if a developer implements a more advanced access log writing functionality that integrates the Nokia WAP Server logging into an existing billing system, the developer will: 1
Implement a servlet that provides the Servlet interface and AccessLogWriter interface.
2
In a servlet.init()call made by the Nokia WAP Server, register the exposed AccessLogWriter interface to the Nokia WAP Server via the com.nokia.wap.server.WapServer interface by using the registerExtensionService() method.
3
When an event to be written to the access log occurs inside the Nokia WAP Server, the logAccess() method of the registered interface is called and the server extension has all the information there is in the access log entry.
4
The Nokia WAP Server never calls the service() method of the servlet if there is no URL mapping defined for the servlet.
If a servlet wants to use a server extension, the com.nokia.wap.server.WapServer interface provides methods for locating an implementation. For each interface, it is defined whether there can be several registered implementations. The following interfaces have been defined for the Nokia WAP Server 1.0 release:
Nokia WAP Server API 1.0
20
Programmer's Guide
Interface
Purpose
AccessLogWriter
Provides a customized log writer for access information. Can be used to e.g. collect billing information.
AlarmHandler
Enables an extension to receive and handle alarms generated in the Nokia WAP Server. Using this interface, a WAP Server extension can integrate to existing alarm management software.
For a detailed description of the interfaces, see the enclosed Nokia WAP Server API reference.
4.3.1
Server extension sample
The following sample illustrates how integration with existing billing information system can be implemented. The sample code shows how to create a server extension that implements the AccessLogWriter interface and maintains a persistent connection to a billing system. As discussed later [see 5.1], a servlet can initialise persistent connections during the initialisation of the servlet. import javax.servlet.*; import com.nokia.wap.server.*; import com.bcomp.billing.*; public class WapService extends GenericServlet, implements com.nokia.wap.server.extension.AccessLogWriter { // My connection to on-line billing system BillingOnLine billSystem; public void init(ServletConfig config) throws ServletException { // create and open connection to actual system billSystem = new BillingOnLine(config.getInitParameter("SysName")); billSystem.loginAsRecordCreator(config.getInitParameter("BFo rmat")); // Get WAPServer interface ServletContext myCntx = config.getServletContext(); WapServer iServ=(WapServer)myCntx.getAttribute ("com.nokia.wap.server.WapServer"); // Register myself as AccessLogWriter iServ.registerExtensionService( "com.nokia.wap.server.extension.AccessLogWriter", this); } // AccessLogWriter methods
Nokia WAP Server API 1.0
Features in the Nokia WAP Server API
21
public void LogAccess(AccessLogEntry entry) { if (entry.getWspStatusCode() == 0x20) { Brecord br=billSystem.createRecord(entry.getUserid()); br.setSelector(GetServiceName(entry.getRequestedUrl())); billSystem.commit(br); } }
String GetServiceName(URL url) { return …; } }
Nokia WAP Server API 1.0
22
Programmer's Guide
Nokia WAP Server API 1.0
5 Servlets in the Nokia WAP Server
This chapter gives a more technical description of the dynamics of a servlet in the Nokia WAP Server.
5.1
The life cycle of a servlet Servlets are loaded dynamically by the Nokia WAP Server. The loading is done using the normal Java class loading and initialisation facilities. The Nokia WAP Server loads the servlet when the server starts or when the servlet is installed.
WAP Request : method, URL, headers, request data Nokia WAP Server
init()
WAP Response : status, response data, response headers
service()
Servlet
destroy()
After the loading, the following three main methods are involved in the life cycle of the servlet: Servlets are activated by the Nokia WAP Server through an init() call. Servlets are likely to provide their own implementation of this method to perform the possibly slow and costly initialization of the servlet only once, rather than once per request. With the init() call, the servlet receives the configuration information (ServletConfig). The Nokia WAP Server provides a user interface for editing and maintaining these configuration settings.
Nokia WAP Server API 1.0
24
Programmer's Guide After the initialization, the servlets handle many requests. Each terminal request generates one service() method call. These requests can be concurrent. The request processing goes on until the Nokia WAP Server explicitly shuts down the servlet by calling the destroy() method. The Nokia WAP Server provides a "reload servlet" functionality for the administrator. The servlets see this as a destroy() call for the current servlet instance, followed by the creation of a new instance and an init() call for it. If the configuration of the servlet is changed, the updated configuration is provided in the init() call for the new instance.
5.2
Security The Nokia WAP Server is responsible for an end-to-end security solution for the servlets. The Nokia WAP Server takes care of all the security issues and a servlet does not have to implement anything in order to be accessed securely. This chapter describes how a servlet can know the level of security and the authentication method that the Nokia WAP Server has used to identify the servlet user. The Nokia WAP Server also has access control features that are not visible to the servlets. These features contain URL based access control and terminal access control. Terminal access control means that the Nokia WAP Server can be accessed only with defined terminals. For a detailed description of the Nokia WAP Server security and access control features, see the Nokia WAP Server product information.
5.2.1
WAP security protocol (WTLS)
The Nokia WAP Server supports the WAP security protocol, which provides the following security features: ■
Content encryption
■
Content integrity
■
Server authentication using certificates
The level of security varies depending on the algorithms used. The algorithms are selected by the Nokia WAP Server administrator. With the WapRequest.getSecureClass() method, a servlet can query the security class that is used by the WTLS security. If the WTLS protocol is not used at all, the method also returns the information about that. Nokia WAP Server administrator selects the server certificates to be used. Note: A WAP service author has no way of influencing when WTLS is used and when it is not used. The terminal decides when to use WTLS : it might use it always or it may have a user option for that. Also, an HTTPS scheme in the WML deck has no influence on whether WTLS is used or not. It is up to the Nokia WAP Server or the servlet to allow or
Nokia WAP Server API 1.0
Servlets in the Nokia WAP Server
25
disallow communication to origin servers or to a local application when WTLS is not used. You should also note that as the Nokia WAP Server 1.0 does not support HTTPS to the origin server, the HTTPS requests are not served at all. In case high security is needed, the most important thing is to have WTLS security between the WAP terminal and the Nokia WAP Server hosted by the trusted party (the company itself). Then the connection from the Nokia WAP Server to the origin server within the trusted domain can be implemented over plain HTTP.
5.2.2
Nokia WAP Server user authentication
The Nokia WAP Server applies user authentication if so requested by the Nokia WAP Server administrator. The user authentication can be applied with OR without using the WTLS protocol. The user authentication can be done in the following ways: ■
■
Using the HTTP proxy authentication protocol [4]. The Nokia WAP Server user database contains the users and their passwords. The Nokia WAP Server uses the Basic authentication scheme for the proxy authentication. Using terminal address information. For each user, the administrator can define a set of terminal addresses (MSISDN numbers), which can be marked as "trusted" MSISDN numbers.
Servlets have access to the authentication information, which contains the following items: who the authenticated user is and how the authentication was done. WapRequest.getAuthenticationType() returns which of the above mentioned authentication types was used. If the authentication is not done, user information is not available with the other functions. WapRequest.getUserId() provides the Nokia WAP Server specific ID of the authenticated user. The ID can be used to access information via the UserDirectory interface. WapRequest.getUserName() provides the Nokia WAP Server username of the authenticated user if it is available. HttpServletRequest.getRemoteUser() provides the user's Nokia WAP Server username only if the user has been authenticated with proxy authentication. HttpServletRequest.getAuthType() returns the proxy authentication scheme that was used for the authentication. When the WTLS protocol is used, HTTP proxy authentication is a very reliable way of authenticating users. If a servlet requires separate user authentication, it may use the HTTP authentication for its own purposes. For details, see [4].
Nokia WAP Server API 1.0
26
5.3
Programmer's Guide
Session tracking It is often necessary to keep track of how a user navigates in a WAP service and what kind of interrelated actions the user performs within one WAP session (e.g. what items are collected into a shopping cart). Thus, the WAP application has to be able perform session tracking. There are several alternatives for implementing session tracking with the Nokia WAP Server. All the options below are possible for implementing session tracking, and there is no single right way to implement session tracking in WAP applications. The best practice should be selected case by case, depending on the application type (e.g. the amount of information that is tracked during the session).
5.3.1
Services for session tracking via the HttpSession interface
The standard Java Servlet API defines the HttpSession interface, which enables session management. For details of the use of the HttpSession interface, see [1]. Note: URL rewriting is implemented in the Nokia WAP Server API as defined in the Java Servlet API, but instead of cookies, the Nokia WAP Server implementation uses WSP session IDs for session identifying. However, also note the following remarks and other optional ways for implementing session tracking.
Nokia WAP Server API 1.0
Servlets in the Nokia WAP Server
WSP Session ID
27
The Nokia WAP Server creates a unique session ID for each WSP session. The WSP session is created only in the connection oriented mode and you should note that e.g. Nokia 7110 creates a new WSP session for each CSD call. For additional information on the WSP protocol, see [3]
The session ID can be retrieved also for application session handling purposes via the WapRequest interface by using the getWapSessionId() method.
Note: the WSP session IDs are the same for all the servlets. Thus, several servlets can utilise the IDs created by the Nokia WAP Server.
5.3.2
WML code
WML variables retain their values between requests and thus are a nice way to implement session tracking. WML code generated e.g. by servlets (or some script on the origin server) can thus include the necessary session information in the form of variables. For further information, see e.g. the WML Reference document included in the Nokia WAP Toolkit.
Nokia WAP Server API 1.0
28
Programmer's Guide
5.3.3
Other optional ways to implement session tracking
WTLS Session ID
The Nokia WAP Server creates a unique ID for each WTLS session. This ID remains the same for subsequential WTLS connections, depending on the terminal implementation (in the case of Nokia 7110, the ID remains the same). The session ID can be retrieved for application session tracking purposes via the WapRequest interface by using the getWtlsConnectionId() method. Note: WTLS session IDs are the same for all the servlets. Thus, several servlets can utilise the IDs created by the Nokia WAP Server.
Cookies
Cookies can be used e.g. by the origin server to handle sessions in the WAP application. In that case, the Nokia WAP Server will pass the cookies from the origin server to the terminal and vice versa. However, it is important to notice that not all WAP terminals (such as Nokia 7110) support cookies and thus the use of this option should be considered very carefully.
5.4
Error handling Like all programming, WAP programming must also handle errors. In WAP servlet programming, errors can occur in various phases of the processing. This section outlines the error types, defines the Nokia WAP Server behaviour in these situations and suggests how the servlets should handle errors. ■
■
■
Service error. The servlet detects that there is an error, and the requested service can not be provided to the terminal user. E.g. there is insufficient input for the service or a broken database connection. Servlet error. The servlet works incorrectly, e.g. creates an invalid WML page, provides content type that is not supported by the terminal, provides content too large for the terminal, or the servlet goes into an infinite loop. Nokia WAP Server error. The WAP Server fails to convert, encode or deliver the given content.
Nokia WAP Server API 1.0
Servlets in the Nokia WAP Server ■
29
WAP Protocol error. Delivering the data fails due to networking problems, terminal out of battery power, failed security, etc.
5.4.1
Service errors
Service errors are handled in WAP as they are handled in HTTP. A servlet should use either HttpServletResponse.sendError(code, msg) with the appropriate HTTP status code. If msg is provided, it is sent in a WML page to the terminal. The code is one of the SC_* error status codes defined in the HttpServletResponse. The servlet should use an error code from the 400 range of HTTP error codes. The servlet can also decide to report a service error with an SC_OK status and provide a WML page describing the problem.
5.4.2
Servlet errors
These errors are detected by the Nokia WAP Server. The request is responded with an HTTP status code from the 500 range, and the servlet is provided the information via the AckListener interface if it has been registered. If the servlet uses too much time for the service() call, the Nokia WAP Server will terminate the request processing, unload the servlet and then reload and initialize it again. The interrupted request is returned to the terminal with an SC_GATEWAY_TIMEOUT status. The servlet can throw a ServletException or IOException when service() is called. If the ServletException is thrown, the Nokia WAP Server sets the status of the response to SC_SERVICE_UNAVAILABLE. The AckListener interface is not called for service() calls that have thrown an exception.
5.4.3
Nokia WAP Server errors
If the Nokia WAP Server fails to convert, encode or deliver the given content, the request is responded to with an HTTP status code from the 500 range, and the servlet is provided with the information via the AckListener interface.
5.4.4
WAP protocol error
If the delivery of the content fails at the protocol level (timeout, communication error), the servlet will be informed in case it has registered an AckListener interface. This applies to requests made using the connection-oriented WSP protocol. When the connectionless WSP protocol is used, these errors are never delivered to the servlet.
Nokia WAP Server API 1.0
30
5.5
Programmer's Guide
Performance A Nokia WAP Server servlet is a fast way to provide a response to a request. This is because servlets run in the same process context as the Nokia WAP Server. Activating a servlet requires only a lightweight thread context switch for the Nokia WAP Server. On the other hand, the WAP protocol processing, content encoding and other Nokia WAP Server functionality require processor time. Thus, WAP services requiring a lot of processing power should be placed on another machine if the number of requests is great. For that kind of services, servlets are more like WAP connectors than standalone WAP applications.
5.5.1
Threading
Servlets run in the same process as the Nokia WAP Server. When several clients try to use the servlet simultaneously, the service() method is called by several threads concurrently. The servlet should itself protect class specific data and other necessary resources from concurrent access. If the servlet is not prepared for concurrent use, it should implement the SingleThreadModel interface. This ensures that the Nokia WAP Server will call the service() method of the servlet only from one single thread.
5.6
Servlets working together A servlet can be in various roles in a complete WAP service. As discussed earlier, a servlet might perform preprocessing of WAP terminals' requests that will be forwarded either to another servlet or to an origin server. Alternatively, a servlet might perform postprocessing of data returned by an origin server or another servlet in the Nokia WAP Server. Thus, servlets could serve e.g. the following practical purposes: ■
■
■
■
A servlet might preprocess the WAP terminal's request in order to check e.g. the security class of the request before the request is forwarded to any other servlet or origin server. A servlet might incorporate some information (such as MSISDN number or type of connection) from the WAP Service API's interfaces to the HTTP request that will be forwarded to the origin server. A servlet might filter the origin server's response based on specific rules (e.g.to optimise the content for a specific terminal) A servlet might monitor the service and register the AckListerner interface in order to verify the delivery of the response (for creating accurate billing information or for ensuring some specific business logic).
Depending on the application's needs, various techniques can be used to link servlets to work together or to perform above type of filtering for terminals' requests or origin servers' responses:
Nokia WAP Server API 1.0
Servlets in the Nokia WAP Server ■
■
■
■
31
Servlet chaining. The Nokia WAP Server supports servlet chaining, which is an easy way to link several servlets to process a WAP terminal's request. MIME type mapping. The Nokia WAP Server supports mapping of MIME types to specific servlets to perform postprocessing of predefined content types returned by e.g. another servlet or origin server. Locating other servlets via ServletContext. Servlets can locate other servlets via Java Servlet API's ServletContext to perform specific tasks. Locating server extensions. Finally, servlets can utilise server extensions, which are servlets implemented by the developer to enhance the Nokia WAP Server's functionality to serve specific needs.
The following sections describe the techniques in further detail.
5.6.1
Servlet chaining
The Nokia WAP Server supports servlet chaining, which provides an easy means for passing the output of one servlet to another servlet as input. The output of the last servlet in the chain is sent back to the terminal as a response to the terminal's request. As illustrated in the picture below, a servlet chain might include pre-processing of the requests, fetching information from the origin server and post-processing of the origin server's response. All of the servlets in the chain can be mapped to a single URL.
Nokia WAP Server API 1.0
32
Programmer's Guide Nokia WAP Server
ServletRequest Application server
Preprocessor
Connector ServletResponse
HTTP request HTTP response
Postprocessor
Servlet chaining: an output from one servlet is passed as input to another servlet. The Nokia WAP Server 1.0 does not provide an administration interface for configuring servlet chains, but you can easily configure them by editing the configuration files located in the [installation directory]\config directory.
Configuration file
Description
Servlets.config
Defines the loaded servlets and their initialization parameters. All these definitions can be configured from the Nokia WAP Server Manager. Thus, editing this file is not recommended as the servlets can be created and configured via the Nokia WAP Server Manager.
UrlMappings.config
Defines the URLs mapped to servlets and servlet chains. Note: URL mappings to a single servlet can be configured from the Nokia WAP Server Manager, but file editing is needed for the servlet chaining.
NOTE: The Nokia WAP Server MUST NOT be running when editing the configuration files. You must shut down the Nokia WAP Server before you edit the configuration files and you must restart it after you have configured all the configuration files.
Nokia WAP Server API 1.0
Servlets in the Nokia WAP Server
33
Mapping URLs to servlet chains by editing the UrlMappings.config file The following syntax can be used for mapping URLs to servlets or servlet chains. However, mapping URLs to a single servlet can be done via the Nokia WAP Server Manager, the management user interface of the Nokia WAP Server, and thus editing the file is needed only when mapping URLs for servlet chains.
Syntax: urlmap.total=[total number of the url mappings] urlmap.[number].name=[servlet name] urlmap.[number].url=[url mapping]
Example: urlmap.total=4 urlmap.1.name=FileServlet urlmap.1.url=http\://yourdomain/file/ urlmap.2.name=HelloWorld urlmap.2.url=http\://yourdomain/helloworld/ urlmap.3.name=FilterSample,HeaderSample urlmap.3.url=http\://yourdomain/myfirstchain/ urlmap.4.name=HTTPManager urlmap.4.url=http\://
5.6.2
Mapping servlets to handle specific MIME types
A servlet can be mapped to handle particular MIME types returned by another servlet or an origin server. A typical example of the use of the MIME type mapping is e.g. conversion of text/html to wml so that the response that is of the text/html MIME type is automatically directed to a servlet that converts the content to wml. The same approach can also be used for e.g. converting various image formats to the wbmp format by using appropriate image converters.
Nokia WAP Server API 1.0
34
Programmer's Guide Defining mappings for MIME types by editing the MimeTypeMappings.config file Mapping specific MIME types to an appropriate filter (servlet) can be done by editing the MimeTypeMappings.config file in the [installation directory]\config directory.
Configuration file
Description
MimeTypeMappings.config
Defines the MIME types mapped to appropriate servlets. In the Nokia WAP Server 1.0 release, MIME types can be configured only by editing this file (not via the management user interface). The following syntax must be used.
Syntax: mimetypemap.total=[total number of the filter mappings] mimetypemap.[number].filter=[filter name] mimetypemap.[number].mimeType=[mime type]
Example: mimetypemap.total=1 mimetypemap.1.filter=jsp mimetypemap.1.mimeType=java-internal/java-html
NOTE: The Nokia WAP Server MUST NOT be running when you are editing the configuration files. You must shut down the Nokia WAP Server before you edit configuration files and restart it after all the configuration files are configured.
5.6.3
Locating other servlets and server extensions
Servlet chaining and content filtering are not the only ways to make several servlets to interact with each other. A servlet migh want to utilise other servlets installed into the Nokia WAP Server e.g. in the following ways:
Nokia WAP Server API 1.0
Servlets in the Nokia WAP Server
5.7
35
Locating servlets via ServletContext
One way to locate other servlets is to use the ServletContext services in the Java Servlet API. Once you have the servlet interface of another servlet, the service method of the located servlet can be called.
Locating server extensions
A servlet might want to use a server extension that provides an implementation of some interfaces defined in the Server Extension API. In that case, the servlet can locate the desired extensions by using the QueryInterface and getProviders methods in the com.nokia.wap.server.WapServer interface.
Pre-installed servlets There are some servlets pre-installed on the Nokia WAP Server. These include: HTTPManager
A servlet that provides connectivity to origin servers via HTTP. The servlet is an integrated part of the Nokia WAP Server and can not be removed. The servlet can be used by other servlets that need to request information from the origin servers via HTTP. The HTTPManager can be used e.g. in the servlet chain.
FileServlet
A servlet that provides access to files saved locally to the [installation directory]\wap_root directory. The servlet must be configured for various content types. See the Nokia WAP Server Administration Guide for further information on the use of the FileServlet.
The FileServlet and HTTPServlet are features of the official Nokia WAP Server 1.0 product. In addition to these servlets, there also are some samples with source code that are included in the product package to help developers to learn to write Java Servlets. These samples include e.g.:
Nokia WAP Server API 1.0
36
Programmer's Guide
HelloWorld
The HelloWorld is a simple example of how to write Java Servlets. The servlet is also included in this document.
AckListenerSample
The sample illustrates how the AckListener interface can be used to verify the delivery of the response. Also, the sample illustrates one of the ways of implementing session handling with the Nokia WAP Server.
WapRequestSample
The sample illustrates how to obtain WAPspecific information from the WapRequest interface.
WMLTool
The WMLTool sample illustrates how writing servlets to generate WML can be simplified by creating appropriate utilities. The related WMLToolSample illustrates the use of the WMLTool utility. See also the JavaDoc reference documentation in [installation directory]\docs for the details of the WMLTool sample.
HeaderSample
The HeaderSample can be used to echo the HTTP headers back to the WAP terminal. This sample can be used e.g. together with the FilterSample. A simple servlet chain can be implemented according to the servlet chain configuration instructions in this document so that the FilterSample adds some information to the HTTP headers and the HeaderSample prints the headers back to the terminal.
FilterSample
The FilterSample illustrates how information, such as WAP–specific information from the WAP Service API, can be added to HTTP headers that are then received by another servlet in a servlet chain or an origin server.
Note that the samples that are located in the [installation directory]\servlets\samples directory have to be configured with the package name (samples.servletname).
Nokia WAP Server API 1.0
Servlets in the Nokia WAP Server
37
Note that the above samples are provided for learning purposes only. Samples, such as the WMLTool, can be further developed to meet specific needs, but no official support or maintenance is provided for the samples.
5.8
WAP MIME types WAP defines its own MIME types for WAP-specific content types. Typically, a WAP terminal can accept the following MIME types: application/vnd.wap.wmlc
Encoded WML
application/vnd.wap.wmlscriptc
Encoded WMLScript
image/vnd.wap.wbmp
WAP graphics format
Note that all WAP terminals may not support WMLScripts or bitmaps. In addition to these, some more specialised content types can be accepted:
application/vnd.wap.wtls-ca-certificate
Certificate Authors WTLS format certificate
When a request comes to the Nokia WAP Server, it adds some accepted content types to the request before forwarding it to the servlet. The following content types are added:
Nokia WAP Server API 1.0
38
Programmer's Guide
MIME type
Description
text/vnd.wap.wml
Textual WML. If the servlet sets the content-type to this type, the Nokia WAP Server automatically encodes the given WML page before it is sent to terminal.
text/vnd.wap.wmlscript
Textual WMLScript. If a servlet sets the content-type to this, the Nokia WAP Server automatically compiles and encodes it before sending it to the terminal.
text/html
Textual html. If a servlet is willing to return HTML, the Nokia WAP Server will convert it to WML and encode it before sending it to the terminal.
In addition to these, the MIME types defined in the MIME type mapping (see 5.6.2) are added to the request's accept header. Terminals may accept multipart content types. If a servlet replies with a multipart response containing e.g. textual wml and textual wmlscript, the Nokia WAP Server can correctly encode the individual subparts with the appropriate encoder. Note that the WAP protocols and the Nokia WAP Server can be used to deliver any content type to the WAP terminal. So, the Nokia WAP Server's content delivering ability is not limited to WAP content types.
Nokia WAP Server API 1.0
6 Using javax.servlet.http
interfaces with WAP protocol
The WAP/WSP protocol is essentially a binary form of HTTP/1.1. The Nokia WAP Server provides a complete implementation of the Java Servlet API 2.0, and existing servlets can be run directly on the Nokia WAP Server. There are some basic differences in the underlying WAP protocols that may affect WAP service development when the Java Servlet API is used. This chapter describes the biggest differences at the WAP and HTTP concept level. The enclosed Nokia WAP Server API Reference in the [installation directory]\docs directory contains notes about the notable differences between implementing servlets for WAP and for HTTP.
6.1
WSP protocol has two modes The WSP protocol has two modes of operation: the connection-oriented and connectionless mode. The essential difference between these modes is that the connection-oriented mode uses the WTP transaction protocol and thus provides a reliable service. Connectionless requests are just datagrams that can be lost or duplicated, and they can arrive in a different order than they were sent, and the same applies to responses. The Nokia WAP Server accepts and negotiates the WSP sessions with the terminals. Session creation is allowed to all terminals that are allowed to communicate with the Nokia WAP Server. Servlets receive the connectionless requests and connection-oriented requests identically as a HttpServletRequest into their service() (or doGet()) method. If a servlet wants to know how the request was delivered, it should get the WapRequest interface and use the IsConnectionMode() method. A connectionless service does not have associated session information. This means that session headers can not be used to optimise bandwidth usage, the maximum allowed response size can not be known, the maximum datagram size of the bearer limits the response sizes, and requests can not be aborted. Both session protocol modes can operate over the security layer (WTLS).
Nokia WAP Server API 1.0
40
6.2
Programmer's Guide
WAP is message-based (not stream-based) The HTTP protocol is built on reliable TCP connections. When an HttpServlet on a web server writes its response to the OutputStream, it assumes that the response is then delivered unless the stream writing fails and throws an exception. WAP does not have a connection-based reliable stream for data transfer. WAP has the Wireless Transaction Protocol (WTP), which provides reliable transactions as its basic service. Servlet requests in the WSP connection-oriented mode are delivered with a WTP class 2 transaction invoke, and the servlet response is delivered in the Result part of the transaction. When the terminal has successfully received the response, it acknowledges the result. Server
Terminal 1 2 3
Invoke Result Ack
This has some effects on the behaviour of the servlets using the Java Servlet API. InputStream. When the input stream is being read, the actual data is already in the Nokia WAP Server and thus reading from the stream is fast. OutputStream. The servlet creates its output by writing to the ServletOutputStream object. The output stream provided by the Nokia WAP Server is not a stream to the terminal, instead it is a memory-based stream that is copied to a WSP protocol message after the service() and sent to the terminal with the Response part of the WTP protocol. Sending the response starts after the service() method has returned. Calling os.close() or os.flush() in service() are ignored by the Nokia WAP Server. Response Headers. There is a fixed place in the WSP protocol for sending the HTTP headers in encoded format and for the status code. Sending the HTTP headers starts after the service() method has returned. The limitations defined in the Java Servlet API for setting all the headers and status code before writing the response body thus do not apply in the Nokia WAP Server, but it is recommended that you follow the instructions.
6.3
Response delivery in WAP As mentioned in the previous section, WAP is not stream-based and thus the delivery of the response including the status, body and response headers starts after the servlet service() method has returned. This means that a servlet using the Java Servlet
Nokia WAP Server API 1.0
Using javax.servlet.http interfaces with WAP protocol
41
API has no way of getting information about if the response was delivered or not. This also applies to origin server-based architecture: the origin server has no means of getting information about whether the response was delivered to the WAP terminal or not. Often, however, this is an important requirement in order to ensure consistency of a business process (e.g. to make sure that an assignment to a field worker was delivered to the WAP terminal) or to establish accurate billing procedures (a customer is charged only for successful service transactions). The Nokia WAP Server defines an AckListener interface, which can be implemented by a servlet that requires the response delivery status information. Servlets willing to receive this information must provide their AckListener interface to the Nokia WAP Server during the servlet.init() method through the com.nokia.wap.server.WapServer interface that can be retrieved via ServletContext.getAttribute(). The Nokia WAP Server will then during the response delivery provide information to the servlet about the status of the delivery with the following functions: ■
AckListener.ResponseError(reasonClass, reasonCode, ServletRequest, ServletResponse) to inform that the response was not delivered to terminal, because the transaction has been aborted by the terminal or by the Nokia WAP Server. If the terminal is out of coverage, out of battery power or inaccessible for some other reason, the response delivery is aborted by the Nokia WAP Server due to timeout in the WTP protocol.
■
AckListener.ResponseConfirmed(String ackHeaders, ServletRequest, ServletResponse) to inform that the response was successfully delivered to the terminal and the terminal has acknowledged it.
The ServletRequest and ServletResponse are the same objects that were given to the servlet in the servlet.service() call. WSP requests made using the connectionless WSP protocol are never confirmed or aborted by the Nokia WAP Server. For details, see the Nokia WAP Server API Reference.
6.4
Wireless world has limited bandwidth The driving goal of the WAP protocol development has been to optimise the bandwidth usage of the protocols. This optimisation has some effects on the servlets. Header encoding. The WSP protocol defines a compact binary encoding of the textual HTTP headers. The Nokia WAP Server does this encoding automatically when the response delivery starts. Status code. A servlet can set the response status with the status codes defined in the HttpServletResponse interface. The Nokia WAP Server converts the status code to the 8-bit format defined in the WSP protocol. The textual description added with setStatus() in the HttpServlet interface is ignored by the Nokia WAP Server.
Nokia WAP Server API 1.0
42
Programmer's Guide Aborting a request. A servlet can also choose to abort a request. If the request is aborted, the terminal does not need to provide an acknowledgement and thus saves it sending a datagram. The request aborting can be done with the WapRequest interface in the Nokia WAP Service API. Limited data capacity of terminals. Terminals are devices that often have limited processing power and memory capacity. The WSP protocol provides session negotiation where the terminal can express the maximum packet data size it can receive. If a servlet tries to send a response that is known by the Nokia WAP Server to be too big, an error page is returned to the terminal and the servlet is informed if it has registered an AckListener interface. Note that size limitations apply to actual data content, so if the servlet replies with a WML page, the limitation applies to the encoded WML page. The defined maximum size of a WSP data unit for terminals is 1400 bytes.
6.5
WSP session The WSP protocol defines the concept of a WSP session. The session provides a context for making requests and sending responses. A session holds information that helps to optimise the bandwidth usage. A session contains the following information: Session headers. A WSP session holds information about server and client headers that remain constant for each request and response. If a request and response contain headers that are equal to the headers in the session, there is no need to transfer them per request or response. The Nokia WAP Server takes care of removing the unnecessary headers from the response and automatically adding the client session headers to the request headers before passing the request to the servlet. Protocol options. The terminal and the Nokia WAP Server negotiate WSP protocol options during the session setup or resumption. These options specify e.g. if push is allowed, the maximum data amount that can be sent or received, if resumption is allowed, etc. Header code pages. If additional header code pages have been negotiated, the Nokia WAP Server will automatically use them during header encoding. Extended methods. If extended methods are used, the HttpServlet helper functions like doGet() can not be used. Instead, the service() method must be overridden and the correct action taken based on the extended method.
Nokia WAP Server API 1.0