Using BSF in servlets or applications is also quite simple. In order to provide an application with scripting support, you need to import the BSF class hierarchy and instantiate a BSFManager
object. After instantiating the BSFManager
, you register or declare any Java objects to be made available within the scripting engine. Then call either one of the eval()
or exec() BSFManager
methods (depending on whether you want to evaluate a script and have the value of the evaluation returned, or execute a script). Alternatively, you can call the loadScriptingEngine()
method in order to get an object implementing the BSFEngine
interface for the desired scripting language. You can then call the exec()
or eval()
methods of BSFEngine
to run the script.
Additionally, BSF declares an object named bsf
within a scripting engine's execution context, which represents the BSFManager
that is associated with the scripting engine. This object provides all of the methods and properties associated with the BSFManager
to the script. However, the most used method within scripts is usually lookupBean()
, which is used to access objects in BSF's object registry.
The most important methods within the BSFManager
are:
BSFManager
() - the BSFManager
constructoreval()
- used to evaluate a script and return its valueexec()
- used to execute a script loadScriptingEngine()
- used to return a BSFEngine
for the desired scripting languageregisterBean()
- adds an object to BSF's object registrylookupBean()
- retrieves an object from BSF's object registrydeclareBean()
- creates an implicit object in the context of any loaded scripting language, which does not have to be accessed via lookupBean()
Other, less often used methods within the BSFManager
are:
apply()
- used to call anonymous functionscompileExpr()
- used to compile an expression into a CodeBuffer
objectcompileScript()
- similar to compile expression, used to compile scripts into CodeBuffer
objectscompileApply()
- similar to both of the above - used to compile anonymous functions into CodeBuffer
objects
For the curious, the CodeBuffer
is a class provided by BSF for storing generated Java code.
The BSFManager
exec()
, eval()
, and apply()
methods (as well as their compile counterparts) are wrappers over the equivalent methods presented by the BSFEngine
interface. If the programmer explicitly loads a scripting engine via loadScriptingEngine()
, they can use the exec()
or eval()
methods of the resulting BSFEngine
as appropriate.