当前位置: 移动技术网 > IT编程>开发语言>Java > Java中使用JavaScript脚本的方法步骤

Java中使用JavaScript脚本的方法步骤

2020年06月14日  | 移动技术网IT编程  | 我要评论

简介 nashorn

nashorn 一个 javascript 引擎。

从jdk 1.8开始,nashorn取代rhino(jdk 1.6, jdk1.7)成为java的嵌入式javascript引擎。nashorn完全支持ecmascript 5.1规范以及一些扩展。

它使用基于jsr 292的新语言特性,其中包含在jdk 7中引入的 invokedynamic,将javascript编译成java字节码。

与先前的rhino实现相比,这带来了2到10倍的性能提升。

使用方式

1. 编写javascript脚本

列:javascript方法使用java对象执行方法获取返回值。

function scriptfunction(obj){
 var a = 1;
 var b = 2;
 return obj.sum(a,b);
}
scriptfunction(obj);//调用该方法

该脚本变量定义为 string script1;

2. 创建javascript容器用户存储脚本 scirptcontainer.java

public class scirptcontainer {
 
 
 public static scriptengine engine;//脚本引擎
 
 static {
 scriptenginemanager manager = new scriptenginemanager();//脚本引擎管理
 engine = manager.getenginebyname("nashorn");//获取nashorn脚本引擎
 engine.getcontext().getwriter();//获取正文并且写入
 }
 
 private concurrenthashmap<integer, compiledscript> scripts = new concurrenthashmap<>();//脚本存储容器
 
 
 public compiledscript getcompiledscript(string script) throws scriptexception{
 //判断脚本是否为空
 if(script == null || "".equals(script)){
 throw new scriptexception("javascript empty");
 }
 //获取脚本hash
 int hashcode = script.hashcode();
 //从容器中获取脚本
 compiledscript compiledscript = scripts.get(hashcode);
 if(compiledscript == null){
 //容器中无脚本创建脚本对象
 compilable compilable = (compilable) engine;
 //编译javascript脚本
 compiledscript = compilable.compile(script);
 //脚本对象存入容器中
 scripts.put(hashcode, compiledscript);
 }
 return compiledscript;
 } 
}

3. java执行javascript脚本

public class scripthandler {
 
 //创建容器对象
 private scirptcontainer scirptcontainer = new scirptcontainer();
 
 //需要执行的对象
 string js1 = "function scriptfunction(obj){ var a = 1; var b = 2; return obj.sum(a,b); } scriptfunction(obj);";
 
 @test
 public void test() throws scriptexception{
 //获取脚本对象
 compiledscript c1 = scirptcontainer.getcompiledscript(js1);
 //创建参数绑定
 bindings bindings = scirptcontainer.engine.createbindings();
 //obj参数绑定sumtest类
 bindings.put("obj", new sumtest());
 //执行javascript脚本并且打印返回值
 system.out.println(c1.eval(bindings));
 }
}

注意事项:

  • 脚本中scriptfunction(obj);是必须存在,否则不会执行方法.
  • 脚本中可以创建java对象,需要全类名如var map = new java.util.hashmap();

到此这篇关于java中使用javascript脚本的方法步骤的文章就介绍到这了,更多相关java使用javascript脚本内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

作者: simplewu

出处:https://www.cnblogs.com/simplewu/p/12598442.html

本站使用「simplewu by 4.0」创作共享协议,转载请在文章明显位置注明作者及出处。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网