Java Programing laungage

J2ME Projects

J2ME Project 1

adplus-dvertising
Create an application for access database through 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 of servlet in Midlet. In which a string is passing to servlet through Midlet class and store into database form servlet, and database response display in Midlet client class.

Midlet Program


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

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

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

    final Command SUBMIT = new Command("Store", Command.OK, 1);
    final Command EXIT = new Command("Exit", Command.EXIT, 2);
    private Form form;
    private TextField T_user, T_pass, T_balance;

    public dataBaseSevletMidlet() {
        // declaration field with initialization
        form = new Form("DataBase Connection");
        T_user = new TextField("Username", "", 10, TextField.PLAIN);
        T_pass = new TextField("Password", "", 10, TextField.PLAIN);
        T_balance = new TextField("Balance $", "", 12, TextField.NUMERIC);
        form.append(T_user);
        form.append(T_pass);
        form.append(T_balance);
        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);
        } else if (c == SUBMIT) {
            // 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
                DataServletClient client = new DataServletClient(this, user, pass, balance);
                client.start();
            } else {
                Alert alert = new Alert("Blank Field Error", 
					"Please Don't leave any Block empty!", null, AlertType.ALARM);
                alert.setTimeout(1000);
                Display.getDisplay(this).setCurrent(alert, d);
            }
        }
    }
}

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

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

    DataServletClient(dataBaseSevletMidlet 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, 0);
        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.0");
            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 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("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 == EXIT || c == Alert.DISMISS_COMMAND) {
            parent.destroyApp(true);        //terminate application
        }
    }
}

Servlet Program


/*
 * Save as a dataBaseServlet.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 dataBaseServlet 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 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);

        // initilized a new class
        DataBaseClient client = new DataBaseClient();
      client.store(user, pass, balance);   // passing value form class constructor

        // send response to the client
        out.println("Data sucessfully store into MYSQL DataBase");
        out.close();    // close text-output stream 
    }
}

/*
 * ----------------------------------------------------------
 * Class DataBaseClient handle store data into MYSQL database
 * ----------------------------------------------------------
 */
class DataBaseClient {

    // private Field 
    private Connection con = null;
    private String sql = "INSERT INTO R4R.MOBILE 
	(USERNAME, PASSWORD, BALANCE) VALUES ('?', '?', '?');";

    void store(String user, String pass, String balance) {

        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()) {
          // insert data into database 
           PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1, user);
            ps.setString(2, pass);
            ps.setString(3, balance);
            ps.execute();
                System.out.println("Data Sucessfully Store into MYSQL DataBase");
            } else {
                System.out.println("Can't open MYSQL DataBase, try Later");
            }
        } catch (Exception ex) {
            Logger.getLogger(DataBaseClient.class.getName())
			.log(Level.SEVERE, "An Exception occurred due processing request", ex);
        } finally {
            // close Database connection
            try {
                if (con != null) {
                   con.close();
                }
            } catch (SQLException ex) {
                Logger.getLogger(DataBaseClient.class.getName())
			.log(Level.SEVERE, "An Exception occurred due processing request", ex);
            }
        }
    }
}


output
Previous Home Next