Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 6 Next »

You can write normal Java servlets in Groovy (i.e. Groovlets).
There is also a GroovyServlet which automatically compile your .groovy source files, turn them into bytecode, load the Class and cache it until you change the source file.

Here's a simple example to show you the kind of thing you can do from a Groovlet.
Notice the use of implicit variables to access the session, output & request.

Error rendering macro 'code': Invalid value specified for parameter 'lang'
import java.util.Date

if (session.counter == null) {
  session.counter = 1
}

println """
<html>
    <head>
        <title>Groovy Servlet</title>
    </head>
    <body>
Hello, ${request.remoteHost}: ${session.counter}! ${new Date()}
    </body>
</html>
"""
session.counter = session.counter + 1

Or, do the same thing using MarkupBuilder:

Error rendering macro 'code': Invalid value specified for parameter 'lang'
import java.util.Date
import groovy.xml.MarkupBuilder

if (session.counter == null) {
      session.counter = 1
}

html.html {    // html is implicitly bound to new MarkupBuilder(out)
  head {
      title("Groovy Servlet")
  }
  body {
    p("Hello, ${request.remoteHost}: ${session.counter}! ${new Date()}")
  }
}
session.counter = session.counter + 1

Implicit variables

The following variables are ready for use in Groovlets:

variable name

bound to

note

request

ServletRequest

response

ServletResponse

context

ServletContext

application

ServletContext

unlike Struts

session

getSession(true)

out

response.getWriter()

see * below

sout

response.getOutputStream()

see * below

html

new MarkupBuilder(out)

see * below

  • These variables cannot be reassigned inside a Groovlet.
    They are bound on first access, allowing to e.g. calling
    methods on the 'response' object before using 'out'.

Setting up groovylets

Put the following in your web.xml:

Then all the groovy jar files into WEB-INF/lib. (You should only need to put the groovy jar and the asm jar).

Now put the .groovy files in, say, the root directory (i.e. where you would put your html files). The groovy servlet takes care of compiling the .groovy files.

So for example using tomcat you could edit tomcat/conf/server.xml like so:

Then access it with http://localhost:8080/groovy/hello.groovy

  • No labels