public
class
ExecJs {
/**
* 记录日志类
*/
private
Logger log = Logger.getLogger(ExecJs.
class
);
/**
* 后置处理,执行js脚本
* @param js
* @throws Exception
*/
public
void
execJs(String js, Map<String,Object> map)
throws
Exception {
if
(log.isDebugEnabled()) {
log.debug(
"execJs js : "
+ js);
Iterator<Entry<String, Object>> it = map.entrySet().iterator();
while
(it.hasNext()) {
Entry<String, Object> entry = (Entry<String, Object>) it.next();
log.info(
"EXECJS MAP : "
+ entry.getKey() +
"---"
+ entry.getValue());
}
// end while
}
// end if
if
(
""
.equals(js) || js ==
null
) {
log.info(
"EXECJS ERROR : JAVASCRIPT CONTENT IS NULL"
);
}
else
if
(map ==
null
|| map.size()<=
0
){
log.info(
"EXECJS ERROR : MAP CONTENT IS NULL"
);
}
else
{
// 获取脚本引擎
ScriptEngineManager mgr =
new
ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName(
"javascript"
);
// 绑定数据
ScriptContext newContext =
new
SimpleScriptContext();
Bindings bind = newContext.getBindings(ScriptContext.ENGINE_SCOPE);
bind.putAll(map);
try
{
engine.setBindings(bind, ScriptContext.ENGINE_SCOPE);
engine.eval(js);
}
catch
(Exception e) {
log.info(
"EXECJS EXCEPTION : EXECUTE JAVASCRIPT EXCEPTION"
, e);
throw
(e);
}
// end try
}
// end if
}
}
调用例子
boolean flag = false;
String js = “var a = 1; var b = a + aKey;println(b);”;
Map<String,Object> map = new HashMap<String,Object>();
map.put(“aKey”, “aValue”);
try {
flag = execJs.execJs(js, map);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String js = “var a = 1; var b = a + aKey;println(b);”;
Map<String,Object> map = new HashMap<String,Object>();
map.put(“aKey”, “aValue”);
try {
flag = execJs.execJs(js, map);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}