Java调用js方法
生活随笔
收集整理的這篇文章主要介紹了
Java调用js方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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());} 超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的Java调用js方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java文件操作:文件夹中搜索文件
- 下一篇: Java之toString()方法详解