Java Programing laungage

J2ME Projects

J2ME Project 1

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

Midlet Program


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

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


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

    final Command SUBMIT = new Command("Submit", Command.OK, 1);
    final Command EXIT = new Command("Exit", Command.EXIT, 2);
    private Form form;
    private TextField T_fname, T_lname, T_age, T_number;

    public servletConnectionMidlet1() {
        // declaration field with initialization
        form = new Form("Servlet Connection...");
        T_fname = new TextField("Firstname", "", 10, TextField.PLAIN);
        T_lname = new TextField("Lastname", "", 10, TextField.PLAIN);
        T_number = new TextField("Number", "", 12, TextField.PHONENUMBER);
        T_age = new TextField("Age", "", 2, TextField.NUMERIC);
        form.append(T_fname);
        form.append(T_lname);
        form.append(T_number);
        form.append(T_age);
        form.addCommand(SUBMIT);
        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 == SUBMIT) {
            // Store value form TextField to String 
            String fname = T_fname.getString().trim();
            String lname = T_lname.getString().trim();
            String age = T_age.getString().trim();
            String number = T_number.getString().trim();
            // initialize new Class
            ConnectionClient client = new ConnectionClient
				(this, fname, lname, number, age);
            client.start();
        }
    }
}
/*
 * --------------------------------------------------
 * Class ConnectionClient handle Client side request 
 * or Receive server response.
 * --------------------------------------------------
 */
class ConnectionClient implements Runnable, CommandListener {

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

    ConnectionClient(servletConnectionMidlet1 aThis,
		String fname, String lname, String number, String age) {
        this.parent = aThis;  // set field
        this.fname = fname;
        this.lname = lname;
        this.number = number;
        this.age = age;

        // 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);
            //Sets the general request property 
            hc.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
            hc.setRequestProperty("CONTENT-TYPE", "application/x-www-form-encoded");

            //Open DataOutputStream and write data into Stream(in byte form)
            String data = fname + "?" + lname + "?" + number + "?" + age + "?";
            os = hc.openDataOutputStream();
            os.write((data).getBytes());
            os.flush();

            //Open dataInputStream for a 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!",
	"Cannot connect to server. Ping the server to 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 e) {
            }
        }
    }

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

servlet program


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

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

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

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

    @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.
        String fname = s.substring(0, s.indexOf("?"));

        int start = s.indexOf("?") + 1;
        int end = s.indexOf('?', start + 1);
        String lname = s.substring(start, end);

        start = s.indexOf('?', start + 1);
        end = s.indexOf('?', start + 1);
        String number = s.substring(start + 1, end);

        start = s.indexOf('?', start + 1);
        end = s.indexOf('?', start + 1);
        String age = s.substring(start + 1, end);

        // send response to the client
        out.println(" Firstname =" + fname +
	"\n Lastname =" + lname + "\n Number =" + number + "\n Age =" + age);
        out.close();    // close text-output stream 
    }
}


Output of Program - Run application

Previous Home Next