Application and implementation of cookie technology in Java ME platform

Source: Internet
Author: User
Tags parent directory send cookies tostring

Cookies are widely used in Web applications to maintain the state between browsers and servers. Unfortunately, this feature is not supported in the Java ME platform. Therefore, to maintain the state of the client and server side, you must use a URL rewrite method. URL rewriting is a hassle to work with, so it's a good idea to study the cookie principle and implement cookies on the Java ME platform. First, let's look at the principle of cookies. When the server needs and browsers to maintain a certain state, such as the need to record the user's shopping cart has been purchased goods. At this point the server can create a new cookie and write it to the response, and the browser receives the cookie from the response and saves it. When the browser sends a request to the server again, the browser checks to see if there is a matching cookie based on domain and path (path), and if there is a cookie sent to the server in the form of "name = value", the server will know the user's status by parsing the cookie from the request. So, what rules does the browser decide to send cookies to the server, first to match domain, and if the domain property of the cookie is. google.com, the cookie will not be sent when the request points to j2medev.com. If the criteria for domain matching are met, the path is judged to match, and if the path attribute of the cookie is the parent directory of the requested URI, the cookie is sent to the server. Cookies have a lifetime, and the expired cookies are automatically purged by the browser. If the server creates a cookie without setting the lifecycle, the browser deletes the cookie at the end of the session. If you do not specify the path attribute for a cookie, the default is the path to this request.

Cookies are used in many Web applications, such as remembering passwords, shopping carts, and so on. When developing MIDlet, you can also have your application support cookies so that maintaining the state of the client and server side will be simpler, laying the groundwork for you to focus on other business methods. Now that you know how cookies work, consider whether the idea of how to implement cookies on the Java ME platform is feasible. I will analyze from the following three aspects.

First: Get Cookies

When the server-side response arrives, we should be able to read cookies. If the server writes cookies to the client, the HTTP header "Set-cookie" in the response contains a string that represents the cookie's information. Luckily we were able to get cookies using the httpconnection.getheaderfiled ("Set-cookie") method, but we need to be aware that we read only a cookie here, and if the response contains more than one cookie, Then you need to loop the reading. Similar to the following code

String SCookie = null;
String key = null;
int i = 0;
If the key exists, the key of the header is queried and if key equals Set_cookie, the store
while ((key = Connection.getheaderfieldkey (i))!=null) {
if (key.equals (Set_cookie) | | Key.equals (SESSIONID)) {
SCookie = Connection.getheaderfield (i);
Savecookie (Scookie,url);
}
i++;
}

The code above reads the contents of the header as a set-cookie and Sesssionid cookie.

Second: Save cookies

Once you've got the cookie, you need to store the cookie, store it in two parts, first need to parse the cookie, and we define a Java bean to represent the 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, cookies are used to maintain the states 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 () + ";p ath=" +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)) {
Doing 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 * Panax Notoginseng + path.hashcode ();
result = result * Panax Notoginseng + name.hashcode ();
return result;
}
}
Provides a Parsecookie method to parse cookies, and the exact principle is no longer introduced. You then need to store this cookie object in the RMS. Cookies are not large enough to take up too much space and are very suitable for storage in RMS. Note It is not necessary for cookies to be stored in RMS for the duration of the session, because the session ends and it becomes invalid to declare a map in memory to store the session-type cookie.

Third: Send cookies

Sending cookies also takes two steps, first retrieving RMS and memory to see if there are any cookies that meet the criteria if any are read out. Then send it to the server by using the following method

Check if any cookies need to be sent to the server side
String _cookie = Collectcookie (URL);
if (_cookie!= null)
Connection.setrequestproperty (Cookie,_cookie);

If you can successfully solve the above three steps, the basic cookies can be implemented in the Java ME platform application. In the Java Me core technology and best practices book, I wrote a HTTPME networking framework, including cookies in the Java ME platform for your reference.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.