开发者

how to make a midlet on phone to access a servlet on pc

Just been trying out this but it's failing. I uploaded my midlet to the Phone using bluetooth and tried to connect to my servlet running on pc but it failed. My imagination was to connect my pc to the internet using a modem and then obtain its IP address and replace localhost in the url in the midlet with that IP address and build it and place it in the phone. It did not work. What can be done? Please help

This is my code:Midlet: `import javax.microedition.midlet.;//midlet class package import import javax.microedition.lcdui.;//package for ui and commands import javax.microedition.io.;// import java.io.;

/** * @author k'owino */ //Defining the midlet class public class mmm extends MIDlet implements CommandListener {

private boolean midletPaused = false;//variable for paused state of midlet
//defining variables
private Display display;// Reference to Display object
private Form welForm;//welcome form
private Form welForm2;//welcome form
private Form welForm3;//welcome form
private List mainMenu;//vote code
private List voteCats;//vote cats
private List voteCats2;//vote cats
private StringItem welStr;
private StringItem welStr1;
private TextField codeField;
private StringItem codeError;
private Command quitCmd;
private Command contCmd;
private Command quitCmd1;
private Command contCmd1;
private Command quitCmd3;
private Command contCmd3;
private Command okCmd;
private Command quCmd;
private Command bkCmd;
private Command ok2Cmd;
String codefield;
public static String[] list_wrd = new String[100];
public static String[] list_wrd1 = new String[100];
public static String track = "";
int l;
int g;
String selected, postn_scted;
String cnfrm, cnfrm2;
String st2;

//constructor of the midlet
public mmm() {

    display = Display.getDisplay(this);//creating the display object
    welForm = new Form("THE MVS");//instantiating welForm object
    welStr = new StringItem("", "Welcome to the MVS, Busitema's mobile voter."
            + "Please enter your voting code below");//instantiating welStr string item
    codeError = new StringItem("", "");//intantiating phone error string item
    codeField = new TextField("Voting code", "", 10, TextField.PASSWORD);//phone number field object
    quitCmd = new Command("Quit", Command.EXIT, 0);//creating quit command object
    contCmd = new Command("Continue", Command.OK, 0);//creating continue command object
    welForm.append(welStr);//adding welcome string item to form
    welForm.append(codeField);//adding phone field to form
    welForm.append(codeError);//adding phone error string item to form
    welForm.addCommand(contCmd);//adding continue command
    welForm.addCommand(quitCmd);//adding quit command
    welForm.setCommandListener(this);
    display.setCurrent(welForm);

}

//start application method definition
public void startApp() {
}

//pause application method definition
public void pauseApp() {
}

//destroy application method definition
public void destroyApp(boolean unconditional) {
}

//Command action method definition
public void commandAction(Command c, Displayable d) {
    if (d == welForm) {
        if (c == quitCmd) {
            exitMidlet();//call to exit midlet
        } else {//if the command is contCmd
            //place a waiting activity indicator
            System.out.println("ken de man");
            Thread t = new Thread() {

                public void run() {
                    try {

                        //method to connect to server
                        sendPhone();

                    } catch (Exception e) {
                    }//end of catch
                }//end of ru()
            };//end of thread
            t.start();//starting the thread
        }//end of else
    }//end of first if

}//end of command action

//defining sendPhone method
public void sendPhone() throws IOException {

    System.out.println("ken de man");//check

    HttpConnection http = null;//HttpConnection variable
    OutputStream oStrm = null;//OutputStream variable
    InputStream iStrm = null;//InputStream variable
    //String url = "http://10.100.29.15:8080/www/serv" + "?" + "code=" + codeField.getString();//server url and parameters
    String url = "http://localhost:8080/www/serv" + "?" + "code=" + codeField.getString();//server url and parameters
    try {
        http = (HttpConnection) Connector.open(url);//opening connection
        System.out.println("connection made");//checking code
        //oStrm = http.openOutputStream();//opening output stream
        http.setRequestMethod(HttpConnection.GET);//setting request type
        //http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//setting content type
        //byte data[] = ("phone=" + phoneField.getString()).getBytes();
        //oStrm.write(data);
        iStrm = http.openInputStream();//openning input stream
        if (http.getResponseCode() == HttpConnection.HTTP_OK) {//if the connection is ok
            int length = (int) http.getLength();
            String str;
            if (length != -1) {
                byte servletData[] = new byte[length];
                iStrm.read(servletData);
                str = new String(servletData);
            } else // Length not available...
            {
                ByteArrayOutputStream bStrm = new ByteArrayOutputStream();

                int ch;
                while ((ch = iStrm.read()) != -1) {
                    bStrm.write(ch);
                }

                str = new String(bStrm.toByteArray());
                bStrm.close();
            }
            System.out.println("de man");

            System.out.println(str);
            int x = str.length();
            System.out.println(x);

            if (str.equals("ok")) {
                track = codeField.getString();
                codeField.setString("");//emptying textfield

                mainMenu = new List("", Choice.IMPLICIT);//creating a list object
                mainMenu.append("Vote", null);
                mainMenu.append("Results", null);
                quCmd = new Command("Quit", Command.EXIT, 0);//creating a quit command on the list
                okCmd = new Command("Ok", Command.OK, 0);//creating an ok command on the list
                mainMenu.addCommand(okC开发者_如何学运维md);//adding ok command
                mainMenu.addCommand(quCmd);//adding quit command
                mainMenu.setSelectCommand(okCmd);//setting the default select command
                mainMenu.setCommandListener(this);//setting the command listener
                display.setCurrent(mainMenu);
            } else {
                //add error message to phone_error stingItem

                codeField.setString("");//emptying textfield
                codeError.setText("Wrong code, please enter right code");
                display.setCurrent(welForm);
            }
        }
    } catch (Exception e) {
    } finally {
        if (iStrm != null) {
            iStrm.close();

        }
        if (http != null) {
            http.close();

        }
    }
}

}//end of class servlet:import java.io.;//package for io classes import javax.servlet.ServletException;//package for servlet exception classes import javax.servlet.http.; import java.sql.*;//package for sql classes

/** * * @author k'owino */ public class serv extends HttpServlet {

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

    //declaring variables
    PrintWriter pw;//PrintWriter object
    String vcode;//code parameter sent from client
    Connection con = null;//connection variable
    String dbDriver = "com.mysql.jdbc.Driver";//the database driver
    String dbUrl = "jdbc:mysql://localhost/mvs_db";//the database url
    String dbUser = "root";//database user
    String dbPwd = "";//database password
    PreparedStatement pstmt = null;//Prepared statement variable
    String query = "select * from student where vote_code = ?;";//the query to select code from db
    ResultSet rs = null;//resultset variable
    String dbCode = null;//code from database

    //getting the "phone" parameter sent from client
    vcode = req.getParameter("code");//getting the "code" parameter sent from voter
    //vcode = "345qwert";

    //setting the content type of the response
    res.setContentType("text/plain");

    //creating a PrintWriter object
    pw = res.getWriter();//getting a writer
    //pw.println("ken");

    try {//trying to load the database driver and establish a connection to the database

        Class.forName(dbDriver);//loading the database driver
        con = DriverManager.getConnection(dbUrl, dbUser, dbPwd);//establishing a connection to the database
        //pw.println("connection established");//output if connection is established
    } catch (Exception e) {
        e.printStackTrace(pw);//printing the exception error trace to the writer
    }

    //trying to query the database
    try {

        pstmt = con.prepareStatement(query);//preparing a statement
        pstmt.setString(1, vcode);//setting the input parameter
        rs = pstmt.executeQuery();//executing the query assigning to the resultset object
        //pw.println("ken");

        //extracring data from the resultset
        while (rs.next()) {
            dbCode = rs.getString("vote_code");//getting the code from database
            //pw.println(dbPhone);
        }//end of while

        if (vcode.equals(dbCode)) {
            pw.print("ok");//printing ok if code mataches
        } else {
            pw.print("error");//printing error if code doesn't match
        }
        //pw.println("yeah");

    } catch (Exception e) {
        e.printStackTrace(pw);//sending the error
    }
    finally{
        if(pw !=null){
            pw.close();
        }

    }

}

} `. No errors. Works fine in emulator but cannot connect to servlet when on phone.


I guess the url your modem is giving you is http://10.100.29.15 That address is not a public address but a private block, that means it can just be accessed by someone connected to the same network your modem is connected to. In order to that test to work, you should connect your phone to the same modem via WiFi. That works as the phone will be in the same private block and find the server. I have done it myself several times.

Another option, which is harder to get working, is do port forwarding. If your ISP gives your modem a public internet address and can forward ports, choose any port to forward to your machine. In that way you can connect to your server from any Internet connected device, until your ISP assigns a different public address for your modem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜