本文目录一览:
java程序中运行js脚本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class ExecJs {
/**
* 记录日志类
*/
private Logger log = Logger.getLogger(ExecJs.class);
/**
* 后置处理,执行js脚本
* @param js
* @throws Exception
*/
public void execJs(String js, MapString,Object map) throws Exception {
if (log.isDebugEnabled()) {
log.debug("execJs js : " + js);
IteratorEntryString, Object it = map.entrySet().iterator();
while (it.hasNext()) {
EntryString, Object entry = (EntryString, 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
}
}
js怎么调用JAVA方法
一般的浏览器中是无法通过js调用本地java程序的,但是可以调用嵌入到网页的applet的方法。交互方式如下:
applet codebase = "." width = "400" height = "400"
name= "MyApplet" code = "test.applets.MyApplet1.class"
script
// js访问applet属性:document.appletName.appletField (属性必须是public的)
// js访问Applet方法:document.appletName.appletMethod (方法必须是public的)
function showLable{
// 调用test.applets.MyApplet1类的invokeByJS方法
document.applets["MyApplet"].invokeByJS('myvalue');
}
/script
如何实现js调用java函数
var xmlHttp; //创建XMLHttpRequest对象 function createXMLHttpRequest(){ if(window.ActiveXObject){ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } else if(window.XMLHttpRequest){ xmlHttp = new XMLHttpRequest(); } } function startRequest(){ createXMLHttpRequest(); try{ xmlHttp.onreadystatechange = handleStateChange; xmlHttp.open("GET", "xxxxxxx.action",true); xmlHttp.send(null); }catch(exception){ alert(exception.message); } } function handleStateChange(){ if(xmlHttp.readyState == 4){ if (xmlHttp.status == 200 || xmlHttp.status == 0){ // 取得返回字符串 var resp = xmlHttp.responseText; // 然后可以把resp构造返回JSON对象或者XML对象 } }}JS中调用 startRequest()方法,handleStateChange()方法中获得JAVA类的返回数据