随笔记:java中调用JavaScript方法(多js文件)
程序员文章站
2024-02-14 14:13:58
...
1. 测试代码目录结构:
2. 接口定义
JavaScriptInterface中定义了一个接口:
public interface JavaScriptInterface {
public String execute(String s1, String s2);
}
JavaScript1.js 同样定义一个excute方法
function execute(s1, s2) {
if (!validate(s1, s2)) {
return s2 + s1
}
return s1 + s2;
}
其中validate方法为JavaScript2.js中声明的方法,内容如下:
function validate(s1,s2) {
return true
}
3. java调用
import com.byrd.development.notes.others.js.JavaScriptInterface;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.FileReader;
public class ExecuteScript {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
try {
String path = Thread.currentThread().getContextClassLoader().getResource("").getPath(); // 获取targe路径
System.out.println(path);
// FileReader的参数为所要执行的js文件的路径
engine.eval(new FileReader(path+ "js/JavaScript1.js"));
engine.eval(new FileReader(path+ "js/JavaScript2.js"));
if (engine instanceof Invocable) {
Invocable invocable = (Invocable) engine;
JavaScriptInterface executeMethod = invocable.getInterface(JavaScriptInterface.class);
System.out.println(executeMethod.execute("str1", "str2"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}