Cookies are widely used in web applications to maintain the status between browsers and servers. Unfortunately, this feature is not supported on the Java me platform. Therefore, to maintain the status of the client and server, you must use URL rewriting. It is troublesome to rewrite the URL, so it is a good attempt to study the principle of cookie and implement cookie on the Java me platform.
First, let's take a look at the principles of cookies. When the server needs to maintain a certain state with the browser, for example, you need to record the purchased items in the user's shopping cart. In this case, the server can create a new cookie and write it into the response. The browser receives the cookie from the response and saves it. When the browser sends a request to the server again, the browser checks whether a matching cookie exists based on the domain and path, if yes, the cookie is sent to the server in the form of "name = value", and the server parses the cookie from the request to know the user's status. Therefore, the browser determines based on what rules to send a cookie to the server. First, it must match the domain. If the Cookie's domain attribute is .google.com, the cookie will not be sent when the request points to j2medev.com. If the domain match condition is met, the system checks whether the path matches. If the path attribute of the cookie is the parent directory of the requested URI, the cookie is sent to the server. The cookie has a life cycle. Expired cookies are automatically cleared by the browser. If the server does not set the lifecycle when creating a cookie, the browser deletes the cookie after the session ends. If the path attribute is not specified for the cookie, The Request Path is used by default.
Cookies are used in many web applications, such as remembering passwords and shopping carts. When developing a MIDlet, you can also enable your application to support cookies. Maintaining the status of the client and server becomes simple and lays the foundation for you to concentrate on other business methods. Now that we know how cookies work, we should consider how to implement cookies on the Java me platform. Is this idea feasible. I will analyze the following three aspects.
First, obtain the cookie.
When the server responds, we should be able to read cookies. If the server writes a cookie to the client, the HTTP header "Set-cookie" in the response will contain a string representing the cookie information. Fortunately, we use httpconnection. the getheaderfiled ("Set-cookie") method can obtain the cookie, but note that only one cookie is read here. If the response contains multiple cookies, you need to read them cyclically. Similar to the following code
Java mobile network [www.cnjm.net] string scookie = NULL;
String key = NULL;
Int I = 0;
Java mobile network [www.cnjm.net] // if the key exists, the header key is queried. If the key is equal to set_cookie, it is stored
While (Key = connection. getheaderfieldkey (I ))! = NULL ){
If (key. Equals (set_cookie) | key. Equals (sessionid )){
Scookie = connection. getheaderfield (I );
Savecookie (scookie, URL );
}
I ++;
}
The above Code reads the cookie content whose header is set-Cookie and sesssionid.
Second, save the cookie.
After obtaining the cookie, you need to store the cookie. The storage is divided into two parts. First, you need to parse the cookie. We define a Java Bean to represent the cookie.
Package com. j2medev. lomol. model;
JAVA mobile network [www.cnjm.net]
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 = "";
JAVA mobile network [www.cnjm.net] 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 (){
JAVA mobile network [www.cnjm.net]}
JAVA mobile network [www.cnjm.net]
Public String getpath (){
Return path;
}
Java mobile network [www.cnjm.net] 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;
Java mobile network [www.cnjm.net]}
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 );
}
Java mobile network [www.cnjm.net]
Public static cookie deserialize (datainputstream dis) throws ioexception {
Cookie = new cookie ();
Cookie. Name = dis. readutf ();
Cookie. value = dis. readutf ();
Cookie. Path = dis. readutf ();
Cookie. expire = dis. readlong ();
Return cookie;
}
Java mobile network [www.cnjm.net] public long getexpire (){
Return expire;
Java mobile network [www.cnjm.net]}
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 = new cookie ();
Stringutil su = new stringutil (S ,";");
While (SU. hasmoretokens ()){
String STR = Su. nexttoken (). Trim ();
Java mobile network [www.cnjm.net] 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 );
Java mobile network [www.cnjm.net]}
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;
}
Java mobile network [www.cnjm.net]}
A parsecookie method is provided to parse the cookie. The specific principle is not described. Then you need to store the cookie object in RMS. The cookie is not large, so it does not occupy too much space. It is suitable for storing in RMS. Note that there is no need to store cookies during a session in RMS because the session becomes invalid after the session ends. It is better to declare a map in the memory to store session cookies.