java调用javascript实例

/*
* JSExploration.java
* @author Lucky
* Created on November 4, 2008, 11:16 AM
*/

package com.pengzhoushuo.js;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.Properties;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;


/**
* this class provide a way for java class to call java script code<p>
*
*/
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 = null;
  InputStream is = null;
  try {
   is = this.getClass().getClassLoader().getResourceAsStream(filename);
   reader = new LineNumberReader(new InputStreamReader(is));
   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;
  }finally{
   if(reader != null)
    try {
     reader.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    if(is != null)
     try {
      is.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
  }
}

public Scriptable getScope() {
  return scope;
}

/**
  * 调用JAVASCRIPT对密码进行加??
  * @param key 密码明文
  * @return 密码密文
  */
public static String getKey(String key) { 
          //javacript file path
         String filename = "com/pengzhoushuo/js/RSAKey.js";
         JSExploration jsExploration = new JSExploration();     
         Object result = jsExploration.runJavaScript(filename);     
         Scriptable scope = jsExploration.getScope();      

          //getKey是javascript中对应的方法名
         Function sum = (Function) scope.get("getKey", scope);  
         Object isPrime = sum.call(Context.getCurrentContext(), scope, sum, new Object[] {key});       
         return Context.toString(isPrime);

}

public static void main(String[] args){
  System.out.println(JSExploration.getKey("a1234567"));
}
} 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值