Share on Google+Share on Google+

mukesh
how to connect j2me program with mysql using servlet?
0 Answer(s)      6 years and 5 months ago
Posted in : JDBC

my program of j2me

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

public class Demo extends MIDlet implements CommandListener { private String username; private String url = "http://localhost:8082/mobileDemo/DBConnection"; private Display display; private Command exit = new Command("EXIT", Command.EXIT, 1);; private Command login = new Command("Login", Command.SCREEN, 1); // private TextField tb; private Form menu; private TextField tb1; private TextField tb2; DBConn db;

  public Demo() throws Exception {
        display = Display.getDisplay(this);

  }

  public void startApp() {
        displayMenu();
  }

  public void displayMenu() {
        menu = new Form("Login Form");

        tb1 = new TextField("Please input Mobile No: ","",30,TextField.ANY);

        tb2 = new TextField("Please input password: ","",30,TextField.PASSWORD);

        //menu.append(tb);
        menu.append(tb1);
        menu.append(tb2);
        menu.addCommand(exit);
        menu.addCommand(login);
        menu.setCommandListener(this);
        display.setCurrent(menu);
  }

  public void pauseApp() {}

  public void destroyApp(boolean unconditional) {}

  public void commandAction(Command command, Displayable screen) {
        if (command == exit) {
              destroyApp(false);
              notifyDestroyed();
        } else if (command == login) {
              db = new DBConn(this);
              db.start();
              db.connectDb(tb1.getString(),tb2.getString());
        }
  }

  public class DBConn implements Runnable {
        Demo midlet;
        private Display display;
       // String db;
        String user;
        String pwd;
        public DBConn(Demo midlet) {
              this.midlet = midlet;
              display = Display.getDisplay(midlet);
        }

        public void start() {
              Thread t = new Thread(this);
              t.start();
        }

        public void run() {
              StringBuffer sb = new StringBuffer();
              try {
                    HttpConnection c = (HttpConnection) Connector.open(url);
                    c.setRequestProperty("User-Agent","Profile/MIDP-1.0, Configuration/CLDC-1.0");
                    c.setRequestProperty("Content-Language","en-US");
                    c.setRequestMethod(HttpConnection.POST);
                    DataOutputStream os = (DataOutputStream)c.openDataOutputStream();


                    os.writeUTF(user.trim());
                    os.writeUTF(pwd.trim());
                    os.flush();
                    os.close();

                    // Get the response from the servlet page.
                    DataInputStream is =(DataInputStream)c.openDataInputStream();
                    //is = c.openInputStream();
                    int ch;
                    sb = new StringBuffer();
                    while ((ch = is.read()) != -1) {
                          sb.append((char)ch);
                    }
                    showAlert(sb.toString());
                    is.close();
                    c.close();
              } catch (Exception e) {
                    showAlert(e.getMessage());
              }
        }
        /* This method takes input from user like db,user and pwd and pass to servlet */
        public void connectDb(String user,String pwd) {

              this.user = user;
              this.pwd = pwd;
        }

        /* Display Error On screen*/
        private void showAlert(String err) {
              Alert a = new Alert("");
              a.setString(err);
              a.setTimeout(Alert.FOREVER);
              display.setCurrent(a);
        }
  };

}

servlet program is: import java.io.*; import java.util.*; import javax.sql.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*;

    public class DBConnection extends HttpServlet {
    public void init() { }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    DataInputStream in = new DataInputStream((InputStream)request.getInputStream());

    String user = in.readUTF();
    String pwd = in.readUTF();
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    String userid=connect(user.toLowerCase().trim(), pwd.toLowerCase().trim());
     if (userid == null)
    {
    response.sendError(response.SC_BAD_REQUEST, "Unable to locate user.");            
     return;
        }
    out.println(userid);
     out.close();
     in.close();
        out.flush();
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request,response);
    }
    private String connect(String user,String pwd){

        String db="mobileapp";
        String username="root";
        String password="vertrigo";
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {


        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+db,username,password);

        stmt = con.createStatement();
        rs = stmt.executeQuery("SELECT * FROM emp where username='user' and password='pwd'");
        // displaying records
        if(rs.next()){
        return rs.getString(2);
        }
        else { return null; }

    } catch (Exception e) { 

     return e.toString(); }


  }

    }

and xml of servlet is :

DBConnection DBConnection

DBConnection /DBConnection

please help me its urgent for me

Ads

View Answers









Tutorials   
Java Spring Hibernate Struts Training how to retrieve text and images from mysql database and show on html page using jsp servlet How to install Neo4j on Ubuntu 15.10? please help me in these prog MYSQL - mysql copy table to another table example by creating new table solution for mapping hibernate and pojos from net beans through database Connect GWT application with Oracle inventory System of Medical Store inventory System of Medical Store inventory System of Medical Store inventory System of Medical Store This code have created jTable that connected with a database.every cell of last column have a button.But this button doesn't work properly.Where is the error java program Java Database Program jdbc Database connection class in a live project ..?? What is JDBC architecture? Unable to Create DSN for excel to ms access importing data and edit that data Database Scrolling Buttons how to use foreign key in java How to delete content of a log file from linux terminal? JSP-Oracle connectivity Student Management System Java code for Saving Marathi (Indian local language ) in Mysql and retrieving the same crud operations with foreign key constraint. I really need help with this assignment question Please help me out Please Backup Failed Mysqldump Got Errno 28 On Write Upgrade MySQL 5.1 to 5.5 in cpanel mysqldump all databases com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'jpa.sequence' doesn't exist persistence xml class element persistence.xml for MySQL MySQL JDBC Driver pom dependency code Blob column jdk6 and oracle 8i connexion oracle 8i et jdk6 java [ cannot retrive date from sql ] why?? Order Entry System How to threow timeout exception when DB is not responding How to threow timeout exception when DB is not responding This is the employee form to add data to mysql database but I got error of NullPointerException, Is this write code please give me feedback as soon as possible make a method which takes user name & pwd as parameter & validate them against the database. If the corresponding user exist return true otherwise false. prabhakar validating credentials and displaying error message in login .jsp if not valid JDBC jdbc jdbc code register servlet vibhu connectiondetails from vibhu

Ads

 
Advertisement null

Ads