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"));
}
} 
 

你可能感兴趣的:(JavaScript,java)