`
wangxc
  • 浏览: 209688 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Midlet与Servlet传递Cookie

    博客分类:
  • J2ME
阅读更多
Cookie在Java ME平台中没有得到支持,因此要想维持客户端和服务器端的状态则必须要使用URL重写的方式.
 
   Cookie的工作原理如图:
  


   浏览器根据 域(domain) 和 路径(path) 检查是否有匹配的cookie,如果有则把cookie 以“名称 = 值” 的形式发送给服务器

    获取(客户端) cookie 的方式:
 
HttpConnection.getHeaderField("set-cookie");


 
J2ME中得到服务器端的cookie并保存到RMS中,下文代码的实现思路是:
 
  1.打开RMS并读取RMS中是否存有cookie;
  2.连接服务器,采用get请求,如果RMS中有cookie,那么设置
 http.setRequestProperty("cookie", cookie);

  3.如果RMS中没有记录(cookie),那么将服务器端通过
http.getHeaderField("set-cookie");
得到的cookie保存到RMS中。

J2ME中的核心代码:

 
   package com.easymorse;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextBox;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.RecordStore;

public class Cookie extends MIDlet implements CommandListener,Runnable{

	private Display display;
	  private TextBox tbMain;
	  private Form fmMain;
	  private Command cmExit;
	  private Command cmLogon;
	  private String cookie = null;
	  private RecordStore rs = null;  
	  static final String REC_STORE = "rms_cookie";  
	  private String url = "http://dev.mopietek.net:8080/cookieServer/cookieServlet"; //连接公司服务器地址
	  
	  public Cookie()
	  {
	    display = Display.getDisplay(this);

	    // Create commands
	    cmExit = new Command("Exit", Command.EXIT, 1);
	    cmLogon = new Command("Logon", Command.SCREEN, 2);    
	    // Create the form, add commands, listen for events
	    fmMain = new Form("");
	    fmMain.addCommand(cmExit);
	    fmMain.addCommand(cmLogon);
	    fmMain.setCommandListener(this);

	    // Read cookie if available
	    openRecStore();   
	    readCookie();
	      // System.out.println("Client cookie: " + cookie);        
	  }

	  public void startApp()
	  {
	    display.setCurrent(fmMain);
	  }    

	  public void pauseApp()
	  { }

	  public void destroyApp(boolean unconditional)
	  { 
	    closeRecStore();  // Close record store
	  }

	  public void openRecStore()
	  {
	    try
	    {
	      // The second parameter indicates that the record store
	      // should be created if it does not exist
	      rs = RecordStore.openRecordStore(REC_STORE, true);
	    }
	    catch (Exception e)
	    {
	      db("open " + e.toString());
	    }
	  }    
	  public void closeRecStore()
	  {
	    try
	    {
	      rs.closeRecordStore();
	    }
	    catch (Exception e)
	    {
	      db("close " + e.toString());
	    }
	  }

	  /*--------------------------------------------------
	  * Write cookie to rms
	  *-------------------------------------------------*/
	  public void writeRecord(String str)
	  {
	    byte[] rec = str.getBytes();

	    try
	    {
	      rs.addRecord(rec, 0, rec.length);
	    }
	    catch (Exception e)
	    {
	      db("write " + e.toString());
	    }
	  }

	  /*--------------------------------------------------
	  * Read cookie from rms
	  *-------------------------------------------------*/
	  public void readCookie()
	  {
	    try
	    {
	      byte[] recData = new byte[25]; 
	      int len;

	      if (rs.getNumRecords() > 0)
	      {
	        // Only one record will ever be written, safe to use '1'      
	        if (rs.getRecordSize(1) > recData.length)
	          recData = new byte[rs.getRecordSize(1)];
	        len = rs.getRecord(1, recData, 0);
	        /*rs.getRecord(arg0,arg1,arg2); //返回值是所复制的数据的字节数
	                          第一个参数是读取数据库中的第几条,第二个参数是保存读取的数据(recData),第三个参数是指定数据写入(recData)中的起始位置索引
             */  
	        cookie = new String(recData);
	      }
	    }
	    catch (Exception e)  {
	      db("read " + e.toString());
	    }
	  }

	  /*--------------------------------------------------
	  * Send client request and recieve server response
	  *
	  * Client: If cookie exists, send it to the server
	  *
	  * Server: If cookie is sent back, this is the 
	  *         clients first request to the server. In
	  *         that case, save the cookie. If no cookie
	  *         sent, display server body (which indicates
	  *         the last time the MIDlet contacted server).
	  *-------------------------------------------------*/    
	  private void connect() throws IOException
	  {
	    InputStream iStrm = null;
	    ByteArrayOutputStream bStrm = null;
	    HttpConnection http = null;    
	    try
	    {
	      // Create the connection
	      http = (HttpConnection) Connector.open(url);

	      //----------------
	      // Client Request
	      //----------------
	      // 1) Send request method
	      http.setRequestMethod(HttpConnection.GET);
	      // If you experience connection/IO problems, try 
	      // removing the comment from the following line
	      //http.setRequestProperty("Connection", "close");      

	      // 2) Send header information
	      if (cookie != null)
	        http.setRequestProperty("cookie", cookie);
	      System.out.println("Client cookie: " + cookie);      

	      // 3) Send body/data - No data for this request
	      //----------------
	      // Server Response
	      //----------------
	      // 1) Get status Line
	      if (http.getResponseCode() == HttpConnection.HTTP_OK)
	      {
	        // 2) Get header information         
	        String tmpCookie = http.getHeaderField("set-cookie");        
	           System.out.println("server cookie: " + tmpCookie);
	        // Cookie will only be sent back from server only if 
	        // client (us) did not send a cookie in the first place.
	        // If a cookie is returned, we need to save it to rms
	        if (tmpCookie != null)
	        {
	          writeRecord(tmpCookie);
	          // Update the MIDlet cookie variable
	          cookie = tmpCookie;
	          fmMain.append("First visit\n");          
	          fmMain.append("Client : " + cookie + "\n");
	        }        
	        else  // No cookie sent from server
	        {
	          // 3) Get data, which is the last time of access
	          iStrm = http.openInputStream();
	          int length = (int) http.getLength();
	          String str;
	          if (length != -1)
	          {
	            byte serverData[] = new byte[length];
	            iStrm.read(serverData);
	            str = new String(serverData);
	          }
	          else  // Length not available...
	          {
	            bStrm = new ByteArrayOutputStream();       
	            int ch;
	            while ((ch = iStrm.read()) != -1)
	              bStrm.write(ch);

	            str = new String(bStrm.toByteArray());
	          }
	          // Append data to the form           
	          fmMain.append("Last access:\n" + str + "\n");                   
	        }
	      }
	    }
	    finally
	    {
	      // Clean up
	      if (iStrm != null)
	        iStrm.close();
	      if (bStrm != null)
	        bStrm.close();                
	      if (http != null)
	        http.close();
	    }
	  }
	  /*--------------------------------------------------
	  * Process events
	  *-------------------------------------------------*/
	  public void commandAction(Command c, Displayable s)
	  {
	    // If the Command button pressed was "Exit"
	    if (c == cmExit)
	    {
	      destroyApp(false);
	      notifyDestroyed();
	    }
	    else if (c == cmLogon)
	    {
	      try 
	      {
	    	  Thread t = new Thread(this);
	    	  t.start();
	      }
	      catch (Exception e)
	      {
	        db("connect " + e.toString());        
	      }
	    }
	  }

	  /*--------------------------------------------------
	  * Simple message to console for debug/errors
	  * When used with Exceptions we should handle the 
	  * error in a more appropriate manner.
	  *-------------------------------------------------*/
	  private void db(String str)
	  {
	    System.err.println("Msg: " + str);
	  }

	public void run() {
		 try {
			connect();
		} catch (IOException e) {
			e.printStackTrace();
			 db("connect " + e.toString());      
		}  
	}
	
	
}


  


服务器端的核心代码:
  

   
  package com.easymorse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public CookieServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	private static int[] clientIDs = {123,456,789,901,225,701};
	private static final Random rand = new Random();
	
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		System.out.println("--------------------------------------------------------------------");
		Cookie[] cookies = request.getCookies();
		System.out.println("cookies=====>"+cookies);
		
		if(cookies != null){
			Cookie theCookie = cookies[0];
			System.out.println("theCookie------------->"+theCookie);
			String id = theCookie.getValue();
			System.out.println("id=====>"+id);
			
			PrintWriter out = response.getWriter();
			out.print("Cookie passwed in was: " + id);
			out.close();
			
		}else{
			System.out.println("没有cookie");
			
			int random = rand.nextInt(100);
			
			Cookie cookie = new Cookie("ID",Integer.toString(random));
			response.addCookie(cookie);
			
		}
		
		
	}
	
	
	public String getServletInfo(){
		return "CookieTest";
	}
	

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doGet(request, response);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}

   


在J2ME中代码URL为我公司的URL,地址可能有变,希望大家在测试的时候,更改成自己服务器的地址就可以了。

   程序运行成功后的部分截图:


手机模拟器第一次运行时出现上图所示,服务器端的截图如下:

第一次手机访问服务器时,服务器产生一个随机数(100以内的整数,当然也可以采用uuid)返回客户端。

手机模拟器第二次访问和服务器的截图:




  
  • 大小: 14.4 KB
  • 大小: 914 Bytes
  • 大小: 1.3 KB
  • 大小: 966 Bytes
  • 大小: 2.4 KB
分享到:
评论

相关推荐

    midlet_servlet.rar_midlet-servlet

    我做的毕业设计,功能是实现手机和SQL的连接解压并配置相关的TOMCAT服务器,在WTK2.5下,可以进行仿真,同时可以生成 .jar 文件传到手机上用

    MIDlet与Servlet通信的研究与设计

    信息设备特征)就是一种特定类型的特征,它包含一些附加的库,为与GUI 和数据库的交互提供了Java API。此外,这些Java API 提 出了诸如应用生命周期和特定设备联网之类的问题。使用MIDP 下的API 创建的各种应用即为...

    MIDLet-Servlet通信

    JAVA移动实现与网络服务器端(servlet)通信实现

    MIDlet与J2EE结合开发移动商务应用

    MIDlet与J2EE结合开发移动商务应用.pdf

    MIDlet程序自签名方法

    这是由于该MIDlet程序未被CA授权,属于非受信MIDlet(Untrusted MIDlet)。而当非受信MIDlet访问系统敏感API时,出于对手机安全性的考虑,设备就需要显式地获得用户许可。 解决该问题的通常做法是购买权威认证机构...

    MIDlet通过蓝牙与电脑通信的案例

    MIDlet通过蓝牙与电脑通信的案例 MIDlet通过蓝牙与电脑通信的案例

    MIDlet控件实例项目(mvc)

    这个是Eclipse项目,MIDlet控件的例子,分成input, output 和midlet.有助于理解控件的使用和分层。

    J2ME入门教程.10(j2me与Servlet相互通讯)编写和配置Servlet服务端

    import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response )throws IOException, ...

    Midlet Signing

    详细介绍了midlet程序签名机制,包括三种信任域的不同、开发过程中使用的签名与产品签名的不同等内容。并基于MOTO手机开发平台给出示例。

    读取MIDlet的系统属性

    J2ME读取MIDlet的系统属性,用于判断J2ME获取的各个属性

    基于HTTP的网络编程

    基于HTTP的网络编程,过HTTP GET方法实现MIDlet与Servlet应用进行交互。

    基于网络的MIDlets简介

    • 一个网络MIDlet范例(以及相应的Java ™ servlet) 我们假设你熟悉Java编程,并具备MIDP编程的基础知识,例如你已经阅读过诺基亚论坛中的相关文章《MIDP编程简介》[MIDPPROG]。 通过这个简介以及网络MIDlet和...

    黑莓MIDlet开发指南

    黑莓MIDlet开发指南 BlackBerry MIDlet Development Guide V4.0 介绍如何使用黑莓JDE开发用于黑莓手机的标准MIDlet程序。 本文档版权属于RIM,仅用于学习交流,切勿用于商业用途。

    Midlet2.rar_midlet_simple

    this is simple example of j2me midlet by using lwuit library in which simple form is displayed

    Midlet.Pascal.v2.0

    使用pascal语言开发手机java游戏的工具.

    如何将MIDlet应用移植到BlackBerry

    进入BlackBerry 开发世界的一个直接方法就是将现有的MIDlet 移植到BlackBerry 平台上。将 MIDlet 移植到BlackBerry 上有不同的方法,从简单的程序转换到复杂的项目重写,可以适合 不同的开发人员和不同的项目。本文...

    BlackBerry 应用和MIDlet之间的交互

    对于很多没有BlackBerry 应用经验的开发者,或者对于很多现有的J2ME 的系统,如果以最小的代 价和BlackBerry 应用交互,或者和BlackBerry...个非常有用的能力:它允许一个MIDlet 套件和另一个MIDlet 套件共享记录存储。

    J2ME开发资料整理-在MIDlet中使用图标(附范例)

    我在一个项目开发中整理的资料,不知道有没有人发过。

    midlet java 浮点运算函数

    做midlet开发,如果需要用到乘幂运算,会用到这个函数。 文件名是float.java 里面包含了pow函数等midlet原本不具备的数学运算函数。

    RMS-MidLet例子

    RMS-MidLet例子,非常有助于理解RMS。而且是分层的。J2ME手机存储的程序,Eclipse项目。

Global site tag (gtag.js) - Google Analytics