Use MIDlet to activate Servlet. You can activate Servlet like activating a CGI in MIDlet. This section describes two examples:
In the first example, use the GET operation to activate the Servlet and display the result.
The second example is that Servlet accepts the user's POST data from the mobile phone.
In the following example, the FirstMidletServlet is activated by the GET method and is returned to the mobile phone. In this example, no data is submitted to the Servlet. After the Servlet is activated, the string "Servlet Invoked" and date are returned to the client.
Below is the MIDlet code FirstMidletServlet. java
- import java.io.*;
- import javax.microedition.io.*;
- import javax.microedition.lcdui.*;
- import javax.microedition.midlet.*;
-
- /**
- * An example MIDlet to invoke a CGI script.
- */
-
- public class FirstMidletServlet extends MIDlet {
- private Display display;
- String url = "http://somesite.com/servlet/HelloServlet";
-
- public FirstMidletServlet() {
- display = Display.getDisplay(this);
- }
-
- //Initialization. Invoked when MIDlet activates
- public void startApp() {
- try {
- invokeServlet(url);
- } catch (IOException e) {
- System.out.println("IOException " + e);
- e.printStackTrace();
- }
- }
-
- //Pause, discontinue ....
- public void pauseApp() { }
-
- //Destroy must cleanup everything.
- public void destroyApp(boolean unconditional) { }
-
- //Prepare connection and streams then invoke servlet.
- void invokeServlet(String url) throws IOException {
- HttpConnection c = null;
- InputStream is = null;
- StringBuffer b = new StringBuffer();
- TextBox t = null;
- try {
- c = (HttpConnection)Connector.open(url);
- c.setRequestMethod(HttpConnection.GET);
- c.setRequestProperty("IF-Modified-Since", "20 Jan 2001 16:19:14 GMT");
- c.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
- c.setRequestProperty("Content-Language", "en-CA");
- is = c.openDataInputStream();
- int ch;
-
- // receive response and display it in a textbox.
- while ((ch = is.read()) != -1) {
- b.append((char) ch);
- }
- t = new TextBox("First Servlet", b.toString(), 1024, 0);
- } finally {
- if(is!= null) {
- is.close();
- }
- if(c != null) {
- c.close();
- }
- }
- display.setCurrent(t);
- }
- }
The following is the HelloServlet code HelloServlet. java that returns "Servlet Invoked" and date.
- import java.io.*;
- import java.util.*;
- import javax.servlet.*;
- import javax.servlet.http.*;
-
- /**
- * The simplest possible servlet.
- */
-
- public class HelloServlet extends HttpServlet {
- public void doGet(HttpServletRequest request
The above are two examples of activating Servlet with MIDlet.
- Wizard for creating Servlet Filters
- Install Servlet and JSP development tools
- Extended Future Response Servlet
- Servlet Container matching process
- User cache Servlet