用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的兩個例子。