用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的两个例子。
                网站题目:用MIDlet激活Servlet
                
                URL地址:http://www.csdahua.cn/qtweb/news21/370021.html
            
网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网