Java中如何执行JavaScript

来源:互联网 发布:好听的女声网络歌曲 编辑:程序博客网 时间:2024/06/05 10:18

   我们在进行WEB开发的时候,经常需要在客户端编写一些js函数,这些函数如果需要在服务端执行的话,如果重新编写的话,就显得十分冗余,因此我们可以尝试在服务端,直接执行js,这样的话就可以避免重复劳动,同时,调用js也有个函数,就是非常方便调试。

最关键的一步就是调用

conext.evaluateString(scope, "script内容", "", 1, null); 将js装入服务端容器中 而这个往往只需要初始化一次即可

 

下面给出一个具体的用例,供参考:

/*
  * (non-Javadoc)
  *
  * @see ygfmis.fw.system.scripting.ScriptEvaluator#evaluateExpression(java.lang.String,
  *      java.util.Map, java.lang.Class)
  */
 public Object evaluateExpression(String expr) {
  initJavaScriptContext();
  java.lang.Object eval;
  try {
   if (log.isDebugEnabled()) {
    log.debug("Evaluating javascript expression:" + expr);
   }
   eval = conext.evaluateString(scope, expr, "", 1, null);
   if (log.isDebugEnabled()) {
    log.debug("JavaScriptEvaluator->Javascript expression " + expr
      + " is evaluated to " + eval);
   }
   return eval;

  } catch (Exception jse) {

   if (log.isErrorEnabled()) {
    log.error("JavaScriptEvaluator -> The result of expression "
      + expr + " can't be evaluated - error message="
      + jse.getMessage(), jse);
   }
   throw new ScriptException("Result cannot be evaluated", jse);
  } finally {
   //org.mozilla.javascript.Context.exit();
  }
 }
 
 private static org.mozilla.javascript.Context conext = null;
 
 private static Scriptable scope = null;
 
 /**
  * YGFMISWeb的地址.
  */
 private static String ygFmisWebUrl = null;
 
 /**
  * 初始化.
  */
 private static void initJavaScriptContext() {
  if (conext == null) {
   conext = org.mozilla.javascript.Context.enter();
   scope = conext.initStandardObjects(null);
   try {
    conext.evaluateString(scope, getJavaScriptContext(), "", 1, null);

    //这里可以多次装载多个js文件
   } catch (JavaScriptException e) {
    e.printStackTrace();
   }
  }
 }
 
 /**
  * 读取js文件.
  * @return 文件内容
  */
 private static String getJavaScriptContext() {
  LineNumberReader reader = null;
  try {
   reader = new LineNumberReader(new FileReader(new File("js文件对应的目录地址"     + File.separatorChar + StringUtil.replaceAllChar("js/clientfuncs/billinput.js", '/', File.separatorChar))));
   String str = "";
   StringBuffer buffer = new StringBuffer();
   while ((str = reader.readLine()) != null) {
    buffer.append(str).append("/n");
   }
   return buffer.toString();
  } catch (Exception e) {
   e.printStackTrace();
   return null;
  }
 }

 

原创粉丝点击