Java Programing laungage

J2ME Projects

J2ME Project 1

adplus-dvertising
Create an application for active session in servlet
Previous Home Next

Introduction

In program, a Http request is made form Midlet to Java Servlet which run on Web Server ( Apache Tomcat ) through HTTP GET method to access doGet method of servlet in Midlet. In which a string is passing to servlet through Midlet class and get requested session Id form servlet, which display in Midlet client class.

Midlet Program


/*
 * Save as a sessionMidlet.java
 */
package r4r.Mobile.Application;

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

/**
 * @author R4R
 */
public class sessionMidlet extends MIDlet implements CommandListener {

    final Command CREATE = new Command("Create", Command.SCREEN, 1);
    final Command EXIT = new Command("Exit", Command.EXIT, 2);
    private Form form;
    private TextField T_name;

    public sessionMidlet() {
        // declaration field with initialization
        form = new Form("Creat Session");
        T_name = new TextField("Name", "", 10, TextField.PLAIN);
        form.append(T_name);
        form.addCommand(CREATE);
        form.addCommand(EXIT);
        form.setCommandListener(this);
    }

    public void startApp() {
        Display.getDisplay(this).setCurrent(form);
    }

    public void pauseApp() {
    }

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

    public void commandAction(Command c, Displayable d) {
        if (c == EXIT) {
            destroyApp(true);  // terminate application
        } else if (c == CREATE) {
            // Store value form TextField to String
            String name = T_name.getString().trim();
            // initialize new Class
            sessionClient client = new sessionClient(this, name);
            client.start();
        }
    }
}

/*
 * --------------------------------------------------
 * Class sessionClient handle Client side request 
 * or Receive server response.
 * --------------------------------------------------
 */
class sessionClient implements Runnable, CommandListener {

    //client can invoke servlet through SERVLET_URL 
    final String SERVLET_URL = "http://localhost:8084/MobileServlet/sessionServlet";
    final Command BACK = new Command("Back", Command.BACK, 1);
    final Command EXIT = new Command("Exit", Command.EXIT, 2);
    private sessionMidlet parent;
    private Display display;
    private TextBox tb;
    private String name;
    private HttpConnection hc = null;
    private OutputStream os = null;
    private InputStream is = null;
    StringBuffer sb = new StringBuffer();

    sessionClient(sessionMidlet aThis, String name) {
        this.parent = aThis;  // set field
        this.name = name;

        // declaration field with initialization
        display = Display.getDisplay(aThis);
        tb = new TextBox("Client Site Response...", null, 1024, 0);
        tb.addCommand(BACK);
        tb.addCommand(EXIT);
        tb.setCommandListener(this);
        display.setCurrent(tb);
    }

    void start() {
        // invoke new thread and begin in execution
        new Thread(this).start();
    }

    public void run() {
        try {
            //Open HTTP connection 
            hc = (HttpConnection) Connector.open(SERVLET_URL);
            // client access servlet GET method 
            hc.setRequestMethod(HttpConnection.GET);
            //Sets the general request property 
            hc.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.1");
            hc.setRequestProperty("CONTENT-TYPE", "application/x-www-form-encoded");

            //Open DataOutputStream and write data into Stream(in byte form)
            os = hc.openDataOutputStream();
            os.write((name).getBytes());
            os.flush();

            //Open DataInputStream for connection.
            is = hc.openDataInputStream();
            int ch;
            //Read the data form DataInputStream
            while ((ch = is.read()) != -1) {
                sb.append((char) ch);          //Convert Byte to character
                System.out.println((char) ch); //Display data on console
            }
            tb.setString(sb.toString());       // data append to textBox
        } catch (IOException ex) {
           Alert a = new Alert("SERVLET Server Error!",
   "Cannot connect to server. Ping to server and make sure it's in running state....",
	              null, AlertType.ERROR);
            a.setTimeout(Alert.FOREVER);
            display.setCurrent(a);
        } finally {
            // close all the Stream and connection
            try {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
                if (hc != null) {
                    hc.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public void commandAction(Command c, Displayable d) {
        if (c == BACK) {
            parent.startApp();
        } else if (c == EXIT) {
            parent.destroyApp(true);  // terminate application
        }
    }
}

servlet program


/*
 * Save as a sessionServlet.java
 */
package r4r.MobileServlet;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

/**
 *
 * @author R4R
 */
public class sessionServlet extends HttpServlet {

    // Private Field
    private String name = null;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // Set the response message's MIME type
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        // Reads line of text from a character-input stream
        BufferedReader br = request.getReader();
        name = br.readLine();

        //set the HttpSession associated with this request
        HttpSession session = request.getSession(true);

        if (name != null) {
            out.println("Hello Mr. " + name + ", 
			your session is active with session id " + session.getId());
        } else {
            out.println("Your session is active with session id " + session.getId());
        }
        out.close();      // close text-output stream 
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }
}


Output of the Program - Run application

Previous Home Next