Java Programing laungage

J2ME Projects

J2ME Project 1

adplus-dvertising
Create an application to ping to 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 POST method to access doPost method ofservlet in Midlet.

Midlet Program


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

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

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

    final Command PING = new Command("Ping", Command.OK, 1);
    final Command EXIT = new Command("Exit", Command.EXIT, 2);
    private Form form;

    public pingServletMidlet() {
        // declaration field with initialization
        form = new Form("Ping to Servlet");
        form.addCommand(PING);
        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 == PING) {
            // initialize new Class
            PingServletClient client = new PingServletClient(this);
            client.start();
        }
    }
}

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

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

    PingServletClient(pingServletMidlet 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(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.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 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 data stream and connection
            try {
                if (is != null) {
                    is.close();
                }
                if (hc != null) {
                    hc.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

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

servlet program


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

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

/**
 *
 * @author R4R
 */
public class pingServlet 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();

        // send response to the client
        out.println("Servlet Ping Successfully.." + "\n");
        out.print(new Date());   // set the current Data & Time
        out.close();             // close text-output stream 
    }
}


output

If your Apache Tomcat server is not in running State the emulator device in through a error Massage which display on screen.

Previous Home Next