Home > Web Front-end > JS Tutorial > How to run js code sharing in java program

How to run js code sharing in java program

零到壹度
Release: 2018-04-14 15:10:31
Original
1767 people have browsed it

The content of this article is to share the code of how to run js in a java program. It has a certain reference value. Friends in need can refer to the

1.6 version ScriptEngine has been added to directly run js code

1. Directly write js code

import javax.script.ScriptEngine; 
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;   /**  * 直接调用js代码  */
public class ScriptEngineTest {    
public static void main(String[] args) { 
  ScriptEngineManager manager = new ScriptEngineManager();
  ScriptEngine engine = manager.getEngineByName("javascript");
     try{    
          engine.eval("var a=3; var b=4;print (a+b);");
         // engine.eval("alert(\"js alert\");");    // 不能调用浏览器中定义的js函数 // 错误,会抛出alert引用不存在的异常
 }catch(ScriptException e){
 e.printStackTrace();
 }
 }   
}
Copy after login


2. Call function

import java.io.FileReader; 
  import javax.script.Invocable;

 import javax.script.ScriptEngine;

 import javax.script.ScriptEngineManager;  
 /**  * Java调用并执行js文件,传递参数,并活动返回值  *   * @author manjushri  */ 

public class ScriptEngineTest {    

public static void main(String[] args) throws Exception {   
ScriptEngineManager manager = new ScriptEngineManager();   
ScriptEngine engine = manager.getEngineByName("javascript");     

String jsFileName = "expression.js";   // 读取js文件   

FileReader reader = new FileReader(jsFileName);   // 执行指定脚本   
engine.eval(reader);   

if(engine instanceof Invocable) {    
Invocable invoke = (Invocable)engine;    // 调用merge方法,并传入两个参数    

// c = merge(2, 3);    

Double c = (Double)invoke.invokeFunction("merge", 2, 3);    

System.out.println("c = " + c);   
}   

reader.close();  

  }
}
Copy after login


js file

// expression.js 
function merge(a, b) { 
 c = a * b; 
 return c; 
}
Copy after login


Related recommendations:

Java directly runs JavaScript code or js files

Directly in Java Call js code

java calls javascript file method

JAVA directly on the server backend Run JavaScript method

The above is the detailed content of How to run js code sharing in java program. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template