且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将值从 HTML 页面传递到 Java 小程序?

更新时间:2023-08-26 19:18:52

我认为您可以像这样从 javascript 对象指定参数:

I think you can specify your parameters from javascript objects like so:

<applet code="Calc.class" width="100" height="100">
    <param name="number" id="parm" value="&{num};">
</applet>

但是,我不确定与 IE 的兼容性,因此您可能必须document.write 将您的小程序代码注入相应的参数值,如下所示:

However, I'm not sure of the compatibility with IE so you may have to document.write out your applet code injecting the respective parameter values like so:

<head>
    <script type="text/javascript">
        var num;

        function getVal() {
            num = document.getElementById('in').value;

            writeAppletTags();
        }

        function writeAppletTags() { 
            var container = document.getElementById("applet-container");

            container.innerHTML = "<applet code=\"Calc.class\" width=\"100\" height=\"100\">";
            container.innerHTML += "<param name=\"number\" value=\"" + num + "\">";
            container.innerHTML += "</applet>";
        }
    </script> 
</head>
<body>
    Number : <input type="text" id="in"  ><br/>
    <button id="myBtn" onclick="getVal()">Try it</button><br/>  
    <div id="applet-container" />
</body>

从 Java 发送 POST

正如我在评论中所说,这有点复杂.您必须将值发布到托管文件(可以是任何服务器端脚本技术)(您也可以使用 GET).下面演示了这一点,从这里获取的代码一>.

As I said in my comment, this is a little more complicated. You'd have to POST (you could also use GET) your values to a hosted file (can be any server side scripting technology). The following demonstrates this, code taken from here.

URL url;
URLConnection urlConnection;
DataOutputStream outStream;
DataInputStream inStream;

// Build request body
String body = "key=value";

// Create connection
url = new URL("http://myhostedurl.com/receiving-page.php");
urlConnection = url.openConnection();
((HttpURLConnection)urlConnection).setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length", ""+ body.length());

// Create I/O streams
outStream = new DataOutputStream(urlConnection.getOutputStream());
inStream = new DataInputStream(urlConnection.getInputStream());

// Send request
outStream.writeBytes(body);
outStream.flush();
outStream.close();

// Close I/O streams
inStream.close();
outStream.close();