Java 中使用rhno引擎,运行JavaScript脚本,实现变量的交互、引入、传递

2 篇文章 0 订阅
2 篇文章 0 订阅

尝试了一下在Java 中使用rhino引擎,运行JavaScript脚本,现在将使用方法整理如下:


1.下载rhino引擎的文件,最后我获取到的是一个 js.jar 文件


2.将这个文件添加到 工程的 Libraries 中去,如图:

  


3.运行脚本并测试


//package test;

//导入的这两个包的路径和网上的有些不同,网上的时sun开头的
//但是我经过尝试发现,不存在这个包,因此后来修改成如下路径
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;


public class Test {
      //一个简单的类,用于测试
      public static class HelloWorld {
		String s = "Hello World";
		public void sayHello(){
			System.out.println(s);
                }
		public void putstring(String s1){
			System.out.println(s1);
               }   
      }
    
	public static void main(String[] args) {
     			
    	//创建类对象
    	HelloWorld hello = new HelloWorld();
        
       //使用rhino的一些初始化操作
        Context cx = Context.enter();
    	try{
    		Scriptable scope = cx.initStandardObjects();
    		//写入JS脚本
    		String str="function a(x,y){var result; while(x<69600){x=x+y;y++;}return x} x =10;y=20; a(x,y);";
               //执行脚本
               Object result = cx.evaluateString(scope, str, null, 1, null);

               //实现JAVA中的变量与js中的变量绑定
               //使用的是 put 方法 ,第一个参数为 JS中的变量名称,第三个参数为java中的对象
               scope.put("script_hello",scope, hello);
                
                //一段经过混淆的js代码
                str="(function(p,a,c,k,e,r){e=String;if('0'.replace(0,e)==0){while(c--)r[e(c)]=k[c];k=[function(e){return r[e]||e}];e=function(){return'^$'};c=1};
                        while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('x*y;',[],1,''.split('|'),0,{}))"; 
                str = "script_hello.putstring("+ str + ")";

               //调用JAVA的类方法
               cx.evaluateString(scope, str, null, 1, null);        
    		 
    		 //输出结果
    		System.out.println(Context.toString(result));
    		} 
    	finally{
    		Context.exit();
    		}
    }
}

	


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值