cookie在web应用程序中被广泛采用,维护浏览器和服务器之间的状态。遗憾的是这一特性在java me平台中并没有得到支持。因此,要想维持客户端和服务器端的状态则必须使用url重写的方式。url重写操作起来比较麻烦,所以研究一下cookie的原理并在java me平台上实现cookie是不错的尝试。
首先,我们来看一下cookie的原理。当服务器需要和浏览器维持某一状态的时候,例如需要记录用户的购物车中已经购买的商品。这时候服务器可以新建一个cookie并把它写入到响应中,浏览器从响应中接收到cookie并保存起来。当浏览器再次向服务器发送请求的时候,浏览器会根据域(domain)和路径(path)检查是否有匹配的cookie,如果有则把cookie以“名称=值”的形式发送给服务器,服务器从请求中解析出cookie就知道用户的状态了。那么,浏览器根据什么规则来决定向服务器发送cookie呢,首先要匹配domain,如果cookie的域属性是.google.com,那么请求指向j2medev.com的时候,cookie就不会被发送。如果域匹配的条件满足,则判断path是否匹配,如果cookie的path属性是请求的uri的父目录的话,那么cookie就会被发送给服务器。cookie是有存活周期的,到期的cookie会被浏览器自动清除。如果服务器创建cookie的时候不设置生命周期,那么在会话结束后浏览器就会删除cookie。如果不为cookie指定path属性,那么默认就是这次请求的路径。
cookie在很多web应用程序中都有应用,比如记住密码,购物车等。在开发midlet的时候,你也可以让你的应用程序支持cookie,这样维持客户端与服务器端的状态将变得简单,为你集中精力解决其他业务方法奠定了基础。既然已经知道了cookie的工作原理,那么就应该考虑一下在java me平台如何实现cookie,这个想法是否可行。从下面三个方面进行分析。
第一:获得cookie
当服务器端的响应到来的时候,我们应该能够读取cookie。如果服务器向客户端写入cookie的时候,响应中的http头“set-cookie”中会包含一个字符串,代表了cookie的信息。幸运的是我们是用httpconnection.getheaderfiled("set-cookie")方法即可获得cookie,但是需要注意这里只是读取了一个cookie,如果响应中包含了多个cookie,那么你需要循环读取。类似于下面的代码
string scookie = null;
string key = null;
int i = 0;
//如果key存在,则查询header的key,如果key等于set_cookie,则存储
while((key = connection.getheaderfieldkey(i))!=null){
if(key.equals(set_cookie)||key.equals(sessionid)){
scookie = connection.getheaderfield(i);
savecookie(scookie,url);
}
i++;
}
|
上面的代码把header是set-cookie和sesssionid的cookie内容读取下来。
第二:保存cookie
已经获得了cookie之后,就需要把cookie存储下来,存储分为两个部分,首先需要解析cookie,我们定义一个java bean来代表cookie.
package com.j2medev.lomol.model;
import com.j2medev.lomol.util.stringutil;
import java.io.datainputstream;
import java.io.dataoutputstream;
import java.io.ioexception;
import java.util.date;
/**
* a cookie stored on the mobile device,
* cookie is used to maintain the states between client and server
* @author mingjava
* @version 0.1 05/06/2006
*/
public class cookie {
private string path = "";
private string name = "";
private string value = "";
private long expire = session_cookie;
public static long session_cookie = 0;
//session cookie,only valid this session
public cookie() {
}
public string getpath() {
return path;
}
public void setpath(string path) {
this.path = path;
}
public string getname() {
return name;
}
public void setname(string name) {
this.name = name;
}
public string getvalue() {
return value;
}
public void setvalue(string value) {
this.value = value;
}
public void serialize(dataoutputstream dos) throws ioexception{
dos.writeutf(name);
dos.writeutf(value);
dos.writeutf(path);
dos.writelong(expire);
}
public static cookie deserialize(datainputstream dis) throws ioexception{
cookie cookie = new cookie();
cookie.name = dis.readutf();
cookie.value = dis.readutf();
cookie.path = dis.readutf();
cookie.expire = dis.readlong();
return cookie;
}
public long getexpire() {
return expire;
}
public void setexpire(long expire) {
this.expire = expire;
}
//for debug
public string tostring(){
return name+"="+value+";expires="+new date(expire).tostring()+";path="+path;
}
public boolean isexpired(long now){
return expire-now<0;
}
public boolean isexpired(){
return expire-(new date().gettime())<0;
}
public static cookie parsecookie(string s,string uri){
cookie cookie = new cookie();
stringutil su = new stringutil(s,";");
while(su.hasmoretokens()){
string str = su.nexttoken().trim();
int i = str.indexof("=");
if(i == -1){
//secure do nothing
continue;
}else{
string name = str.substring(0,i);
string value = str.substring(i+1,str.length());
if("path".equals(name)){
cookie.setpath(value);
}else if("expires".equals(name)){
cookie.setexpire(stringutil.getdata(value));
}else if("domain".equals(name)){
//do nothing
}else{
cookie.setname(name);
cookie.setvalue(value);
}
}
if(cookie.getpath().equals(""))
cookie.setpath(uri);
}
return cookie;
}
public boolean equals(object obj){
if(obj instanceof cookie){
cookie o = (cookie)obj;
if(o.getname().equals(name) && o.getpath().equals(path))
return true;
}
return false;
}
public int hashcode(){
int result = 17;
result = result * 37 + path.hashcode();
result = result * 37 + name.hashcode();
return result;
}
}
|
提供了一个parsecookie方法来解析cookie,具体的原理就不再介绍了。然后需要把这个cookie对象存储到rms中。cookie并不大,所以不会占用太多的空间,在rms中存储非常合适。注意对于会话期间的cookie没有必要存储在rms中,因为会话结束后就失效了,不如在内存中声明一个map来存储会话类型的cookie。
第三:发送cookie
发送cookie也是需要两个步骤,首先检索rms和内存看是否有满足条件的cookie,如果有读取出来。然后通过下面的方法向服务器端发送
//检查是否有cookie需要发送给服务器端
string _cookie = collectcookie(url);
if(_cookie != null)
connection.setrequestproperty(cookie,_cookie);
|
如果能够顺利解决上面的三个步骤,基本可以实现cookie在java me平台的应用。