tomcat - 如何在手机上制作一个midlet来访问pc上的一个servlet

标签 tomcat servlets java-me

刚刚尝试过,但失败了。我使用蓝牙将我的 midlet 上传到手机,并尝试连接到我在 PC 上运行的 servlet,但失败了。我的想象是使用调制解调器将我的电脑连接到互联网,然后获取其 IP 地址,并将 midlet 中 url 中的 localhost 替换为该 IP 地址,然后构建它并将其放入手机中。它不起作用。可以做什么?请帮忙

这是我的代码:Midlet: `import javax.microedition.midlet.;//midlet类包导入 import javax.microedition.lcdui.;//ui和命令包 导入 javax.microedition.io.;// 导入 java.io.;

/** * @author k'owino */ //定义midlet类 公共(public)类 mmm 扩展 MIDlet 实现 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

}//命令 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(okCmd);//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();

        }
    }
}

}//类(class)结束 servlet:import java.io.;//io类包 import javax.servlet.ServletException;//servlet异常类包 导入 javax.servlet.http.; import java.sql.*;//sql类包

/** * * @author k'owino */ 公共(public)类服务扩展 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();
        }

    }

}

}`。没有错误。在模拟器中工作正常,但在手机上无法连接到 servlet。

最佳答案

我猜你的调制解调器给你的 url 是 http://10.100.29.15 该地址不是公共(public)地址,而是一个 private block ,这意味着它只能由连接到您的调制解调器所连接的同一网络的人访问。为了使该测试生效,您应该通过 WiFi 将手机连接到同一调制解调器。这是有效的,因为电话将位于同一个私有(private)区 block 中并找到服务器。我自己做过几次。

另一个更难实现的选项是执行 port forwarding .如果您的 ISP 为您的调制解调器提供了一个公共(public)互联网地址并且可以转发端口,请选择任何端口转发到您的机器。通过这种方式,您可以从任何连接到互联网的设备连接到您的服务器,直到您的 ISP 为您的调制解调器分配不同的公共(public)地址。

关于tomcat - 如何在手机上制作一个midlet来访问pc上的一个servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6145829/

相关文章:

Openam 中的 Java.lang.NullPointerException(配置期间)

java - 从 Java ME 移植到 SE 时如何替换 javax.microedition.event.Event?

java - Tomcat/Spring 集成返回 404

java - 一种基于云分区的公有云负载均衡模型

java - WebSocket 连接到 'ws://*' 失败 : Error during WebSocket handshake: Unexpected response code: 404

java - 将格式化输入流流式传输到服务器的问题

java - CQ5 : 403 Forbidden occurs when call a Post servlet

java - servlet 中 getLocalPort() 和 getServerPort() 的区别

java - 解码图像 - BLACKBERRY/Java

java - 在 Java 的 RecordStore 中表示和存储数据的好方法是什么?