Core Java| JSP| Servlets| XML| EJB| JEE5| Web Services| J2ME| Glossary| Questions?

 

 

 

 

 

 

 

 

 

 

 

 

 

Search Tutorials

Latest Questions
Comments
 
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.

 

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 = (HttpConnectionConnector.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 = (intcon.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 = (intMath.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();
  }
}

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="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

                         

» View all related tutorials
Related Tags: c string image text io colors user color screen display click source cli message set create define show tex example

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Training Courses
Tell A Friend
Your Friend Name
Software Solutions
Least Viewed
Most Rated
Recently Viewed
Search Tutorials

 

 
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Flex Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.