js函数保存在String字符串中
package com.netease.qiyu.test.datastageservice.service.impl;
import com.netease.qiyu.test.datastageservice.service.KefuSipAccountRegisterService;
import org.springframework.stereotype.Service;
import javax.script.Invocable;
import javax.script.scriptEngine;
import javax.script.scriptEngineManager;
import javax.script.scriptException;
import java.io.IOException;
import java.io.StringReader;
@Service
public class KefuSipAccountRegisterServiceImpl implements KefuSipAccountRegisterService {
public static void initialToolbarSDK(){
// js function:getRouteInfo,入参为province
// 参数不要带var。。不然后面执行方法的时候会报错。。
String routescript = "function getRouteInfo(province){ n" + " if (province=='henan') "
+ " return 'http://127.0.0.1/resweb';n" + " else "
+ " return '未找到对应的省份信息,province='+province;n" + "}";
// 脚本的执行结果
String scriptResult = "";
// 1.得到脚本引擎
scriptEngine engine = new scriptEngineManager().getEngineByName("nashorn");
try {
// 2.引擎读取 脚本字符串
engine.eval(new StringReader(routescript));
// 如果js存在文件里,举例
// Resource aesJs = new ClassPathResource("js/aes.js");
// this.engine.eval(new FileReader(aesJs.getFile()));
// 3.将引擎转换为Invocable,这样才可以掉用js的方法
Invocable invocable = (Invocable)engine;
// 4.使用 invocable.invokeFunction掉用js脚本里的方法,第一個参数为方法名,后面的参数为被调用的js方法的入参
scriptResult = (String)invocable.invokeFunction("getRouteInfo", "henan");
} catch (scriptException e) {
e.printStackTrace();
System.out.println("Error executing script: " + e.getMessage() + " script:[" + routescript + "]");
} catch (NoSuchMethodException e) {
e.printStackTrace();
System.out.println("Error executing script,为找到需要的方法: " + e.getMessage() + " script:[" + routescript + "]");
}
System.out.println(scriptResult.toString());
}
public static void main(String args[]){
initialToolbarSDK();
}
}
js函数保存在.js文件中
public static void initialToolbarSDK(){
String scriptResult = "";
scriptEngine engine = new scriptEngineManager().getEngineByName("nashorn");
try {
//文件路径设置成绝对路径即可
String jsFile = "service/impl/test.js";
FileInputStream fileInputStream = new FileInputStream(new File(jsFile));
Reader scriptReader = new InputStreamReader(fileInputStream, "utf-8");
engine.eval(scriptReader);
Invocable invocable = (Invocable)engine;
scriptResult = (String)invocable.invokeFunction("getRouteInfo", "henan1");
} catch (scriptException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(scriptResult.toString());
}