Session management in Java ME
Article Metadata
The following MIDlet and Java Servlet implement session management using cookies. Upon the first request from the client to the servlet, the servlet will generate a unique client ID (simply a random number). This ID will be sent back to the MIDlet as a cookie:
HttpServletResponse res;
...
// Create new cookie and send ID in the header
Cookie cookie = new Cookie("ID", Integer.toString(random));
res.addCookie(cookie);
The MIDlet will store this value in the record store. All future requests from the MIDlet to the servlet will be accompanied by the client ID. When the servlet recognizes that the client (MIDlet) sent a cookie, it will simply return the value of the cookie.
Code Example
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import javax.microedition.io.*;
import java.io.*;
import java.util.Random;
public class CookieTest extends MIDlet implements CommandListener {
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://www.xxxxxxx.com/servlet/ CookieTestServlet";
private static final Random rand = new Random();
public CookieTest() {
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();
}
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());
}
}
public void writeRecord(String str) {
byte[] rec = str.getBytes();
try {
//adds a new record to the RecordStore
rs.addRecord(rec, 0, rec.length);
} catch (Exception e) {
db("write " + e.toString());
}
}
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);
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 the string sent from the
* 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(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 {
// Logon to the servlet
connect();
} catch (Exception e) {
db("connect " + e.toString());
}
}
}
private void db(String str) {
System.err.println("Msg: " + str);
}
}
/*--------------------------------------------------
* CookieTestServlet.java
*
* Use a cookie to identify clients
*
* www.CoreJ2ME.com
*-------------------------------------------------*/
package corej2me; // Required for mycgiserver.com
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.text.*;
public class CookieTestServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// Get cookie from the header
Cookie[] cookies = req.getCookies();
//-------------------------------------------
// If cookie passed in...
// return the value of the cookie
// to the cleint
//-------------------------------------------
if (cookies != null) {
// There will be only one cookie
Cookie theCookie = cookies[0];
String id = theCookie.getValue();
// Send back the last access date to the client
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
out.print("Cookie passed in was: " + id);
out.close();
} else // No Cookie
{
//-------------------------------------------
// Generate a unique client ID, which is
// nothing more than a random number
//-------------------------------------------
// Random ID
int random = rand.nextInt(100);
// Create new cookie and send ID in the header
Cookie cookie = new Cookie("ID", Integer.toString(random));
res.addCookie(cookie);
}
}
/*--------------------------------------------------
* Information about servlet
*-------------------------------------------------*/
public String getServletInfo() {
return "CookieTest";
}
}


26 Sep
2009
Session management is the most important part of any secure application. MIDlet does this using cookies. When MIDlet first request the servlet, that is server side script that handles incoming request and send response as HTML. So first time Servlet send unique ID to the MIDlet.Whenever MIDlet send second request to the same server,serer look for the Cookies and if found then treat MIDlet as active one and provide resources with minimum time duration.
MIDlet store unique Id in record store.The Code example given in this article is very useful to make secure MIDlet transaction over server and that includes multiple users for same service. Using this article people get to know about session management at server side how to write and store cookie is given with very little but effective code example.
29 Sep
2009
This article demonstrates how we can perform session management between a Java ME midlet and a servlet through the use of cookies. A code example is provided, showing how the first time a midlet makes a request to a servlet, it generates a cookie consisting of a random number. All future requests by the midlet are accompanied by that cookie, which serves to identify the midlet. The code example shows both the midlet code and the servlet code.
This article covers a useful topic. If a midlet is to communicate with a servlet, it is important that the user of the midlet should only have to login once per session, but that this should not compromise security or usability. The use of cookies helps to address this issue. Cookies are wisely used to get around the problems of stateless HTTP, so it is not surprising to see their use in midlet to servlet communication. The use of cookies can help to identify users, and to keep track of their previous actions, and so introduce some sort of state memory in the stateless environment of HTTP. The code example in this case is nicely written. Perhaps the best thing about this article is that the code is heavily commented. Comments are essential to help readers understand the code, and in this article they are used to very good effect.