tags:

views:

555

answers:

2

How do I drop a Groovlet into a Grails app? Say, for example, in web-app/groovlet.groovy

import java.util.Date

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

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

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

A: 

The way I understand it, groovlets are used when you have a Servlet container with Groovy scripting support,

I think in Grails you would need to move your business logic code to a controller and leave the view part to an HTML or a GSP file.

Something along those lines (meta-code from the top of my head, not tested):

grails-app/controllers/SampleController.groovy

class DateController {
    def index = {
        if (session == null) {
          session = request.getSession(true);
        }

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

web-app/sample/index.gsp

<html>
    <head>
    <title>Groovy Servlet</title>
    </head>
    <body>
Hello, ${request.remoteHost}: Counter: ${session.counter}! Date: ${new Date()}
<br>

Hope that helps!

kolrie
+5  A: 
  1. grails install-templates
  2. Edit src/templates/web/web.xml to include your groovlet
  3. grails war
  4. deploy

I've not personally done this to incorporate a groovlet, but this is the documented way to modify the deployed Grails web.xml

Ken Gentle
Nice! I didn't know that. Do you think that using groovlet is considered a hack as opposed to MVC way of adding a controller and a view, or do you think it's just fine?
kolrie
If the groovlet is already part of a production app, or otherwise well tested, I'd include it as described above.Having said that, if the groovlet is trivial, or can easily be ported to a Grails controller (with tests, of course), then the port is probably worth it, just to maintain continuity.
Ken Gentle