我正在创建一个Web应用程序,需要使用来自jar或class文件的Java对象。如何连接我的Java类和JavaScript? (我通常对JavaScript和Web开发相当陌生)。JavaScript - 并创建和使用Java对象
(大多数搜索结果我得到了这个话题的是从谁不知道,Java与JavaScript无关彼此的人。这不是这里的情况。)
我想要完成:
PropertiesEditor对象首先加载一个属性文件模板并将属性拆分成一个ArrayList。然后在网页上为每个属性生成一个表单,并允许用户编辑这些值并使用新的文件名提交。然后将值传递给PropertiesEditor对象,并创建属性文件,并与其他属性文件一起保存。此Web应用程序将允许非编程用户从现有模板创建新的属性文件;在我的情况下文本语言的本地化。
的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是不相关的。 – unmuse