print("sys.isVariableDefined(\"headerList2\"):" + sys.isVariableDefined("headerList2"));
sys (即SystemUtilities) 的getVar( )的取值顺序是:先从FunctionContext中取,再从Scraper的Context中取。
<var/>的取值是:会从传入的Context实例中取,如果<var/>标签中<Fuction/>标签中,当然传入的是FunctionContext。
SystemUtilities.java
public Variable getVar(String varName) {
CallProcessor runningFunction = scraper.getRunningFunction();
ScraperContext activeContext = runningFunction == null ? scraper.getContext() : runningFunction.getFunctionContext();
return activeContext.getVar(varName);
}
SetContextVar.java只有下面这个invoke方法(看到interpreter得到的Context是当前Context而不只是scraper.getContext()得到的Context)
这是一个BeanShell的预定义方法(关于BeanShell中预定义方法的使用,参见BeanShell的用户手册的Compiled Commands一节)。
public static void invoke(Interpreter interpreter, CallStack callstack, String name, Object value) {
try {
ScraperContext context = (ScraperContext) interpreter.get(ScriptEngine.CONTEXT_VARIABLE_NAME);
if (context != null) {
context.setVar(name, value);
}
} catch (EvalError e) {
throw new ScriptException("Cannot get web-Harvest context from interpreter: " + e.getMessage(), e);
}
}
下面是BeanShell脚本引擎的创建过程堆栈:
org.webharvest.runtime.scripting.BeanShellScriptEngine.BeanShellScriptEngine(Map)
org.webharvest.definition.ScraperConfiguration.createScriptEngine(Map, String)
org.webharvest.definition.ScraperConfiguration.createScriptEngine(Map)
org.webharvest.runtime.processors.CallProcessor.CallProcessor(CallDef, ScraperConfiguration, Scraper)
在构造CallProcessor时传入的就是FunctionContext:
public CallProcessor(CallDef callDef, ScraperConfiguration configuration, Scraper scraper) {
super(callDef);
CallProcessor runningFunction = scraper.getRunningFunction();
ScraperContext callerContext = runningFunction == null ? scraper.getContext() : runningFunction.getFunctionContext();
try {
this.functionContext = new ScraperContext(scraper, callerContext);
this.scriptEngine = configuration.createScriptEngine(functionContext);
this.callDef = callDef;
} catch (Exception e) {
e.printStackTrace();
}
}
org.webharvest.runtime.variables.ListVariable headerList = new org.webharvest.runtime.variables.ListVariable();
String tmpHeader = "";
for ( org.webharvest.utils.KeyValuePair item : http.headers ) {
tmpHeader = "header (" + item.getKey() + ") is: "+ item.getValue() ;
headerList.addVariable(new org.webharvest.runtime.variables.NodeVariable(tmpHeader));
}
print("====headerList:" + headerList);
sys.defineVariable("headerList2", headerList);
//print("sys.isVariableDefined(\"headerList2\"):" + sys.isVariableDefined("headerList2"));
//print("====headerList2:" + headerList2);
//print("====sys.getVar(\"headerList2\"):" + sys.getVar("headerList2"));
<loop item="respHeader" index="i">
<list>
<var name="headerList2"/>
</list>
<body>
<log message=" ${i} : ${respHeader}" level="debug"/>
</body>
</loop>