今天在开发中使用到了js和Java的交互,平时我们用的比较多的就是js调用Java的方法,可以使用dwr、Ajax、jquery。突然发现要Java调用js的话还真没有见过,今天上网查询了下资料,顺便总结一下:
前提条件:jdk1.6才支持,1.6以前的就不行了。
js代码如下:
- function convert (id,str)
- {
- if (‘505041’==id)
- {
- return str;
- }
- else
- {
- return “A”;
- }
- }
function convert (id,str)
{
if ('505041'==id)
{
return str;
}
else
{
return "A";
}
}
Java代码如下:
- package ;
- import ;
- import ;
- import ;
- import ;
- import ;
- import ;
- public class JsTest {
- public static void main(String[] args) throws Exception {
- testJSFile();
- }
- private static void testJSFile() throws Exception {
- ScriptEngineManager mgr = new ScriptEngineManager();
- ScriptEngine engine = (”javascript”);
- (readJSFile());
- Invocable inv = (Invocable) engine;
- Object res = (Object) (”convert”, new String[] { “5050412”, “D” });
- (”res:” + res);
- }
- private static String readJSFile() throws Exception {
- StringBuffer script = new StringBuffer();
- File file = new File(“E:\\workspace\\test4\\WebRoot\\”);
- FileReader filereader = new FileReader(file);
- BufferedReader bufferreader = new BufferedReader(filereader);
- String tempString = null;
- while ((tempString = ()) != null) {
- (tempString).append(”\n”);
- }
- ();
- ();
- return ();
- }
- }
package ;
import ;
import ;
import ;
import ;
import ;
import ;
public class JsTest {
public static void main(String[] args) throws Exception {
testJSFile();
}
private static void testJSFile() throws Exception {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = ("javascript");
(readJSFile());
Invocable inv = (Invocable) engine;
Object res = (Object) ("convert", new String[] { "5050412", "D" });
("res:" + res);
}
private static String readJSFile() throws Exception {
StringBuffer script = new StringBuffer();
File file = new File("E:\\workspace\\test4\\WebRoot\\");
FileReader filereader = new FileReader(file);
BufferedReader bufferreader = new BufferedReader(filereader);
String tempString = null;
while ((tempString = ()) != null) {
(tempString).append("\n");
}
();
();
return ();
}
}
在Java类中直接run就可以得到如下结果:
res:A
以此记录一下。