Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: at the 'Implicit variables', 'params', 'headers' (these are useful!) rows were added provisionally. (Written in the API doc 'ServletBinding'. I didn't know these can be used in not only Grails, but also Groovlets.)

...

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.

Code Block
java
java

if (!session) {
  session = request.getSession(true);
}

if (!session.counter) {
  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:

Code Block
java
java

if (!session) {
  session = request.getSession(true)
}

if (!session.counter) {
      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

...

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

...

Put the following in your web.xml:

Code Block
xml
xml

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

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

...

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

Code Block
xml
xml

<Context path="/groovy" docBase="c:/groovy-servlet"/>

...