1.
Document mydoc = null;
public BareBonesBrowserLaunch(String url) throws MalformedURLException, IOException{
mydoc = Jsoup.parse(new URL(url),30000);//利用Jsoup实现document树
}
2.
public Element getElementById(){//实现document的方法
System.out.println("Java println:\t"+mydoc.getElementById(id));
return mydoc.getElementById(id);//返回的是Element对
}
3.java中调用js
/**
* 调用js中的方法
* @throws Exception
*/
public static void ExcuteJs(String url) throws Exception{
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine se = sem.getEngineByName("JavaScript");
String path =this.getServlet().getServletContext().getRealPath("/WEB-INF/js/jituan.js");
File f = new File(path);
Reader d = new InputStreamReader(new FileInputStream(f));
se.eval(d);
Invocable inv = (Invocable) se;
se.put("document", new BareBonesBrowserLaunch(url));关联对象,很重要,关联javascript的document对象为BareBonesBrowserLaunch,即自己实现的document对象
String value = (String) inv.invokeFunction("load",url);
System.out.println(value);
//直接调用js方法
// ScriptEngineManager factory = new ScriptEngineManager();
// ScriptEngine scriptEngine = factory.getEngineByName("JavaScript");
// try {
// // String script = "function load(url){var dom=null;if(document.implementation && document.implementation.createDocument){dom=new window.XMLHttpRequest();}else{dom=new ActiveXObject(\"Microsoft.XMLHttp\");} dom.open(\"GET\",url,false); dom.send(null); return dom;}";
//
// // se.eval(script);
// Invocable inv2 = (Invocable) se;
// String res=(String)inv.invokeFunction("load",url);
//
// System.out.println(res);
// }catch(Exception e){e.printStackTrace();}
}