Chris Greenhalgh, 2007-02-06
For some applications and for intial development prototyping it may
be preferred by some developers to use a scripting language to develop
controllers (which may then be ported to native Java controllers).
The tutorial has examples of using the Apache Jakarta Bean
Scripting Framework (now becoming a JCP standard) to create
controllers whose main functionality is specified by a script.
<bean id="firstScriptController"
class="equip2.webapptutorial.scripting.ScriptingAbstractController">
<property name="scriptResource" value="equip2/webapptutorial/scripting/first_script.py" />
<property name="dataspace"><ref bean="dataspace"/></property>
</bean>
The property 'scriptResource'
is a Java resource path to the script file which is called to implement
the standard abstract controller method:
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws Exception;
In the tutorial example, the build process copies script file(s)
from the src/ directory
hierarchy into the build
and hence to the web applications classes/
directory hierarchy. In this case, the script file is src/equip2/webapptutorial/scripting/first_script.py:
# this is the body of a function with signature (thisref, request, response)
# it handles a standard spring request, and should return a ModelAndView
# ModelAndView
from org.springframework.web.servlet import ModelAndView
mav = ModelAndView()
mav.viewName = 'scripting/first_script_success'
model = mav.model
model.put('answer',42)
# example of accessing dataspace
session = thisref.getDataspace().getSession()
session.begin()
from equip2.core import QueryTemplate
from equip2.webapptutorial.db import Player
from java.lang import Class
query = QueryTemplate(Class.forName('equip2.webapptutorial.db.Player'))
players = session.match(query)
session.end()
model.put('players', players)
return mav
The script is run using BSFs apply
method, which converts it into the body of an unnamed function and
calls it with specified arguments [actually this is currently broken
for Jython, so we work around it ourselves], but it generally looks the
same. This example shows both creating a ModelAndView for rendering,
and accessing the application dataspace (via the property 'dataspace' defined in the
scripting controller class).
The final view, as expected, is rendered by the JSP scripting/first_script_success.jsp
Note that the script execution currently re-reads the script file
every time it is called, so:
Common script support is provided by equip2.webapptutorial.scripting.ScriptManager.
The Script Manager method(s) callScript/callScriptLiteral could also be
used to introduce scripting into other point in an application.
Refer to the BSF documentation for details on how to add support for
other scripting languages (the main thing should be to copy the
relevant JARs into the Web application on deployment).
2007-02-06