ONJava.com    
 Published on ONJava.com (http://www.onjava.com/)
 See this if you're having trouble printing code examples


Galago Lemur from Wireless Java

Invoking JavaServer Pages from MIDlets

by Qusay Mahmoud, author of Learning Wireless Java
12/05/2001

The next big shake-up in the industry is wireless. The benefit of wireless applications, however, becomes useful for organizations when their employees can access critical business data efficiently from anywhere they go. Therefore, the interaction between wireless applications (such as MIDlets) and external enterprise systems is important, but how can this be done?

In this article, I will show you how MIDlets can interact with JSP-based enterprise systems by walking you through an example. First, however, I will discuss the HttpConnection interface, which can be used for establishing HTTP connections.

The HttpConnection Interface

The Connected Limited Device Configuration (CLDC) provides a set of classes for network connectivity, collectively known as the generic connection framework -- a platform-independent connectivity framework that provides a hierarchy of connectivity interfaces, the implementation os which is to be provided by profiles (such as the Mobile Information Device Profile (MIDP)).

The MIDP extends the CLDC generic connection framework by providing the HttpConnection framework to support HTTP. All MIDP implementations are required to have support for HTTP, and this is mainly because HTTP can either be implemented using IP-based protocols (such as TCP/IP) or non-IP protocols (such as WAP).

All connections are created using the open() method of the Connector class. If successful, this method returns an object that implements one of the generic connection interfaces. For example, the following segment of code can be used to open an HTTP connection to a URL:

String url = "http://www.ora.com/whatif.jsp";
HttpConnection connection = Connector.open(url);

Once a connection has be established, some properties can be set, and I/O streams can be established to send and receive data. For example the following snippet of code sets some properties and establishes I/O streams:

// set some HTTP properties
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("IF-Modified-Since", 
	"20 Nov 2001 16:33:19 GMT");
connection.setRequestProperty("User-Agent",
	"Profile/MIDP-1.0 Configuration/CLDC-1.0");
connection.setRequestProperty("Content-Language", "en-CA");

// create I/O streams
InputStream is = connection.openInputStream();
OutputStream os = connection.openOutputStream();

Example: Invoke a JSP Script

Now, let's look at an example to see how to invoke JSP from MIDlets. The JSP page we want to invoke is shown in Listing 1.


Listing 1: today.jsp

<%! String name; %>
<%
name = request.getParameter("name");
java.util.Date today = new java.util.Date();
out.println("Got: "+name);
out.println("Date&time: "+today);
%>

This JSP page expects a value for a variable named name. Once the value is retrieved, an instance of Date is created, and then the name and date are printed to the output stream for the client.

Now, let's see how to write a midlet to invoke this JSP page. We will invoke it using the POST request method, meaning that the data to be sent to the JSP page is not encoded with the URL, but rather sent as a separate message. The MIDlet is shown in Listing 2.


Listing 2: InvokeJSPMidlet.java

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import java.io.*;

public class InvokeJSPMidlet extends MIDlet implements CommandListener {
  Display display = null;

  // name field  
  TextField name = null;

  Form form;

  String url = "http://127.0.0.1:8080/examples/jsp/today.jsp";
  static final Command callCommand = new Command("date?", Command.OK, 2);
  static final Command clearCommand = new Command("clear", Command.STOP, 2);

  String myname;


  public InvokeJSPMidlet() {
   display = Display.getDisplay(this);
   name = new TextField("Name:", " ", 25, TextField.ANY);
   form = new Form("Invoke JSP");

  }

  public void startApp() throws MIDletStateChangeException {
   form.append(name);
   form.addCommand(clearCommand);
   form.addCommand(callCommand);
   form.setCommandListener(this);
   display.setCurrent(form);
  }

  public void pauseApp() {
  }

  public void destroyApp(boolean unconditional) {
   notifyDestroyed();
  }


  void invokeJSP(String url) throws IOException {
    HttpConnection c = null;
    InputStream is = null;
    OutputStream os = null;
    StringBuffer b = new StringBuffer();
    TextBox t = null;
    try {
     c = (HttpConnection)Connector.open(url);
     c.setRequestMethod(HttpConnection.POST);
     c.setRequestProperty("IF-Modified-Since", "25 Nov 2001 15:17:19 GMT");
     c.setRequestProperty("User-Agent","Profile/MIDP-1.0 Configuration/CLDC-1.0");
     c.setRequestProperty("Content-Language", "en-CA");
     c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    
     os = c.openOutputStream();
     os.write(("name="+myname).getBytes());
     os.flush();

     is = c.openDataInputStream();
     int ch;
     while ((ch = is.read()) != -1) {
      b.append((char) ch);
      System.out.print((char)ch);
     }
     t = new TextBox("Date", b.toString(), 1024, 0);
     t.setCommandListener(this);
    } finally {
     if(is!= null) {
       is.close();
     }
     if(os != null) {
       os.close();
     }
     if(c != null) {
       c.close();
     }
    }
    display.setCurrent(t);
  }

public void commandAction(Command c, Displayable d) {
   String label = c.getLabel();
   if(label.equals("clear")) {
    destroyApp(true);
   } else if (label.equals("date?")) {
     myname = name.getString();
     try {
     invokeJSP(url);
     }catch(IOException e) {}
   }
}
}

The InvokeJSPMidlet specifies the URL for the JSP page to be invoked, then creates two command buttons. A text field is created where the user would enter his or her name. In the invokeJSP() method, an HTTP connection to the URL is established, and I/O streams are created. The MIDlet uses the output stream to send data to the JSP page and uses its input stream to receive data from the JSP page. Note that we are sending the name to the JSP page just to illustrate to you how data can be communicated between MIDlets and JSPs.

The most important thing to note in Listing 2 is that in order for the JSP page to use getParameter() to retrieve the value for the name variable, you must set the Content-Type property to application/x-www-form-urlencoded.

Testing

To test this application, compile the InvokeJSPMidlet using your favourite MIDlet development tool (I am using Sun's Wireless Toolkit) and run it. Once it runs, enter some name, and if everything goes well, you should see something similar to Figure 1.

i85s display.
Figure 1: InvokeJSPMidlet running on an i85s

 

i85s display.
Figure 2: today.jsp invoked.

Now, you need to deploy the today.jsp page on a Web server (I am using Tomcat). Once this is done, you can press the soft button associated with "date?" to invokde the JSP page. If all goes well, you should see something similar to Figure 2.

Conclusion

Related Reading

Learning Wireless JavaLearning Wireless Java
By Qusay H. Mahmoud
Table of Contents
Index
Sample Chapter
Full Description

This article shows how to invoke JavaServer Pages from MIDlets. The InvokeJSPMidlet framework can be easily adapted to invoke other JSPs. Note, however, that most JSPs work with HTML, but if you do not have a browser to handle HTML on the device, then XML is an attractive alternative since MIDlets can parse XML documents, and that is the topic of another article.

Qusay Mahmoud is the author of Learning Wireless Java for O'Reilly, and Distributed Programming with Java for Manning Publications.


O'Reilly & Associates will soon release (December 2001) Learning Wireless Java: Help for New J2ME Developers.

Return to ONJava.com.

Copyright © 2009 O'Reilly Media, Inc.