用MIDlet激活Servlet,你可以象MIDlet激活一个CGI一样激活Servlet,本段将介绍两个例子:
第一个例子用GET操作激活Servlet,并显示结果。
第二个例子是Servlet接受用户由手机POST上来的数据
下面这个例子的内容是,FirstMidletServlet被GET方法激活并返回显示给手机。本例中并没有递交数据给Servlet, Servlet被激活后一会返回字符串“Servlet Invoked”和日期给客户端。
下面是MIDlet的代码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);
- }
- }
下面是返回“Servlet Invoked”和日期的HelloServlet代码HelloServlet.java
- 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
以上是用MIDlet激活Servlet的两个例子。