用MIDlet激活Servlet可以象MIDlet激活一个CGI一样激活Servlet本段将介绍用GET操作激活Servlet并显示结果和Servlet接受用户由手机POST上来的数据这两两个例子
Servlet被激活后一会返回字符串“ServletInvoke和日期给客户端。下面这个例子的内容是FirstMidletServlet被GET方法激活并返回显示给手机。本例中并没有递交数据给Servlet.
下面是MIDlet代码FirstMidletServlet.java
importjava.io.*;
importjavax.microedition.io.*;
importjavax.microedition.lcdui.*;
importjavax.microedition.midlet.*;
/**
*AnexamplMIDlettoinvokaCGIscript.
*/
publicclassFirstMidletServletextendMIDlet{
privatDisplaidisplay;
Stringurl="http://somesite.com/servlet/HelloServlet";
publicFirstMidletServlet{
displai=Display.getDisplaithi;
}
//Initialization.InvokewhenMIDletactivates
publicvoidstartA pp{
try{
invokeServleturl;
}catchIOExceptione{
System.out.println"IOException"+e;
e.printStackTrac;
}
}
discontinu.... //Pause.
publicvoidpauseA pp{}
//Destroimustcleanupeverything.
publicvoiddestroyA ppbooleanuncondit{}
//Preparconnectandstreamtheninvokservlet.
voidinvokeServletStringurlthrowIOException{
HttpConnectc=null;
InputStreamis=null;
StringBuffb=newStringBuff;
TextBoxt=null;
try{
c=HttpConnectConnector.openurl;
c.setRequestMethodHttpConnection.GET;
"20Jan200116:19:14GMT"; c.setRequestProperti"IF-Modified-Since".
"Profile/MIDP-1.0Configuration/CLDC-1.0"; c.setRequestProperti"User-A gent".
"en-CA "; c.setRequestProperti"Content-Language".
i=c.openDataInputStream;
intch;
//receivresponsanddisplaiitinatextbox.
whilech=is.read!=-1{
b.appendcharch;
}
b.toStr,t=newTextBox"FirstServlet".1024,0;
}final{
ifis!=null{
is.clos;
}
ifc!=null{
c.close;
}
}
display.setCurrt;
}
}
下面是返回“ServletInvoke和日期的HelloServlet代码HelloServlet.java
importjava.io.*;
importjava.util.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
/**
*Thesimplestpossiblservlet.
*/
publicclassHelloServletextendHttpServlet{
publicvoiddoGetHttpServletRequestrequest