1) Introduction
In this article, we will learn about how to achieve Web Development using Groovy. Groovy is a scripting language and it has components called Groovlets which sit on top of a Web Server for handling HTTP Requests and Responses similar to Java Servlets. This article will provide an overview about Groovlets in the first section and will present several code snippets that will help in simplifying the usage of Groovlets in the subsequent sections. Remember, this is not an introductory article on Groovy and first-time readers are strongly advised to have a look over the Introductory article on Groovy .
2) Groovlets
Before getting into Groovlets, let us look into the basics of a typical Java Web Application. Usually a Web Server will host one or more Web Applications and the Client’s Requests are handled by Components called Java Servlets which usually sit on top of the Web Server. A Servlet continue to live within the Web Server’s address space and its life-time will be controlled only by the Web Server. One of the major responsibilities of a Web Server is to match a client request to a particular Servlet in an Application. Typically, this is done in the Application’s configuration file, usually web.xml
file.
So a Java Servlet can be considered as an extension point which provides some useful services to a Client. The Web Server wraps the Client request and passes a Http Request object to the Servlet. The Servlet retrieves various inputs from the Client and executes some actions accordingly. A Servlet is written in pure Java code and one can see a mix of Java Business logic as well as Html UI Generation in a Servlet.
Now, let us see the Java Servlet’s counterpart, Groovlets. Groovlets, or Groovy Pages that end with .groovy extension are processed by Groovy Engine which sits on top of a Web Server. Typically, a Groovy Engine is nothing but a Groovy Servlet. When a client requests for a Groovy page for the very first time, the Groovy Servlet will be invoked (we will configure this in the Application’s descriptor file) and parses the page to convert into a Java class or a Java Servlet. The Java Servlet is then compiled and an instance of the class will be created by the Web Server. Groovlets are much suitable only for simpler or small Web Applications. Compared to Java Servlets, coding in Groovy will be much simpler.
In the next few sections, we will see how to develop Groovlets or Groovy pages.
3) Developing a Simple Groovlet
In this section, we will see how to write a simple static Groovlet. By the word static, we mean that this Groovlet doesn’t provide any dynamic content upon request. Instead it will provide a simple Html page back to the Client Browser.
Let us look into the sample code,
test.groovy
html.html { head { title 'Groovy Test' } body { h1 'Groovy page called' } }
Save the above file as test.groovy
and deploy the file in a Web Application. For testing purpose, Tomcat Web Container can be used which is running the Groovlet. Make sure that you follow the J2EE standard directory structure for packaging the Web Application.
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>GroovyServlet</servlet-name> <servlet-class>groovy.servlet.GroovyServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>GroovyServlet</servlet-name> <url-pattern>*.groovy</url-pattern> </servlet-mapping> </web-app>
The above listing is the deployment descriptor file for the Application. This Deployment Descriptor has two sections. One is the declaration of the Servlet and the other provides the mapping information to call the Groovy Servlet.
<servlet> <servlet-name>GroovyServlet</servlet-name> <servlet-class>groovy.servlet.GroovyServlet</servlet-class> </servlet>
The above code snippet declares the Groovy Servlet with the name 'GroovyServlet'
. Note that the 'servlet-class'
tag should point to the fully qualified name of the Servlet, in this case it happens to 'groovy.servlet.GroovyServlet'
. Don’t forget to add the library classes (groovy-all-1.0.jar
, which comes as part of the Groovy Distribution).
Now, consider the following code snippet,
<servlet-mapping> <servlet-name>GroovyServlet</servlet-name> <url-pattern>*.groovy</url-pattern> </servlet-mapping>
This declaration basically defines a mapping. A mapping generally specifies ‘the type of Request to be handled by the corresponding components’. In the above code snippet, we define the url pattern of the request in the tag 'url-pattern'
as '*.groovy'
. It means that the request that matches this URL pattern will be handled by the Groovy Servlet.
Before jumping into the next section, let us analyse the code in test.groovy
. The test.groovy
file looked like this,
test.groovy
html.html { head { title 'Groovy Test' } body { h1 'Groovy page called' } }
In Groovy, there are Components called Builders, which stands as the base for building the target. For example, a variant of Builder called Xml Builder can be used to populate XML contents in a file. Similarly, Html Builder can generate Html files. Other notable Builders in Groovy are Ant Builders and Swing Builders which are used to construct Build files and Swing Components respectively.
In our above code, we have used Html builder for populating Html contents which is to be served shortly to the clients. For the above test.groovy
, the equivalent generated Html code would be,
<html> <head> <title>Groovy Test</title> </head> <body> <H1>Groovy page called</H1> </body> </html>
4) Groovlet displaying Request Information
In this section, we will develop a Groovlet which will display the various request information supplied by the clients. Parallely, we will use the various implicit objects that are available. These implicit objects will be bound to some classes in the Java Servlet API. The following objects are the various commonly used implicit objects that are readily available and can be used in a Groovy Page.
- application, context –> Maps to javax.servlet.ServletContext
- session –> Maps to javax.servlet.HttpSession
- request –> Maps to javax.servlet.HttpServlet
- response –> Maps to javax.servlet.HttpResponse
- out –> Maps to response.getWriter()
RequestInfo.groovy
html.html() { head() { title 'Request Information' } body() { table(border : "2") { tr() { td("Authentication Type"); td("${request.getAuthType()}"); } tr() { td("Context Path"); td("${request.getContextPath()}"); } tr() { td("HTTP Method"); td("${request.getMethod()}"); } tr() { td("Path Info "); td("${request.getPathInfo()}"); } } } }
In the above file RequestInfo.groovy
, we have again made use of Groovy Builder classes for generating the Html output. Note that for building an Html element that involves attributes, we have use the following syntax,
(attrName : attrValue).
For example, in the above code, if we wish to set the 'border'
attribute for the table tag as 2
, then the same has to be mentioned as,
table(border : "2")
We have decorated the output by embedding the content in a simple Html table. Watch carefully for how we have taken the request information. We have used a simple scripting for the same. For example, consider the following script,
${request.getPathInfo()
Here, the symbol 'request'
maps to the HttpServletRequest
object and getPathInfo()
can be treated as a method in the class HttpServletRequest
. ${Symbol}
is the value for the expression. The equivalent Html code is given below,
<html> <head> <title>Request Information</title> </head> <body> <table border='2'> <tr> <td>Authentication Type</td> <td>null</td> </tr> <tr> <td>Context Path</td> <td>/Groovy-Groovlets</td> </tr> <tr> <td>HTTP Method</td> <td>GET</td> </tr> <tr> <td>Path Info </td> <td>null</td> </tr> </table> </body> </html>
5) Handling Form Requests
In the final section, we will see how to use Groovlets for form submission. As a simple example, let us develop a simple Login form that contains the username/password text-fields along with a submit button. The following code is an example for the same,
Login.groovy
html.html() { head() { title 'Login Form' } body() { form(method : 'GET' , action : 'LoginAction.groovy') { tr() { td("Firstname:") input(type : 'text' , name : 'username') } tr() { td("Password:") input(type : 'password' , name : 'password') } tr() { input(type : 'submit') } } } }
Note that when the user clicks the form to submit the values, we want some other Groovlet to be called with some appropriate request type. We have achieved the same in the form tag as follows,
form(method : 'GET' , action : 'LoginAction.groovy')
The above form tag details that when this form is submitted, the Groovlet 'LoginAction.groovy'
will be called as pointed by the 'action'
attribute with GET
as the request type. Following is the complete code listing for 'LoginAction.groovy'
.
LoginAction.groovy
html.html() { head() { title 'Welcome Page' } body() { String username = request.getParameter('username'); String password = request.getParameter('password'); if ((username.equals('guest')) && (password.equals('guest')) ) { h1 "Welcome guest" } else { h1 "Unknown user" } } }
In the above Groovlet, the request values containing the username and password are taken and appropriate message is displayed depending on their values. It is always possible to compile Groovy code with that of Java code similar to the one we have seen in the above example.
6) Conclusion
This article provided a basic introduction on how to carry out Web Development programming in Groovy. It discussed about the Servlet counterpart that is available in Groovy, which are termed as Groovlets. The later sections on the article concentrated on writing various Groovlets, that display a simple html file to the user, displaying the request information along with form submission.
The following are some of the popular articles published in Javabeat. Also you can refer the list of groovy articles and groovy books from our website. Please read the articles and post your feedback about the quality of the content.
If you are interested in receiving the future java articles from us, please subscribe here.