Home J2me J2ME Cookies Example
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

J2ME Cookies Example

Advertisement
This Application is used to find the cookies value of the servlet. In this example we are creating a MIDlet ( CookieMIDlet ) for access the servlet.

J2ME Cookies Example

     

This Application is used to find the cookies value of the servlet. In this example we are creating a MIDlet ( CookieMIDlet ) for access the servlet. We are creating servlet (J2MEServletExample) to find the cookies value. We are mapping the servlet in the web.xml file. In this example we are trying to display the cookies value on the mobile window by accessing the servlet from MIDlet.

The Application is as follows:  

CookieMIDlet.java

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import javax.microedition.io.*;
import java.io.*;
  
public class CookieMIDlet extends MIDlet implements CommandListener{
  private Display display;
  private Form form;
  private Command exit, logon;
  private String cookie = null;
  private RecordStore rs = null;  
  static final String REC_STORE = "CookieMIDlet";
  private String url = "http://localhost:8080/J2MEServlet/J2MEServletExample";

  public void startApp(){
  display = Display.getDisplay(this);
  exit = new Command("Exit", Command.EXIT, 1);
  logon = new Command("Logon", Command.SCREEN, 2);
  form = new Form("");
  form.addCommand(exit);
  form.addCommand(logon);
  form.setCommandListener(this);
  openRecord(); 
  readCookie();
  display.setCurrent(form);
  }  
  
  public void pauseApp(){}

  public void destroyApp(boolean unconditional){
  closeRecord();
  notifyDestroyed();
  }

  public void openRecord(){
  try{
  rs = RecordStore.openRecordStore(REC_STORE, true);
  }catch(Exception e){}
  }

  public void closeRecord(){
  try{
  rs.closeRecordStore();
  }catch(Exception e){}
  }

  public void writeRecord(String str){
  byte[] rec = str.getBytes();
  try{
  rs.addRecord(rec, 0, rec.length);
  }catch(Exception e){}
  }

  public void readCookie(){
  try{
  byte[] recData = new byte[25]; 
  int len;

  if(rs.getNumRecords() > 0){
  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){}
  }

  private void httpConnect() throws IOException{
  InputStream is = null;
  ByteArrayOutputStream bos = null;
  HttpConnection con = null;  

  try{
  con = (HttpConnection) Connector.open(url);
  con.setRequestMethod(HttpConnection.GET);
  
  if(cookie != null){
  con.setRequestProperty("cookie", cookie);
  }
  System.out.println("Client cookie: " + cookie);  
  if(con.getResponseCode() == HttpConnection.HTTP_OK){
  String server_cookie = con.getHeaderField("set-cookie");  
  System.out.println("server cookie: " + server_cookie);
  if(server_cookie != null){
  writeRecord(server_cookie);
  cookie = server_cookie;
  form.append("First visit\n");  
  form.append("Client : " + cookie + "\n");
  }else{
  is = con.openInputStream();
  int length = (int) con.getLength();
  String str;
  if(length != -1){
  byte serverData[] = new byte[length];
  is.read(serverData);
  str = new String(serverData);
  }else{
  bos = new ByteArrayOutputStream(); 
  int ch;
  while((ch = is.read()) != -1){
  bos.write(ch);
  }
  str = new String(bos.toByteArray());
  }
  form.append("Last access:\n" + str + "\n"); 
  }
  }
  }finally{
  if(is != null){
  is.close();
  }
  if(bos != null){
  bos.close();
  }
  if(con != null){
  con.close();
  }
  }
  }

  public void commandAction(Command c, Displayable s){
  String label = c.getLabel();
  if(label.equals("Exit")){
  destroyApp(true);  
  }else if(label.equals("Logon")){
  try{
  httpConnect(); 
  }catch(Exception e){}
  }
  }
}

Download This Source Code

J2MEServletExample.java

import java.io.*;
import java.sql.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class J2MEServletExample extends HttpServlet{
  String url = "jdbc:mysql://localhost:3306/";
  String dbName = "test";
  String driverName = "com.mysql.jdbc.Driver";
  String userName = "root";
  String password = "root";
  Connection con = null;
  
  protected void doGet(HttpServletRequest req, HttpServletResponse res) 
  throws ServletException, IOException{
  Cookie[] cookies = req.getCookies();
  System.out.println("cookies "+cookies);
  res.setContentType("text/html");  
  PrintWriter out = res.getWriter();
  out.println("<html>");
  out.println("<head><title>J2ME Servlet</title></head>");
  out.println("<body>");
  out.println("<h1>J2ME Servlet</h1>");
  out.println("</body></html>");  
  
  if(cookies != null){
  Cookie theCookie = cookies[0];
  String id = theCookie.getValue();
  out.println("<b>The Cookies Value is:</b> " + id);
  out.print("<br>");
  out.println("And The Table Data is Display Here<br>");
  } else {
  int random = (int) Math.round(100 * Math.random());
  Cookie cookie = new Cookie("ID", Integer.toString(random));
  System.out.println("cookie "+cookie);
  res.addCookie(cookie);
  }

  try{
  Class.forName(driverName).newInstance(); 
  con = DriverManager.getConnection(url+dbName, userName, password);
  Statement stmt = con.createStatement();
  java.util.Date currentTime = new java.util.Date(); 
  SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
  String dateString = formatter.format(currentTime);
  String query = "UPDATE emp set lastAccess = '" + dateString + "' where id = 2";
  stmt.executeUpdate(query);

  ResultSet rs = stmt.executeQuery("Select * from emp"); 
  while(rs.next()){
  out.println(rs.getString(1) + " " + rs.getString(2) + " " + 
  rs.getString(3));
  out.println("<br>");
  }
  }catch (Exception e){
  System.out.println(e);
  }  
  out.close();
  }http://java.sun.com/xml/ns/j2ee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">


<display-name>Servlet 2.4 application</display-name>

<servlet>
<servlet-name>J2MEServletExample</servlet-name>
<servlet-class>J2MEServletExample</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>J2MEServletExample</servlet-name>
<url-pattern>/J2MEServletExample</url-pattern>
</servlet-mapping>

</web-app>

Download This Source Code

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 2, 2008

Ask Questions?    Discuss: J2ME Cookies Example   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com