本文目錄一覽:
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類的返回數據
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/188422.html