【发布时间】:2012-01-19 19:22:23
【问题描述】:
我正在创建一个需要使用 jar 或类文件中的 Java 对象的 Web 应用程序。如何桥接我的 Java 类和 JavaScript? (总的来说,我对 JavaScript 和 Web 开发还很陌生)。
(我得到的关于这个主题的大部分搜索结果都来自那些没有意识到 Java 和 JavaScript 彼此无关的人。这里不是这种情况。)
我想要完成的事情:
PropertiesEditor 对象首先加载一个属性文件模板并将属性拆分为一个 ArrayList。然后在网页上为每个属性生成一个表单,并允许用户编辑值并使用新文件名提交。然后将这些值传递给 PropertiesEditor 对象并创建属性文件,并与其他属性文件一起保存。这个网络应用程序将允许非编程用户从现有模板创建新的属性文件;就我而言,用于文本语言的本地化。
Java 类:
public class PropertiesEditor {
private File propertiesFile;
private ArrayList<Property> propertyList;
private Scanner scan;
/**
*
*/
public void load(String fileName) {
try {
propertiesFile = new File(fileName);
scan = new Scanner(propertiesFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
propertyList = new ArrayList<Property>();
try{
while (scan.hasNext()){
String string = scan.nextLine();
if (!(string.startsWith("#"))){
String[] array = string.split("=");
String key = array[0];
String value = array[1];
Property property = new Property(key, value);
propertyList.add(property);
}
}
}catch (NoSuchElementException nse){
}
}
public void save(String fileName){
Properties properties = new Properties();
for (Property current : propertyList){
properties.setProperty(current.getKey(), current.getValue());
}
try {
File file = new File(fileName + ".properties");
FileOutputStream fileOut = new FileOutputStream(file);
properties.store(fileOut, fileName);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public int getNumberOfProperties(){
return propertyList.size();
}
public String getPropertyKey(int index){
return propertyList.get(index).getKey();
}
public String getPropertyValue(int index){
return propertyList.get(index).getValue();
}
public void setPropertyValue(int index, String value){
propertyList.get(index).setValue(value);
}
}
我认为 JavaScript 应该是什么样子:
<script type='text/javascript'>
var pe = <PropertiesEditorObject>;//Obviously where I want to create the Java Object
pe.load("en-us.properties");
function formValidator(){
for (i=0;i<pe.getNumberOfProperties();i++){
var current = document.getElementById(i);
pe.setPropertyValue(i, current);
}
pe.save(document.getElementById('fileName');
}
function createForm(){
document.write("<form onsubmit='return formValidator()' >")
for (i=0;i<pe.getNumberOfProperties();i++){
document.write( pe.getPropertyValue(i) + "<input type='text' id='" + i + "' /><br />"
}
document.write("Properties File Name: <input type='text' id='fileName' /><br /><input type='submit' value='Check Form' /><br /></form>");
}
</script>
【问题讨论】:
-
你不能混合和匹配 java 对象和 javascript 对象。
-
Java 和 Javascript 不相关。如果您有一个现有的 Java 代码库需要某种方式的 Javascript 前端,那么让它们相互交互的一种方法是开发一个 Web 应用程序,该应用程序提供一个您的 Javascript 可以与之交互的 Web 服务。
-
我提到如果你阅读整篇文章,我意识到 Java 和 JavaScript 没有关系。
标签: java javascript jsp web-applications