Java Reference
In-Depth Information
At this point, you can visualize the state of the
ScriptContext
instance as shown in
Figure
3-1
.
Figure 3-1.
A pictorial view of an instance of the SimpleScriptContext class
You can perform several operations on a
ScriptContext
. You can set a different
value for an already stored key using the
setAttribute(String name, Object value,
int scope)
method. You can remove a key-value pair using the
removeAttribute(String
name, int scope)
method for a specified key and a scope. You can get the value of a key
in the specified scope using the
getAttribute(String name
,
int scope)
method.
The most interesting thing that you can do with a
ScriptContext
is to retrieve a
key value without specifying its scope using its
getAttribute(String name)
method. A
ScriptContext
searches for the key in the engine scope
Bindings
first. If it is not found in
the engine scope, the
Bindings
in the global scope is searched. If the key is found in these
scopes, the corresponding value from the scope, in which it is found first, is returned. If
neither scope contains the key,
null
is returned.
In your example, you have stored the key named
year
in the engine scope as well as
in the global scope. The following snippet of code returns 1969 for the key
year
from the
engine scope as the engine scope is searched first. The return type of the
getAttribute()
method is
Object
.
// Get the value of the key year without specifying the scope.
// It returns 1969 from the Bindings in the engine scope.
int yearValue = (Integer)ctx.getAttribute("year");
You have stored the key named
name
only in the global scope. If you attempt to
retrieve its value, the engine scope is searched first, which does not return a match.
Subsequently, the global scope is searched and the value
"Boni"
is returned, as shown:
// Get the value of the key named name without specifying the scope.
// It returns "Boni" from the Bindings in the global scope.
String nameValue = (String)ctx.getAttribute("name");
Search WWH ::
Custom Search