Java Programing laungage

J2ME Projects

J2ME Project 1

adplus-dvertising
Create an application for access database through 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 store into database form servlet, similarly, a requested String get form database and display in Midlet client class.

Midlet Program


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

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

/**
 * @author R4R
 */
public class communicateMidlet 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_user, T_pass, T_balance;

    public communicateMidlet() {
        // declaration field with initialization
        display = Display.getDisplay(this);
        mlist = new List("Account Information",
			List.IMPLICIT, new String[]{"Info Get", "Info Post", "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) {
            // Store value form TextField to String 
            String user = T_user.getString().trim();
            String pass = T_pass.getString().trim();
            // User can't allow to leave any TextField blank
            if (!user.equals("") && !pass.equals("")) {
                // initialize new Class
                doGetClient client = new doGetClient(this, user, pass);
                client.start();
            } else {
    Alert a = new Alert("Blank Field Error", "Please Don'tleave any field empty!",
		null, AlertType.ALARM);
                a.setTimeout(1000);
                display.setCurrent(a, d);
            }
        } else if (c == POST) {
            // Store value form TextField to String 
            String user = T_user.getString().trim();
            String pass = T_pass.getString().trim();
            String balance = T_balance.getString().trim();
            // User can't allow to leave any TextField blank
            if (!user.equals("") && !pass.equals("") && !balance.equals("")) {
                // initialize new Class
                doPostClient client = new doPostClient(this, user, pass, balance);
                client.start();
            } else {
                Alert a = new Alert("Blank Field Error", "Please Don't leave any field empty!",
					null, AlertType.ALARM);
                a.setTimeout(1000);
                display.setCurrent(a, d);
            }
        } else {
            //Display the selected String form the LIST
            List index = (List) display.getCurrent();
            switch (index.getSelectedIndex()) {
                case 0:
                    infoGetForm();
                    break;
                case 1:
                    infoPostForm();
                    break;
                case 2:
                    destroyApp(true);
                    break;
            }

        }
    }

    private void infoGetForm() {
        Form form = new Form("Account Information: GET");
        T_user = new TextField("Username", "", 10, TextField.PLAIN);
        T_pass = new TextField("Password", "", 10, TextField.PASSWORD);
        form.append(T_user);
        form.append(T_pass);
        form.addCommand(GET);
        form.addCommand(BACK);
        form.setCommandListener(this);
        display.setCurrent(form);
    }

    private void infoPostForm() {
        Form form = new Form("Account Information: Post");
        T_user = new TextField("Username", "", 10, TextField.PLAIN);
        T_pass = new TextField("Password", "", 10, TextField.PASSWORD);
        T_balance = new TextField("Balance $", "", 10, TextField.NUMERIC);
        form.append(T_user);
        form.append(T_pass);
        form.append(T_balance);
        form.addCommand(POST);
        form.addCommand(BACK);
        form.setCommandListener(this);
        display.setCurrent(form);
    }
}

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

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

    doGetClient(communicateMidlet aThis, String user, String pass) {
        this.parent = aThis;  //set field
        this.user = user;
        this.pass = pass;

        // 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 DataOutputStream and write data into Stream(in byte form)
            String data = user + "?" + pass;
            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());
        } 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 || c == Alert.DISMISS_COMMAND) {
            parent.destroyApp(true);   //terminate application
        }
    }
}


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

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

    doPostClient(communicateMidlet aThis, String user, String pass, String balance) {
        this.parent = aThis;  // set field
        this.user = user;
        this.pass = pass;
        this.balance = balance;

        // 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 = user + "?" + pass + "?" + balance + "?";
            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());
        } 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 {
            try {
                //Close all the Stream and Connection
                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 || c == Alert.DISMISS_COMMAND) {
            parent.destroyApp(true);     // terminate application
        }
    }
}

Servlet Program


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

import java.io.*;
import java.sql.*;
import java.util.logging.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

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

    // Private Field
    private Connection con = 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();
        String s = br.readLine();

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

        //store value form getAccountInfo() method into String
        String balance = getAccountInfo(user, pass);
        if (balance == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
				"Unable to get Balance information, try again");
            return;
        } else {
            // send response to the client
            out.println("Username " + user + "\n Password " + pass + "\n Balance" + balance);
            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.
        String user = s.substring(0, s.indexOf("?"));

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

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

        //store value form getAccountInfo() method into String
        String accountStatus = postAccountInfo(user, pass, balance);
        if (accountStatus == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
				"Unable to store Account inforamtion");
            return;
        } else {
            // send response to the client
            out.println("Data Successfully store into DataBase" + 
				" \n Username " + user + "\n Password " + pass + "\n Balance" + balance);
            out.close();    // close text-output stream 
        }
    }

    @Override
    public String getServletInfo() {
        return "Example of doGet and doPost in Servlet";
    }

    /*
     * --------------------------------------------------------------
     * Method getAccountInfo handle to get information about
     * Specific data form MYSQL database 
     * --------------------------------------------------------------
     */
    private String getAccountInfo(String user, String pass) {
        String sql = "SELECT BALANCE FROM R4R.MOBILE WHERE USERNAME= '" 
			+ user + "' AND PASSWORD='" + pass + "'";
        try {
            // open class and load the connection Driver
            Class.forName("com.mysql.jdbc.Driver");
            // Open MYSQL Database connection 
            con = DriverManager.getConnection("jdbc:mysql:///r4r", "root", "sachin");
            if (!con.isClosed()) {
                // Get the information about specific data form database table
                Statement smt = (Statement) con.createStatement();
                ResultSet rs = smt.executeQuery(sql);
                if (rs.next()) {
                    return rs.getString(1);
                } else {
                    return null;
                }
            } else {
                return "Can't open MYSQL DataBase, try Later";
            }
        } catch (Exception ex) {
            Logger.getLogger(communicateServlet.class.getName())
				.log(Level.SEVERE, "An Exception occurred due processing request", ex);
            return ex.toString();
        } finally {
            // close Database connection
            try {
                if (con != null) {
                    con.close();
                }
            } catch (SQLException ex) {
                Logger.getLogger(communicateServlet.class.getName())
					.log(Level.SEVERE, "An Exception occurred due processing request", ex);
            }
        }
    }

    /*
     * --------------------------------------------------------------
     * Method postAccountInfo handle to post information about
     * Specific data into MYSQL database 
     * --------------------------------------------------------------
     */
    private String postAccountInfo(String user, String pass, String balance) {

        String sql = "INSERT INTO R4R.MOBILE (USERNAME, PASSWORD, BALANCE) VALUES ('?', '?', '?');";
        try {
            //open class and load connection driver
            Class.forName("com.mysql.jdbc.Driver");
            // open MYSQL database connection
            con = DriverManager.getConnection("jdbc:mysql:///r4r", "root", "sachin");
            if (!con.isClosed()) {
                // insert data into databse
                PreparedStatement ps = (PreparedStatement) con.prepareStatement(sql);
                ps.setString(1, user);
                ps.setString(2, pass);
                ps.setString(3, balance);
                ps.execute();
                return "DataSuccessfully Store into dataBase";
            } else {
                return "Can't connect to MYSQL Database";
            }
        } catch (Exception ex) {
            Logger.getLogger(communicateServlet.class.getName())
				.log(Level.SEVERE, "An Exception occurred due processing request", ex);
            return ex.toString();
        } finally {
            // close database connection
            try {
                if (con != null) {
                    con.close();
                }
            } catch (SQLException ex) {
                Logger.getLogger(communicateServlet.class.getName())
					.log(Level.SEVERE, "An Exception occurred due processing request", ex);
            }
        }
    }
}


output
Previous Home Next