Groovy and Tomcat, Pt3 – Groovy Scripts

In this part I’m going to show you how to use Groovy Scripts on a Tomcat. It’s very easy to do!

First add these libraries to your project:

- groovy.jar
- groovy-json.jar
- groovy-servlet.jar
- groovy-xml.jar
- antlr.jar
- asm.jar

You might need to add more to the project depending on the functionality of your scripts, but this is the minimum I needed to not encounter any exceptions.

Next, in your web.xmladd the following servlet;


<servlet>
 <servlet-name>GroovyScript</servlet-name>
 <servlet-class>groovy.servlet.GroovyServlet</servlet-class>
 </servlet>

<servlet-mapping>
 <servlet-name>GroovyScript</servlet-name>
 <url-pattern>*.groovy</url-pattern>
 </servlet-mapping>

Groovy will then compile your scripts and run them as requested. For a quick test, put this in your webapp root folder and have its name end with .groovy, I named mine script.groovy, but you should name it something more meaningful.


def ip = request.getRemoteAddr()

println """
<html>
<head>
<title>Groovy Scripts</title>
</head>
<body>
<p>Hello ${ip}</p>
</body>
</html>
"""

Navigate to the url of the script and you’ll get a warm welcome.

Wasn’t that easy?

Stay tuned,
Eek.




Leave a Reply