定义和使用 Applet 参数
对于 Java applet,参数是对于应用程序的命令行参数。它们使用户能够自定义 Servlets 的操作。通过定义参数,可以提高 Servlets 的灵 Active,使 Servlets 可以在多种情况下工作,而无需重新编码和重新编译它。
指定 Servlets 的 Importing 参数
您可以在小应用程序的 Java 网络启动协议(JNLP)文件或<applet>
标记的<parameter>
元素中指定小应用程序的 Importing 参数。通常最好在 applet 的 JNLP 文件中指定参数,以便即使 applet 部署在多个 Web 页面上也可以一致地提供参数。如果 applet 的参数会因网页而异,则应在<applet>
标签的<parameter>
元素中指定参数。
如果您不熟悉 JNLP,请参阅Java 网络启动协议主题以获取更多信息。
考虑一个带有三个参数的 Servlets。 paramStr
和paramInt
参数在 Servlets 的 JNLP 文件applettakesparams.jnlp中指定。
<?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="1.0+" codebase="" href="">
<!-- ... -->
<applet-desc
name="Applet Takes Params"
main-class="AppletTakesParams"
width="800"
height="50">
<param name="paramStr"
value="someString"/>
<param name="paramInt" value="22"/>
</applet-desc>
<!-- ... -->
</jnlp>
paramOutsideJNLPFile
参数在AppletPage.html传递到 Deployment Toolkit 脚本的runApplet
函数的parameters
变量中指定。
<html>
<head>
<title>Applet Takes Params</title>
<meta http-equiv="Content-Type" content="text/html;
charset=windows-1252">
</head>
<body>
<h1>Applet Takes Params</h1>
<script
src="https://www.java.com/js/deployJava.js"></script>
<script>
var attributes = { code:'AppletTakesParams.class',
archive:'applet_AppletWithParameters.jar',
width:800, height:50 };
var parameters = {jnlp_href: 'applettakesparams.jnlp',
paramOutsideJNLPFile: 'fooOutsideJNLP' };
deployJava.runApplet(attributes, parameters, '1.7');
</script>
</body>
</html>
有关runApplet
函数的更多信息,请参见部署 Servlets。
检索 Applet 的 Importing 参数
您可以使用Applet
类的getParameter方法来检索 Servlets 的 Importing 参数。 AppletTakesParams.javaServlets 检索并显示其所有 Importing 参数(paramStr
,paramInt
和paramOutsideJNLPFile
)。
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
import javax.swing.JLabel;
public class AppletTakesParams extends JApplet {
public void init() {
final String inputStr = getParameter("paramStr");
final int inputInt = Integer.parseInt(getParameter("paramInt"));
final String inputOutsideJNLPFile = getParameter("paramOutsideJNLPFile");
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI(inputStr, inputInt, inputOutsideJNLPFile);
}
});
} catch (Exception e) {
System.err.println("createGUI didn't successfully complete");
}
}
private void createGUI(String inputStr, int inputInt, String inputOutsideJNLPFile) {
String text = "Applet's parameters are -- inputStr: " + inputStr +
", inputInt: " + inputInt +
", paramOutsideJNLPFile: " + inputOutsideJNLPFile;
JLabel lbl = new JLabel(text);
add(lbl);
}
}
接下来显示AppletTakesParams
Servlets。
A browser with JavaScript enabled is required for this page to operate properly\.
Note:
如果看不到 Servlets 正在运行,则需要至少安装Java SE 开发套件(JDK)6 更新 10版本。
Note:
如果看不到示例正在运行,则可能需要在浏览器中启用 JavaScript 解释器,以便 Deployment Toolkit 脚本能够正常运行。
下载源代码用于“带参数的 Servlets”示例,以进行进一步试验。