简体   繁体   中英

phone to servlet communication via bluetooth using j2me

I made the simple j2me login application, code is below.

It's working perfectly on emulator, now I want to run it on my mobile application via bluetooth connection. In other word, phone (j2me application)-pc (servlet) communication via bluetooth. Need help.

update device supports JSR 82 Java APIs for Bluetooth 1.1.

package hello;

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

public class MidletServlet extends MIDlet implements CommandListener {
    Display display = null;
    Form form = null;
    TextField tb = null,tb1= null;
    String str = null;
    String url = "http://localhost:8084/j2metest/getText";
    Command backCommand = new Command("Back", Command.BACK, 0);
    Command submitCommand = new Command("Submit", Command.OK, 2);
    Command exitCommand = new Command("Exit", Command.STOP, 3);
    private Test test;

    public MidletServlet() {}

    public void startApp() throws MIDletStateChangeException {
        display = Display.getDisplay(this);
        form = new Form("Request Servlet");
        tb = new TextField("Username: ","",30,TextField.ANY );
        tb1 = new TextField("Password: ","",30,TextField.ANY);
        form.append(tb);
        form.append(tb1);
        form.addCommand(submitCommand);
        form.addCommand(exitCommand);
        form.setCommandListener(this);
        display.setCurrent(form);
    }

    public void pauseApp() {}

    public void destroyApp(boolean unconditional) {}

    public void commandAction(Command c, Displayable d) {
        if (c == exitCommand) {
            destroyApp(true);
            notifyDestroyed();
        } else if (c == backCommand) {
            display.setCurrent(form);
        } else if (c == submitCommand) {
            test  = new Test(this);
            test.start();
            test.getServlet(tb.getString(),tb1.getString());
        }
    }
    class Test implements Runnable {
        MidletServlet midlet;
        private Display display;
        String pass;
        String user;

        public Test(MidletServlet 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-2.1, Configuration/CLDC-1.1");

                c.setRequestProperty("Content-Language","en-US");
                c.setRequestMethod(HttpConnection.POST);

                DataOutputStream os =
                        (DataOutputStream)c.openDataOutputStream();

                os.writeUTF(user.trim());
                os.writeUTF(pass.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 text and pass
                to servlet */
        public void getServlet(String user,String pass) {
            this.user = user;
            this.pass=pass;
        }

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

and this is my servlet code

package my;
import java.sql.*;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author vicky
 */
import java.io.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class getText 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 pass=in.readUTF();
        String text="";
        try {

            Class.forName("oracle.jdbc.driver.OracleDriver");
                Connection conn= DriverManager.getConnection(
                "jdbc:oracle:thin:@localhost:1521:XE","vicky","1");
                Statement stmt=conn.createStatement();
                ResultSet rs;int f=0;
            rs=stmt.executeQuery("select * from ADMIN");
            //s1=request.getParameter("un");
            //s2=request.getParameter("pw");

            if(user==""||pass=="")
                {
                    text="Username and Password are required for login;";
                }
            else
                {
                //session.setAttribute("uname",s1);
                while(rs.next())
                    {
                    String s3=rs.getString(1);
                    String s4=rs.getString(2);
                    if (user.equals(s3)&&pass.equals(s4))
                        {
                            f=1;
                        }
                }
                if(f==1)
                    {
                    //response.sendRedirect("success.jsp");
                    //out.print(s1);
                text="Login Successful";
                                }
                else
                    {
                     //out.print("ERROR");
                    text="Login Failure";
                                }
                }
          }
        catch(Exception e)
        {
       //out.print("ERROR"+e);
        text="error"+e;
            }
        response.setContentType("text/plain");
        response.setContentLength(text.length());
        PrintWriter out = response.getWriter();

        out.print(text);


        in.close();
        out.close();
        out.flush();
    }

    public void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException,
            IOException {

        doPost(request,response);
    }
}

I think this is where the actual problem is, Just change your String url = "http://localhost:8084/j2metest/getText"; to its computer's ip like 192.168.1.1 kind of and then try again.

The reason behind this is when you run Java ME code on Emulator, it detects localhost. But Now when you deployed that application on mobile and connects it with Bluetooth, you are accessing Computer from the outside, so in this case localhost will not work. you need to pass its IP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM