A Dynamic MVC Development Approach Using Java 6 Scripting, Groovy, and WebLEAF
A flexible and dynamic development environment is currently a great concern, and even though scripting languages have shown they can be of help, we still need to create applications that can be maintained easily while giving us what we need during development. Recognizing the usefulness of scripting languages, Java SE 6 introduced the new Java Scripting API: a language-independent framework that allows developers to use scripting engines from Java code. With this new API, we can take advantage of the characteristics of the scripting languages where we need them most, while being able to use our well-known Java bag of tools.
In this article, we show an example of new architectures made possible with this API, developing a web application based on the Model View Controller (MVC) architecture using Groovy, a dynamic scripting language based on the Java platform, to implement the business logic (the "model"), and using different technologies to implement the interface (the "view"). As the "controller" part of our application, we use WebLEAF, an open source framework to develop web applications based on the MVC architecture. In order to make the example "self contained," we use an embeddable database written in Java, HSQLDB, which allows us to create a sample database with just two text files. To implement the view logic that generates the HTML user interface, the technologies we use in the article are XSLT, a language for transforming XML documents into other XML documents specified by the W3C, and FreeMarker, a popular Java template engine that can also handle XML as input.
The example we are going to develop consists of a page that displays a list of the items of a database and allows us to select one item so we can see its detailed information. It is a fairly simple example, but enough to see the different pieces of the architecture we want to demonstrate.
We are going to follow the example step by step, but you can check the Resources section for the full sample code.
Setting Up the Application Skeleton
The first step is to create the basic structure of a standard web application and add the WebLEAF library version 3, as that is the version that provides support for the new Java Scripting API:
- We start by creating a directory called Test.
- We create a directory inside Test called WEB-INF.
- Inside WEB-INF, we create a directory called lib and another directory called classes.
- We download the WebLEAF 3 .jar file and put it in Test/WEB-INF/lib.
- We create the standard servlet descriptor file Test/WEB-INF/web.xml as displayed below:
<?xml version="1.0"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
<web-app>
<!--
WebLEAF controller servlet configuration
-->
<servlet>
<servlet-name>WebLEAFController</servlet-name>
<servlet-class>org.leaf.LEAFManager</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- End controller servlet -->
</web-app>
This configuration tells the servlet container to instantiate a
WebLEAF controller servlet and start it up when the context is
started. Pay attention that the <load-on-startup>
value is set to 2. We will see in a minute the reason behind this
not being a 1.
- To finish this part, we create the WebLEAF descriptor file, Test/WEB-INF/Test.leaf.conf, by copying this:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE WADSET SYSTEM "http://www.uib.es/leaf/LEAFwad.dtd">
<WADSET>
<WAD
NAME="Test"
INIT_MODE="INITS_ON_START_UP"
XML_ALLOW_SHOW="TRUE"
XSLT_NO_CACHE="TRUE"
>
</WAD>
</WADSET>
That gives us a minimum configuration to start with. But don't
worry, we have just started!
Creating the Database
We are now going to add the database that will be used in our tests.
- As mentioned previously, we will use HSQLDB, so the first steps are to download the latest 1.8.0 HSQLDB JDBC driver, extract it, and add hsqldb.jar to Test/WEB-INF/lib.
- After that, we need to create a small test database with some dummy data in it; so we add the directory Test/WEB-INF/db and put in it two files. The first is named Test.properties and has this content:
#HSQL Database Engine
#Fri Apr 20 18:52:47 CEST 2007
hsqldb.script_format=0
runtime.gc_interval=0
sql.enforce_strict_size=false
hsqldb.cache_size_scale=10
readonly=false
hsqldb.nio_data_file=true
hsqldb.cache_scale=14
version=1.8.0
hsqldb.default_table_type=memory
hsqldb.cache_file_scale=1
sql.compare_in_locale=false
hsqldb.log_size=200
modified=no
hsqldb.cache_version=1.7.0
hsqldb.original_version=1.7.1
hsqldb.compatible_version=1.8.0
The second file is called Test.script and has this
content:
CREATE SCHEMA PUBLIC AUTHORIZATION DBA
CREATE MEMORY TABLE TTST_ITEM(ITE_CODE CHAR(32) NOT NULL PRIMARY KEY,ITE_NAME VARCHAR(100) NOT NULL,ITE_DESCRIPTION VARCHAR(300))
CREATE USER SA PASSWORD ""
GRANT DBA TO SA
SET WRITE_DELAY 60
SET SCHEMA PUBLIC
INSERT INTO TTST_ITEM VALUES('06e8da2682ce842b01a47de7823ec779','Parents','Links for parents')
INSERT INTO TTST_ITEM VALUES('1ab94df54312961a015749157fe05097','Web related','Item description')
INSERT INTO TTST_ITEM VALUES('1acc5e9d4312961a0157491547be91fa','Source control','That must be about source')
INSERT INTO TTST_ITEM VALUES('1ad80b204312961a015749159fe5205a','JBuilder Plugins','Plugin? What's that')
As the HSQLDB driver requires a full path that is known only at deploy time, we will make use of the AutoConfigurer servlet that comes with WebLEAF to self-configure this path.
- To do that, we create the file called Test/WEB-INF/classes/webapp.properties with simply this line inside:
db.location=REAL_PATH/WEB-INF/db
- We then edit Test/WEB-INF/classes/web.xml to add the Autoconfigurer servlet, so it ends up as the sample below:
<?xml version="1.0"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
<web-app>
<!--
Autoconfiguration servlet
-->
<servlet>
<servlet-name>AutoConfigurer</servlet-name>
<servlet-class>org.leaf.util.AutoConfigurer</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>FILE_NAME.1</param-name>
<param-value>WEB-INF/classes/webapp.properties</param-value>
</init-param>
<init-param>
<param-name>NODES_NAME.1</param-name>
<param-value>db.location</param-value>
</init-param>
<init-param>
<param-name>PATTERN.1</param-name>
<param-value>(.*)/WEB-INF/(.*)</param-value>
</init-param>
<init-param>
<param-name>FORMAT.1</param-name>
<param-value>{0}WEB-INF/{1}</param-value>
</init-param>
</servlet>
<!-- End Autoconfiguration servlet -->
<!--
WebLEAF controller servlet configuration
-->
<servlet>
<servlet-name>WebLEAFController</servlet-name>
<servlet-class>org.leaf.LEAFManager</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- End controller servlet -->
</web-app>
The configuration above tells the Autoconfigurer
servlet to check the webapp.properties file and correct
the db.location property if it does not point to the
proper location. Moreover, the Autoconfigurer servlet
is loaded first, before the WebLEAF controller servlet,
thanks to having a lower load-on-startup value. That
guarantees that the Autoconfigurer servlet will have
the chance to fix the db.location property before the WebLEAF
controller servlet (LEAFManager) tries to access the
database.
Implementing the Business Logic in Groovy
Now that we have the database, we can start implementing the business logic. As mentioned previously, Java 6 adds support for scripting languages directly at the JVM level, with Mozilla's Rhino JavaScript engine included by default. WebLEAF takes advantage of these new features and allows us to implement the business logic using any supported scripting language. A Groovy engine is not shipped directly with Java 6, so in order to use it we must turn to the scripting java.net project, which hosts Script engines implementations for various languages.
- We also need Groovy, the language, so we download the latest release of Groovy, extract it and and add groovy-all-1.0.jar (not groovy-1.0.jar) to Test/WEB-INF/lib.
- We then download the jsr223-engines from the java.net scripting project, extract the content, locate the groovy-engine.jar file (it should be in the groovy/build directory inside the .jar) and add it to Test/WEB-INF/lib.
- Now that we have all the required libraries, we can add the code. We create the file Test/WEB-INF/scr/Item.groovy with the following code:
import groovy.xml.MarkupBuilder
import groovy.sql.Sql
import java.util.*
def ShowAllItems(builder,sql)
{
sql.eachRow(
"select * from TTST_ITEM",
{
itemToXML(builder,it)
}
);
}
def showItem(builder,sql,codeItem)
{
if(codeItem)
{
item =
sql.firstRow("select * from TTST_ITEM where ITE_CODE = ?"
,[codeItem])
if(item)
{
builder.ITEM_QUERY(Type:'Selected'){
itemToXML(builder,item)
}
}
}
}
def itemToXML(builder, item)
{
builder.ITEM( Code:item.ite_code,
Name:item.ite_name,
Description:item.ite_description
)
}
def show(param)
{
def bundle = ResourceBundle.getBundle("webapp");
def sql = Sql.newInstance("jdbc:hsqldb:"
+ bundle.getString("db.location")
+ "/Test;shutdown=true;ifexists=true"
, "sa","", "org.hsqldb.jdbcDriver")
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
def groovy = xml.ITEM_QUERY(Type:'All'){
ShowAllItems(xml,sql)
}
showItem(xml,sql,param.p_ite_code)
// Not efficient but it's just to prevent
// HSQLDB to block on the DB files
// when the servlet context is restarted
sql.execute("SHUTDOWN")
return writer.toString()
}
- To be able to use the Groovy script displayed above, we modify
the WebLEAF configuration file
(Test/WEB-INF/Test.leaf.conf) and add an
XMLOPERATIONthat references the script as the business logic implementation. After adding an operation that will answer to requests of the form.../showItems.fm, the configuration file should now look like this:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE WADSET SYSTEM "http://www.uib.es/leaf/LEAFwad.dtd">
<WADSET>
<WAD
NAME="Test"
INIT_MODE="INITS_ON_START_UP"
XML_ALLOW_SHOW="TRUE"
XSLT_NO_CACHE="TRUE"
>
<OPERATIONSET>
<SUFFIX VALUE="fm"/>
<XMLOPERATION
NAME="showItems"
DESCRIPTION="Shows all the items and the selected one"
CLASSNAME="org.leaf.XMLOperation"
>
<SOURCES
GLOBAL_TAG="XML_APP"
>
<SOURCE XML_SOURCE="xml/Labels.xml"/>
<SOURCE XML_SOURCE="script://scr/Item.groovy/show?w_"/>
</SOURCES>
</XMLOPERATION>
</OPERATIONSET>
</WAD>
</WADSET>
One of the important things to notice here is the URL to call the Groovy file (script://scr/Item.groovy/show?w_).
- To have a more real implementation, we also add the labels that will be used later to implement the view. We do this by creating the file Test/WEB-INF/xml/Labels.xml with the following XML content:
<LABELS
Title="Test application"
>
<ITEM
Title="Item Management"
FieldSetLegend="Item data"
SelectDefault="... select an item to display its data"
Code="Code"
Name="Name"
Description="Description"
/>
</LABELS>
- In order for our application to handle the requests ending with
the suffix ".fm", we also need to modify the
Test/WEB-INF/classes/web.xml configuration file to forward
such requests to the WebLEAF controller servlet. That implies
adding a
<servlet-mapping/>tag, like the one displayed at the bottom of this sample:
<?xml version="1.0"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
<web-app>
<!--
Autoconfiguration servlet
-->
<servlet>
<servlet-name>AutoConfigurer</servlet-name>
<servlet-class>org.leaf.util.AutoConfigurer</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>FILE_NAME.1</param-name>
<param-value>WEB-INF/classes/webapp.properties</param-value>
</init-param>
<init-param>
<param-name>NODES_NAME.1</param-name>
<param-value>db.location</param-value>
</init-param>
<init-param>
<param-name>PATTERN.1</param-name>
<param-value>(.*)/WEB-INF/(.*)</param-value>
</init-param>
<init-param>
<param-name>FORMAT.1</param-name>
<param-value>{0}WEB-INF/{1}</param-value>
</init-param>
</servlet>
<!-- End Autoconfiguration servlet -->
<!--
WebLEAF controller servlet configuration
-->
<servlet>
<servlet-name>WebLEAFController</servlet-name>
<servlet-class>org.leaf.LEAFManager</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- End controller servlet -->
<servlet-mapping>
<servlet-name>WebLEAFController</servlet-name>
<url-pattern>*.fm</url-pattern>
</servlet-mapping>
</web-app>
Now it is time to test the application for the first time.
- We configure our favorite servlet container to deploy the application using the test context. We could use any other name, but for simplicity's sake, we will suppose we are using "test" for the context name. The fastest way to deploy the application for some popular containers is to simply move the whole test directory to the auto-deploy directory, usually called webapps.
- We start up the container and access the URL
http://localhost:8080/test/showItems.fm(we need to modify the hostname, port, and context name if using something other than the defaults).
Our browser then displays something like Figure 1:
Figure 1. Snapshot of the application displaying the XML
produced by our business logic
If we check the Test/WEB-INF/db/Test.script file, we
can see that the data in the XML corresponds to the
Labels.xml file we just created, combined with an XML view
of the data stored in the database. We see the plain XML because we
have still not configured any view technology for the
XMLOPERATION, but that's what we are about to do in
the next step.
Implementing the View with FreeMarker
Now that we have implemented the business logic, let's add the view.
- As the first option, we implement the view with FreeMarker; so the first thing we need to do is to download the FreeMarker library, extract it and add freemarker.jar to Test/WEB-INF/lib.
- In order to process the XML with FreeMarker using XPath expressions, we use an XSLT engine, Jaxen, so we download the latest release of Jaxen, extract it and copy jaxen-*.jar to Test/WEB-INF/lib.
- After that, we edit the WebLEAF configuration file
(Test/WEB-INF/Test.leaf.conf) and simply add an
attribute (
FM_TEMPLATE="item.ftl") to theXMLOPERATIONso it looks like the one below:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE WADSET SYSTEM "http://www.uib.es/leaf/LEAFwad.dtd">
<WADSET>
<WAD
NAME="Test"
INIT_MODE="INITS_ON_START_UP"
XML_ALLOW_SHOW="TRUE"
XSLT_NO_CACHE="TRUE"
>
<OPERATIONSET>
<SUFFIX VALUE="fm"/>
<XMLOPERATION
NAME="showItems"
DESCRIPTION="Shows all the items and the selected one"
CLASSNAME="org.leaf.XMLOperation"
FM_TEMPLATE="item.ftl"
>
<SOURCES
GLOBAL_TAG="XML_APP"
>
<SOURCE XML_SOURCE="xml/Labels.xml"/>
<SOURCE XML_SOURCE="script://scr/Item.groovy/show?w_"/>
</SOURCES>
</XMLOPERATION>
</OPERATIONSET>
</WAD>
</WADSET>
- We then create the Test/WEB-INF/templates directory and add there two files (item.ftl and main.ftl) using the code samples displayed below:
<#-- Include the main macros -->
<#include "main.ftl">
<#-- Set the title for this part -->
<#assign Title> - ${Labels.ITEM.@Title}</#assign>
<#assign itemsList =
doc["XML_APP/ITEM_QUERY[@Type='All']"][0]>
<#assign selectedItem =
doc["XML_APP/ITEM_QUERY[@Type='Selected']"]>
<#if (selectedItem?size > 0)>
<#assign theItem = selectedItem.ITEM>
</#if>
<#-- Create the page using the main macro -->
<@Main_Page>
<fieldset>
<legend>${Labels.ITEM.@FieldSetLegend}</legend>
<form id="itemForm" name="itemForm" action="">
<select id="w_p_ite_code"
name="w_p_ite_code"
onchange="itemForm.submit();">
<option value="">${Labels.ITEM.@SelectDefault}</option>
<#if (itemsList.ITEM?size > 0)>
<#list itemsList.ITEM as Item>
<option value="${Item.@Code}"
<#if (theItem?exists &&
theItem.@Code==Item.@Code)>
selected
</#if>
>
${Item.@Name}
</option>
</#list>
</#if>
</select>
</form>
<#if (theItem?exists)>
<br />
<b>${Labels.ITEM.@Name}</b>:
${theItem.@Name}
<br />
<b>${Labels.ITEM.@Description}</b>:
${theItem.@Description}
</#if>
</fieldset>
</@Main_Page>
for the first (item.ftl), and then
<#-- Direct handle for the labels -->
<#assign Labels = doc.XML_APP.LABELS[0]>
<#-- Main reusable macro to create each page -->
<#macro Main_Page>
<!DOCTYPE html
PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<title>${Labels.@Title}${Title} (FREEMARKER)</title>
<meta http-equiv="Expires" content="now"/>
<meta http-equiv="Pragma" content="no-cache"/>
<meta http-equiv="Cache-Control" content="private"/>
</head>
<body>
<#nested>
<a href="./">Back to index</a>
</body>
</html>
</#macro>
for the second one (main.ftl).
- We start up the container again and access the URL http://localhost:8080/test/showItems.fm. This time we see something like Figure 2:
Figure 2. Snapshot of the application displaying list of items,
generated with FreeMarker
- If we select one of the items, we can see its data, as displayed in Figure 3:
Figure 3. Snapshot of the application displaying the details of
an item, generated with FreeMarker
Implementing the View with XSLT
We already implemented the view using FreeMarker, but, as we want to see several options, we will also implement it using XSLT. We already included an XSLT engine, Jaxen, to the classpath, so we don't need to add any other library.
- In this case, we just need to add a new
XMLOPERATION, which will use the same data as the previous one, but processing the XML with XSLT instead of with FreeMarker. As we want to have both operations working at the same time, we add another block of operations (anOPERATIONSET) that will answer under another suffix (.xsl). Our WebLEAF configuration file now looks like this:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE WADSET SYSTEM "http://www.uib.es/leaf/LEAFwad.dtd">
<WADSET>
<WAD
NAME="Test"
INIT_MODE="INITS_ON_START_UP"
XML_ALLOW_SHOW="TRUE"
XSLT_NO_CACHE="TRUE"
>
<OPERATIONSET>
<SUFFIX VALUE="fm"/>
<XMLOPERATION
NAME="showItems"
DESCRIPTION="Shows all the items and the selected one"
CLASSNAME="org.leaf.XMLOperation"
FM_TEMPLATE="item.ftl"
>
<SOURCES
GLOBAL_TAG="XML_APP"
>
<SOURCE XML_SOURCE="xml/Labels.xml"/>
<SOURCE XML_SOURCE="script://scr/Item.groovy/show?w_"/>
</SOURCES>
</XMLOPERATION>
</OPERATIONSET>
<OPERATIONSET>
<SUFFIX VALUE="xsl"/>
<XMLOPERATION
NAME="showItems"
DESCRIPTION="Shows all the items and the selected one"
CLASSNAME="org.leaf.XMLOperation"
XSLT_SOURCE="xsl/Item.xsl"
>
<SOURCES
GLOBAL_TAG="XML_APP"
>
<SOURCE XML_SOURCE="xml/Labels.xml"/>
<SOURCE XML_SOURCE="script://scr/Item.groovy/show?w_"/>
</SOURCES>
</XMLOPERATION>
</OPERATIONSET>
</WAD>
</WADSET>
- To handle those new requests, we need to again modify the
Test/WEB-INF/classes/web.xml configuration file, to
forward the requests ending in ".xsl" to the WebLEAF
controller servlet. After adding another
<servlet-mapping/>tag at the bottom, our Test/WEB-INF/classes/web.xml file looks like this:
<?xml version="1.0"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
<web-app>
<!--
Autoconfiguration servlet
-->
<servlet>
<servlet-name>AutoConfigurer</servlet-name>
<servlet-class>org.leaf.util.AutoConfigurer</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>FILE_NAME.1</param-name>
<param-value>WEB-INF/classes/webapp.properties</param-value>
</init-param>
<init-param>
<param-name>NODES_NAME.1</param-name>
<param-value>db.location</param-value>
</init-param>
<init-param>
<param-name>PATTERN.1</param-name>
<param-value>(.*)/WEB-INF/(.*)</param-value>
</init-param>
<init-param>
<param-name>FORMAT.1</param-name>
<param-value>{0}WEB-INF/{1}</param-value>
</init-param>
</servlet>
<!-- End Autoconfiguration servlet -->
<!--
WebLEAF controller servlet configuration
-->
<servlet>
<servlet-name>WebLEAFController</servlet-name>
<servlet-class>org.leaf.LEAFManager</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- End controller servlet -->
<servlet-mapping>
<servlet-name>WebLEAFController</servlet-name>
<url-pattern>*.fm</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WebLEAFController</servlet-name>
<url-pattern>*.xsl</url-pattern>
</servlet-mapping>
</web-app>
- Lastly, we add the XSLT implementation of the view by creating the file Test/WEB-INF/xsl/Item.xsl with the following XSLT code:
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="html"
indent="yes"
media-type="text/html"
encoding="iso-8859-1"
/>
<xsl:variable name="labels" select="/XML_APP/LABELS" />
<xsl:template match="/">
<html>
<head>
<META HTTP-EQUIV="Expires" CONTENT="now"/>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache"/>
<META HTTP-EQUIV="Cache-Control" CONTENT="private"/>
<title><xsl:call-template name="TITLE"/>(XSLT)</title>
</head>
<body>
<xsl:apply-templates/>
<a href="./">Back to index</a>
</body>
</html>
</xsl:template>
<xsl:template name="TITLE">
<xsl:value-of select="$labels/@Title"/>
<xsl:apply-templates mode="SUB_TITLE"/>
</xsl:template>
<xsl:template match="ITEM_QUERY[@Type='All']" mode="SUB_TITLE">
- <xsl:value-of select="$labels/ITEM/@Title"/>
</xsl:template>
<xsl:template match="ITEM_QUERY[@Type='All']">
<xsl:variable name="theItem"
select="/XML_APP/ITEM_QUERY[@Type='Selected']/ITEM"
/>
<fieldset>
<legend>
<xsl:value-of select="$labels/ITEM/@FieldSetLegend"/>
</legend>
<form id="itemForm" name="itemForm" action="">
<select id="w_p_ite_code"
name="w_p_ite_code"
onchange="itemForm.submit();"
>
<option value="">
<xsl:value-of select="$labels/ITEM/@SelectDefault"/>
</option>
<xsl:for-each select="ITEM">
<option value="{@Code}">
<xsl:if test="$theItem/@Code = @Code">
<xsl:attribute name="selected">
selected
</xsl:attribute>
</xsl:if>
<xsl:value-of select="@Name"/>
</option>
</xsl:for-each>
</select>
</form>
<xsl:if test="$theItem">
<b><xsl:value-of select="$labels/ITEM/@Name"/></b>:
<xsl:value-of select="$theItem/@Name"/>
<br />
<b><xsl:value-of select="$labels/ITEM/@Description"/></b>:
<xsl:value-of select="$theItem/@Description"/>
</xsl:if>
</fieldset>
</xsl:template>
</xsl:stylesheet>
- Now we can start up the container once again and access the URL http://localhost:8080/test/showItems.xsl. (Notice the suffix ".xsl" instead of ".fm".) We see exactly the same thing as before, and no, there is nothing wrong with that. It is exactly what we wanted to accomplish: producing the same exact result with two different view technologies.
Adding the Final Touch
Now that we have almost everything, we can add a small HTML file so we have a starting place to check all the operations.
- The starting place will be the file Test/index.html, which we will create by copying this HTML code:
<html>
<head>
<title>Test application</title>
</head>
<body>
Application to test the possibilities of
WebLEAF 3.0b + Groovy + HSQLDB
<br />
<ul>Test these urls:
<li>
<a href="showItems.fm?showXMLSource=true">
Listing items in the database as XML with Groovy
</a>
<ul><b>Notes</b>
<li>The LABELS node comes from the file at
<i>WEB-INF/xml/Labels.xml</i>
</li>
<li>The ITEM_QUERY node is generated using the Groovy script at
<i>WEB-INF/scr/Item.groovy</i>
</li>
</ul>
</li>
<li><a href="showItems.fm">
Listing items in the database with Groovy + FreeMarker
</a>
</li>
<li><a href="showItems.xsl">
Listing items in the database with Groovy + XSLT
</a>
</li>
</ul>
</body>
</html>
- We can now access the URL http://localhost:8080/test/ to access the raw XML and both views' versions, as displayed in Figure 4:

Figure 4. Snapshot of the application's default page
This is an example of how one can configure a powerful and dynamic development environment while keeping a healthy "separation of concerns," thanks to the new scripting capabilities included in Java 6.
Conclusions
Now that we have everything configured, we can play directly
with the business logic (Item.groovy) or with the views
implementations (Item.ft/Main.ftl or
Item.xsl along with Labels.xml). There is no need
to recompile anything or restart the servlet context, and our
changes are picked up automatically. Moreover, if we add new
XMLOPERATION nodes, we can see that the WebLEAF configuration is
reloaded automatically (it is checked every minute by default). So
we are able to add new functionality, change the business logic, and
modify the user interface without restarting anything.
Thanks to using XML, we can reuse the libraries we already have
in the Java world and produce, for example, dynamic images using
SVG and Batik, PDF reports using
JasperReports
based on XMLDataSource, etc.
It is also important noticing that as we have shown, different view technologies are not mutually exclusive so if you favor XSLT, but you need to generate a plain text document (like a JSON response for an AJAX request), you can easily reuse the same business logic operations and implement the view for just this request with a more text-friendly template system like FreeMarker.
On the other hand, we might need such dynamic development for
the prototyping phase, but want to implement our final
business logic in, for example, compiled Java classes. No problem!
We just need to implement the Java classes that return the same XML
as our Groovy prototype
and then change the XML_SOURCE attributes starting with
"script://" to others starting with "class://".
As long as we return the same XML, nothing else needs to be
changed. Plain Java classes, session EJBs, Oracle's PLSQL procedures,
Hibernate-based DAOs--all are
different options for the XML_SOURCE origin, so there are plenty to
choose from.
Last, but not least, we used Groovy as the scripting
implementation language but, thanks to the scripting java.net project,
we could have used other scripting languages by simply changing the
file the XML_SOURCE URL points to. It is worth mentioning that the
Scripting API allows you to choose the scripting engine to be
loaded depending on the extension of the file to be processed, so
it is just necessary to add the appropriate engine to the
classpath, and sometimes configure the scripting language
underneath, to be able to use other languages. Apart from testing
Groovy, at the time of
writing we had performed successfully the same tests
using other scripting engines and implementing the business logic
in Jython and PHP (Quercus).
Implementation Notes
In the example, access to the database in the Groovy code is
done in an inefficient way, as it opens a database connection
for each request. But this is just a script for demonstration
purposes, and we didn't want to make it more complicated by
introducing a DataSource configuration, which depends on the
servlet container used.
If you are convinced that you want to go Groovy from beginning to end, be aware that there are other options, like Grails, that might be more suitable for you. The final goal of the technique explained in this article was to show an architecture where you can swap Groovy with other scripting languages; and later on replace them with Java/PLSQL, etc., so the approach is totally different as the requirements are also different.
Resources
- Source codeThe sample code used in this document minus the .jar libraries.
- WebLEAF: A servlet framework whose main goal is to help in the development of web server-side applications written in Java.
- HSQDLB: An SQL relational database engine written in Java.
- scripting java.net project: A project at java.net hosting script engines that implement the JSR 223 Scripting APIs introduced with Java 6.
- Groovy: An agile dynamic language for the Java platform with many features that are inspired by languages like Python, Ruby, and Smalltalk, making modern programming features available to Java developers with an almost-zero learning curve.
- FreeMarker: A "template engine;" a generic tool to generate text output (anything from HTML to autogenerated source code) based on templates.
- XSLT: A language for transforming XML documents into other XML documents.
- Jaxen: A Java XPath engine under an Apache-style open source license.
- Scalable Vector Graphics (SVG): A language for describing two-dimensional graphics and graphical applications in XML.
- Batik: A Java-based toolkit for applications or applets that want to use images in the SVG format for various purposes, such as display, generation, or manipulation.
- JasperReports: A powerful open source Java reporting tool that has the ability to deliver rich content onto the screen, to the printer, or into PDF, HTML, XLS, CSV, or XML files.
- Hibernate: A powerful, high performance object/relational persistence and query service.
- PLSQL: Oracle's Procedural Language extension to SQL.
- Grails: An open source web application framework that leverages the Groovy language and complements Java web development.
- Jython: An implementation of the high-level, dynamic, object-oriented language Python written in 100 percent pure Java, and seamlessly integrated with the Java platform.
- JRuby: A 100 percent pure-Java implementation of the Ruby programming language.
- Quercus PHP: Caucho Technology's 100 percent Java implementation of PHP 5, released under the Open Source GPL license.
- Login or register to post comments
- Printer-friendly version
- 3683 reads



