java calls js scripting language

      In the process of our development, there may be such a situation that we need to call js methods to complete some things in java . So when might this happen. For example, we use crawlers to simulate logging in to other websites, but some websites use js to encrypt the password at the front desk, so we need to call the js method in java to complete the encryption operation of the js password.

In this blog, the following calling methods are recorded:

1. java execute js file

2. The js method is written in the java code and then executed

3. The scope and global scope of the script engine itself

4. Call java class in js

 

accomplish:

1. java execute js file

     |- Execute the method in the js file

     |- Pass parameters to the js method

     |- Get the return value after the js method is executed

1.1 Definition of js method

function showUser(name) {
    // console.info("haha");
    return "haha[" + name + "], I returned the value";
}

 

 1.2 java code

@Test
	public void invokedJsFile() throws Exception {
		try (InputStream is = JavaInvokeJsTest.class.getResourceAsStream("script.js")) {
			ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
			// Get the js script engine
			ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("js");
			InputStreamReader isr = new InputStreamReader(is);
			scriptEngine.eval(isr);
			if (scriptEngine instanceof Invocable) {
				Invocable invocable = (Invocable) scriptEngine;
				/**
				 * Call the showUser method, and pass the javascript engine into the showUser method as a parameter
				 */
				String result = (String) invocable.invokeFunction("showUser", "javascript engine");
				System.out.println("the result is : " + result);
			}
		}
	}

 1.3 Results

 

2. The js method is written in the java code

2.1 java code

@Test
	public void invokedScriptMethod() throws Exception {
		ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
		ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("js");
		scriptEngine.put("userName", "张三");
		String script = "function showName(flag){ if(flag){ return userName + ', hello.' ;} else { return 'condition is not met';} }";
		scriptEngine.eval(script);
		Invocable invocable = (Invocable) scriptEngine;
		String result = (String) invocable.invokeFunction("showName", true);
		System.out.println(result);
	}

 2.2 Results

3. The scope and global scope of the script engine itself

   |- The put method of ScriptEngineManager sets the global scope

   |- ScriptEngine's put sets the scope of the script itself

@Test
	public void testScriptScope() throws Exception {
		ScriptEngineManager scriptEngineManager = new ScriptEngineManager();

		ScriptEngine scriptEngine1 = scriptEngineManager.getEngineByName("js");
		// Set the value to the script's global scope
		scriptEngineManager.put("globalVal", "全局");
		// This value is the scope of the script itself
		scriptEngine1.put("userName", "张三");
		String script1 = "function showName(){ return 'Get the value of globalVal in the global scope:['+globalVal + ']: Get the value of username in its own scope:[' + userName + '].' ; }";
		scriptEngine1.eval(script1);
		Invocable invocable1 = (Invocable) scriptEngine1;
		String result1 = (String) invocable1.invokeFunction("showName");
		System.out.println(result1);

		ScriptEngine scriptEngine2 = scriptEngineManager.getEngineByName("js");

		scriptEngine2.put("userName", "李四");
		String script2 = "function showName(){ return 'Get the value of globalVal in the global scope:['+globalVal + ']: Get the value of username in its own scope:[' + userName + '].' ; }";
		scriptEngine2.eval(script2);
		Invocable invocable2 = (Invocable) scriptEngine2;
		String result2 = (String) invocable2.invokeFunction("showName");
		System.out.println(result2);

		System.out.println("=====================================");
		System.out.println("Global scope value: ");
		System.out.println("===> gloableVal:" + scriptEngineManager.get("globalVal"));
		System.out.println("Script scope 1 value: ");
		System.out.println("===> userName:" + scriptEngine1.get("userName"));
		System.out.println("Script scope 2 value: ");
		System.out.println("===> userName:" + scriptEngine2.get("userName"));
		System.out.println("=====================================");

	}

 result:

 

4. Call java class in js

   |- To achieve the effect, the elements in the list collection of java are changed in js, and a value of new java.util.Date() is added

 4.1 Java code

    |- String script writes out how to call java methods in js.

@Test
	public void testJava() throws Exception {
		ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
		ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("js");
		List<String> list = new ArrayList<>(3);
		list.add("Zhang San");
		list.add("Li Si");
		list.add("wangwu");

		String script = "function show(list){ for(var i=0;i<list.size();i++){ list.set(i,list.get(i)+':'+i); };list.add(new java.util.Date().toString());}";
		scriptEngine.eval(script);

		Invocable invocable = (Invocable) scriptEngine;
		invocable.invokeFunction("show", list);

		System.out.println(list);
	}

 4.2 Results

 

      Under normal circumstances, there are few cases of calling js methods in java, but it is good to know about it.
 

 

 

 

 

 

 

 

 


 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326317247&siteId=291194637