Midlet与Servlet传递Cookie

Cookie在Java ME平台中没有得到支持,因此要想维持客户端和服务器端的状态则必须要使用URL重写的方式.
 
   Cookie的工作原理如图:
  
Midlet与Servlet传递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)返回客户端。

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




  

你可能感兴趣的:(thread,servlet,浏览器,Access,UP)