Groovlets Add comment to Wiki View in Wiki Edit Wiki page Printable Version

You can write normal Java servlets in Groovy (i.e. Groovlets).

There is also a GroovyServlet

This feature will 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. Also notice that this is more like a script as it doesn't have a class wrapper.

Or, do the same thing using MarkupBuilder:

Implicit variables

The following variables are ready for use in Groovlets:

variable name

bound to

note

request

ServletRequest

-

response

ServletResponse

-

context

ServletContext

unlike Struts

application

ServletContext

unlike Struts

session

getSession(false)

can be null! see (star) A

params

 

a Map object

headers

 

a Map object

out

response.getWriter()

see (star) B

sout

response.getOutputStream()

see (star) B

html

new MarkupBuilder(out)

see (star) B

jsonnew StreamingJsonBuilder(out)see (star) B

(star) A The session variable is only set, if there was already a session object. See the 'if (session == null)' checks in the examples above.

(star) B These variables cannot be re-assigned 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, the antlr.jar and the asm.jar. Or copy the groovy-all-xyz.jar into WEB-INF/lib - this almost all jar contains the antlr and asm jars.

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

 

Search

Results of your search request can come from various sources: the Groovy website itself, the JIRA issues, the API documentation, as well as a few other interesting Groovy-related blogs.

  By  -  pages  -  views  - last modified