How to implement cookies on the Javame platform

Source: Internet
Author: User
Tags send cookies to domain

Cookies are widely used in Web applications to maintain state between browsers and servers. Unfortunately, this feature has not been supported in the Java ME platform. Therefore, to maintain the state of the client and server side, you must use the URL rewrite method. URL rewriting is cumbersome to do, 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 to maintain a certain state with the browser, for example, it needs to record the items that have been purchased in the user's shopping cart. 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 according to domain (domain) and path (path), and if so, sends the cookie as a "name = value" to the server, and the server resolves the cookie from the request to know the user's status. So, according to what rules the browser decides to send a cookie to the server, first to match domain, if the domain attribute of the cookie is. Google.com, the cookie is not sent when the request points to j2medev.com. If the domain matching criteria are met, the path is determined to match, and if the path property of the cookie is the parent directory of the requested URI, then the cookie is sent to the server. Cookies are live cycles, and expired cookies are automatically erased by the browser. If the server does not set the lifecycle when creating a cookie, the browser will delete the cookie after the session ends. If you do not specify the path property 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 allow your application to support cookies, which will make it easier to maintain the state of the client and server side, laying the groundwork for you to focus on other business methods. Now that you know how cookies work, you should consider the idea of how to implement cookies on the Java ME platform. I will analyze from the following three aspects.

First: Get a cookie

When the server-side response arrives, we should be able to read the cookie. If the server writes a cookie to the client, the HTTP header "Set-cookie" in the response contains a string that represents the cookie's information. Fortunately, we use the httpconnection.getheaderfiled ("Set-cookie") method to obtain cookies, but note that this is just a cookie, and if the response contains more than one cookie, Then you need to loop the reading. Code similar to the following

String SCookie = null;

String key = null;

int i = 0;

If key exists, the key of the header is queried, and if key equals Set_cookie, the storage

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 header from the cookie content of Set-cookie and Sesssionid.

Second: Save cookies

Once a cookie has been obtained, the cookie needs to be stored and stored in two parts, first 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 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 * Notoginseng + path.hashcode ();

result = result * Notoginseng + name.hashcode ();

return result;

}

}

Provides a Parsecookie method to parse the cookie, the specific principle is no longer introduced. You then need to store this cookie object in RMS. Cookies are not very large, so they do not take up too much space and are suitable for storage in RMS. Note It is not necessary for a cookie to be stored in RMS for the duration of the session because it is invalidated after the session has ended, rather than declaring a map in memory to store the session-type cookie.

Third: Send cookies

Sending a cookie is also a two-step process that first retrieves RMS and memory to see if there is a cookie that satisfies the condition if it is read out. Then send it to the server using the following method

Check if there is a cookie that needs 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, basically can implement the cookie in the Java ME platform application. In the book Java Me core technology and best practices, the HTTPME has written a framework for networking, which includes the implementation of cookies on the Java ME platform for your reference.

Data source http://www.91goodschool.com/infolist/002301/

How to implement cookies on the Javame platform

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.