在java中使用Rhino执行js

test.js

function Transfer(content, baseurl)
{
 //TODO
 var result = "";
 if(content.indexOf('<body>') > -1 && content.indexOf('</body>') > -1)
 {
     result = content.substring(content.indexOf('<body>') + 6,content.indexOf('</body>'));
 }
 return result;
}

 java中的代码

 public void excueteJs() {
        Context ct = Context.enter();
        Scriptable scope = ct.initStandardObjects();
        String filename = "E:\\test\\test.js";
        String jsFunction = "Transfer";
        try {
            LineNumberReader reader = new LineNumberReader(new FileReader(filename));

            String temp = null;
            StringBuffer sb = new StringBuffer();
            while ((temp = reader.readLine()) != null) {
                sb.append(temp).append("\n");
            }
            ct.evaluateString(scope, sb.toString(), null, 1, null);
            Object result = ct.evaluateString(scope, jsFunction, null, 1, null);
            System.out.println("my"+result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ct.exit();
        }
    }

  在给个复杂点的例子, 没有什么逻辑,纯技术展示

JSFunction.java:

package co.test;   
  
import org.mozilla.javascript.Function;   
  
public class JSFunction  //extends ScriptableObject   
{   
 private String name;    
    
 private Function handle;   
    
 public void setHandler(Function func)   
 {   
  this.handle = func;   
 }   
    
 public Function getHandler()   
 {   
  return this.handle;   
 }   
  
    
 public JSFunction(String s)   
 {   
  this.name = s;   
 }    
    
 public static void print(String s)   
 {   
  System.out.println(s);   
 }   
  
 public String getName() {   
  return name;   
 }   
 public void setName(String name) {   
  this.name = name;   
 }   
  
}   
  

 JSExploration.java:

package co.test;   
  
import java.io.FileReader;   
import java.io.LineNumberReader;   
  
import org.mozilla.javascript.Context;   
import org.mozilla.javascript.Function;   
import org.mozilla.javascript.Scriptable;   
  
public class JSExploration   
{   
    private Context cx;   
  
    private Scriptable scope;   
  
    public JSExploration()   
    {   
        this.cx = Context.enter();   
        this.scope = cx.initStandardObjects();   
    }   
  
    public Object runJavaScript(String filename)   
    {   
        String jsContent = this.getJsContent(filename);   
        Object result = cx.evaluateString(scope, jsContent, filename, 1, null);   
        return result;   
    }   
  
    private String getJsContent(String filename)   
    {   
        LineNumberReader reader;   
        try  
        {   
            reader = new LineNumberReader(new FileReader(filename));   
            String s = null;   
            StringBuffer sb = new StringBuffer();   
            while ((s = reader.readLine()) != null)   
            {   
                sb.append(s).append("/n");   
            }   
            return sb.toString();   
        }   
        catch (Exception e)   
        {   
            // TODO Auto-generated catch block   
            e.printStackTrace();   
            return null;   
        }   
    }   
  
  
    public Scriptable getScope()   
    {   
        return scope;   
    }   
  
    public static void main(String[] args)   
    {   
        String filename = System.getProperty("user.dir") + "/jsmap.js";   
        JSExploration jsExploration = new JSExploration();   
        Object result = jsExploration.runJavaScript(filename);   
        Scriptable scope = jsExploration.getScope();   
        Scriptable obj = (Scriptable) scope.get("obj", scope);   
        System.out.println("obj.a == " + obj.get("a", obj));   
        Scriptable b = (Scriptable) obj.get("b", obj);   
        System.out.println("b[0] == " + b.get(0, b));   
        Boolean flag = (Boolean) scope.get("flag", scope);   
        System.out.println(flag);   
  
        Scriptable myobj = (Scriptable) scope.get("obj", scope);   
        Boolean myflag = (Boolean) scope.get("flag", scope);   
        System.out.println(myflag);   
  
        Scriptable jsFunction = (Scriptable) scope.get("jsFunction", scope);   
        Function fc = (Function) jsFunction.get("handler", jsFunction);   
        Object isPrime = fc.call(Context.getCurrentContext(), jsFunction, fc, new Object[] { "this is my test" });   
    }   
}   
  

 js脚本:jsmap.js

 

  1. var swingNames = JavaImporter();   
  2.   
  3. swingNames.importPackage(Packages.java.lang);   
  4. swingNames.importPackage(Packages.co.test);   
  5.   
  6. obj = {a:1, b:['x','y']}   
  7. next = isPrime   
  8. flag = isPrime(5)   
  9. with (swingNames) {   
  10.  System.out.println("in javascript");   
  11.  JSFunction.print("in JSFunction");   
  12.   jsFunction = new JSFunction("lichunlei");   
  13.  var name = jsFunction.getName();   
  14.  System.out.println("get name from java source: " + name);   
  15.  jsFunction.setHandler(log);    
  16. }    
  17.   
  18. java.lang.System.out.println("not use swingNames");   
  19. function isPrime (num)   
  20. {   
  21.  java.lang.System.out.println("in isPrime(num)");   
  22.     if (num <= 1) {   
  23.         java.lang.System.out.println("Please enter a positive integer >= 2.")   
  24.         return false  
  25.     }   
  26.        
  27.     var prime = true  
  28.     var sqrRoot = Math.round(Math.sqrt(num))   
  29.        
  30.     for (var n = 2; prime & n <= sqrRoot; ++n) {   
  31.         prime = (num % n != 0)   
  32.     }   
  33.        
  34.     return prime   
  35. }   
  36.   
  37. function log(msg)   
  38. {   
  39.  java.lang.System.out.println("in function log: " + msg);   
  40. }   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值