1. 程式人生 > >對java呼叫javascript的封裝

對java呼叫javascript的封裝

maven依賴

<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.47</version>
		</dependency>
<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.6</version>
		</dependency>
		<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-core</artifactId>
				<version>4.3.6.RELEASE</version>
			</dependency>

java程式碼

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.junit.Test;
import org.springframework.util.ResourceUtils;

import com.alibaba.fastjson.JSONObject;

public class Js {
	private static ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
	private static Invocable invocable = (Invocable) engine;

	/**
	 * 測試java傳參到js檔案,並且js將返回結果返回給java。
	 * 
	 * @throws FileNotFoundException
	 */
	@Test
	public void testArg() throws FileNotFoundException {
		JSONObject json = new JSONObject();
		json.put("name", "avril lavigne");
		json.put("age", 110);
		json.put("like", 3.14);
		String arg = json.toJSONString();
		/**
		 * 使用spring的ResourceUtils,方便讀取檔案
		 */
		File file = ResourceUtils.getFile("classpath:js/testArg.js");
		String res = runFile(file, arg);
		System.out.println(res);
	}

	/**
	 * 將給定檔案的內容作為js程式碼執行,並且將字串作為入參和出參。
	 * @param file
	 * @param arg
	 * @return
	 */
	public static String runFile(File file, String arg) {
		try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line).append(System.lineSeparator());
			}
			return run(sb.toString(), arg);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	/**
	 * 將給定名稱的檔案的內容作為js程式碼執行,並且將字串作為入參和出參。
	 * @param file
	 * @param arg
	 * @return
	 */
	public static String runFile(String file, String arg) {
		File f;
		try {
			f = ResourceUtils.getFile(file);
			return runFile(f, arg);
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 執行給定的js程式碼,並且將字串作為入參和出參。
	 * 字串是最通用的方式,所以設計成入參和出參都是字串。
	 * @param js
	 * @param arg
	 * @return
	 */
	public static String run(String js, String arg) {
		Object res;
		try {
			JSONObject param = null;
			if (arg != null) {
				param = JSONObject.parseObject(arg);
			}
			engine.eval(js);
			res = invocable.invokeFunction("main", param);
			if (res == null) {
				return null;
			}
			return res.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}

src/main/recources/js/testArg.js

/**
 * 程式入口,從main函式開始
 * @param arg java呼叫時傳進來的物件
 * @return JSON字串 
 * */
function main(arg){
	print('abc');
	print(arg.name);
	var res = {
			a:'A',
			b:'B',
			c:[1,2,3]
	};
	return JSON.stringify(res);
}
function f(){
	
}