Java Programing laungage

J2ME Projects

J2ME Project 1

adplus-dvertising
Create an application for access doGet and doPost method of 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 and POST method to access HttpServlet of in Midlet. In which a string is passing to servlet through POST method through Midlet class and get requested String through GET method form servlet, which further display in Midlet client class.

Midlet Program


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

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

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

    final Command GET = new Command("Get", Command.OK, 1);
    final Command POST = new Command("Post", Command.OK, 1);
    final Command BACK = new Command("Back", Command.BACK, 2);
    private Display display;
    private List mlist;
    private TextField T_fname, T_lname;

    public doGetdoPostMidlet() {
        // declaration field with initialization
        display = Display.getDisplay(this);
        mlist = new List("Account Information", List.IMPLICIT,
			new String[]{"Info Post", "Info Get", "Quit"}, null);
        mlist.setCommandListener(this);
    }

    public void startApp() {
        display.setCurrent(mlist);
    }

    public void pauseApp() {
    }

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

    public void commandAction(Command c, Displayable d) {
        if (c == BACK) {
            startApp();
        } else if (c == GET) {
            // initialize new Class
            servletDoGetClient client = new servletDoGetClient(this);
            client.start();
        } else if (c == POST) {
            // Store value form TextField to String 
            String fname = T_fname.getString().trim();
            String lname = T_lname.getString().trim();
            // initialize new Class
            servletDoPostClient client = new servletDoPostClient(this, fname, lname);
            client.start();
        } else {
            //Display the selected String form the LIST
            List index = (List) display.getCurrent();
            switch (index.getSelectedIndex()) {
                case 0:
                    infoPostForm();  // invoke infoPostForm method
                    break;
                case 1:
                    infoGetForm();  // invoke infoGetForm method
                    break;
                case 2:
                    destroyApp(true); // terminate application
                    break;
            }
        }
    }

    private void infoGetForm() {
        Form form = new Form("Servlet Information: GET");
        form.addCommand(GET);
        form.addCommand(BACK);
        form.setCommandListener(this);
        display.setCurrent(form);
    }

    private void infoPostForm() {
        Form form = new Form("Servlet Information: POST");
        T_fname = new TextField("Firstname", "", 10, TextField.PLAIN);
        T_lname = new TextField("Lastname", "", 10, TextField.PLAIN);
        form.append(T_fname);
        form.append(T_lname);
        form.addCommand(POST);
        form.addCommand(BACK);
        form.setCommandListener(this);
        display.setCurrent(form);
    }
}

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

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

    servletDoGetClient(doGetdoPostMidlet aThis) {
        this.parent = aThis;  // set field

        // declaration field with initialization
        display = Display.getDisplay(aThis);
        tb = new TextBox("Client Site Response....", null, 1024, TextField.ANY);
        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);
            hc.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.1");
            hc.setRequestProperty("CONTENT-TYPE", "application/x-www-form-encoded");

            //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 into 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!", 
				"Can't connect to server, Ping to server and
			make sure it's in running stage...",
                    null, AlertType.ALARM);
            a.setTimeout(Alert.FOREVER);
            display.setCurrent(a, tb);
        } finally {
            //Close all the Stream and Connection
            try {
                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
        }
    }
}

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

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

    servletDoPostClient(doGetdoPostMidlet aThis, String fname, String lname) {
        this.parent = aThis;    // set field
        this.fname = fname;
        this.lname = lname;

        // declaration field with initialization
        display = Display.getDisplay(aThis);
        tb = new TextBox("Client Site Response...", null, 1024, TextField.ANY);
        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 POST method 
            hc.setRequestMethod(HttpConnection.POST);
            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)
            String data = fname + "?" + lname;
            os = hc.openDataOutputStream();
            os.write((data).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 into 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!",
				"Can't connect to server, Ping to server 
			and make sure it's in running stage...",
				      null, AlertType.ALARM);
            a.setTimeout(Alert.FOREVER);
            display.setCurrent(a, tb);
        } finally {
             //Close all the Stream and Connection
            try {
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.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 doGetdoPostServlet.java
 */
package r4r.MobileServlet;

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

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

    //Private Field
    private String fname = null, lname = 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();

        if (fname == null && lname == null) {
            out.println("Since no value post in 
			doPost method, hence value retrive form doPost is -"
                    + "\n Firstname = " + fname + "\n Lastname =" + lname);
        } else {
            out.println("Values GET successfully
			form doPost method as - \n Firstname = " + fname + " \n Lastname = " + lname);
        }
        out.close();     // close text-output stream 
    }

    @Override
    protected void doPost(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();
        String s = br.readLine();

        // Get a Specific String value from line of text.
        fname = s.substring(0, s.indexOf("?"));
        lname = s.substring(s.indexOf("?") + 1);

        if (fname == null && lname == null) {
            out.println("As the field is blank so no vlaue post in doPost method");
        } else {
            out.println("Values POST successfully as 
			\n Firstname = " + fname + "\n Lastname = " + lname);
        }
        out.close();    // close text-output stream 
    }
}

output
Previous Home Next