This example uses a number of JS files to show the Java invoke JS effect, JDK version 1.8 (seemingly more than 1.6 support, not verified)
First, Common.js
Get current date, format: yyyy mm month DD Day
function Getnowdate () {
var date = new Date ();
var y = date.getfullyear ();
var m = Addzero (Date.getmonth () + 1);//Gets the date of the current month
var d = Addzero (Date.getdate ());
Return y + "year" + M + "month" + D + ' Day ';
}
Complement 0 operations
function Addzero (number) {
if (number < 10) {
Number = ' 0 ' + number;
}
return number;
}
Second, main.js
function SayHello (name) {
return name + ' Hello, now is A.D. ' + getnowdate ();
}
Third, Java interface
Package com.qfx.interfaces;
/**
- @author ZHANGPJ September 6, 2018
*/
Public interface Javascriptinterface {
The method name is the same as the function name that exists in JavaScript, which is the same as the method SayHello (name) in Main.js
public string SayHello (string name);
}
Iv. Java calls
Package com.qfx.test;
Import Java.io.FileReader;
Import javax.script.Invocable;
Import Javax.script.ScriptEngine;
Import Javax.script.ScriptEngineManager;
Import Com.qfx.interfaces.JavaScriptInterface;
/**
-
@author ZHANGPJ September 6, 2018
*/
public class Executejavascript {
public static void Main (string[] args) {
Readscripttest ("Zhang San");
}
public static void Readscripttest (String param) {
Scriptenginemanager manager = new Scriptenginemanager ();
1. Get a JavaScript engine instance
ScriptEngine engine = Manager.getenginebyname ("javascript");
try { // 2.获取文件路径 String path = Thread.currentThread().getContextClassLoader() .getResource("").getPath(); // System.out.println(path); // 3.执行js脚本,FileReader的参数为所要执行的js文件的路径 engine.eval(new FileReader(path + "../static/js/dateUtil.js")); engine.eval(new FileReader(path + "../static/js/main.js")); // 4.验证engine是否属于Invocable的实例 if (engine instanceof Invocable) { Invocable invocable = (Invocable) engine; // 5.从脚本引擎中获取JavaScriptInterface接口对象 JavaScriptInterface executeMethod = invocable .getInterface(JavaScriptInterface.class); // 6.调用这个js接口(会去调用js中的相匹配名称的函数) String info = executeMethod.sayHello(param); System.out.println(info); } } catch (Exception e) { e.printStackTrace(); }
}
}
V. Advanced applications
Refer to Java8nashorn tutorial, JS can also directly call Java
Java invoke JS simple application