Tuesday, January 4, 2011

Configuring Embedded Tomcat in Grails

When running a Grails application in development mode with an embedded Tomcat instance, you sometimes need to do some custom Tomcat configuration. Unfortunately, you can't use the regular Tomcat XML files because they aren't available to you. Luckily Grails has defined a "ConfigureTomcat" event that can be used to configure some aspects of the embedded Tomcat container.

In order to hook into this event, create an _Events.groovy file in your scripts directory and create the following closure:
eventConfigureTomcat = {tomcat ->
}
In the closure you have access to an org.apache.catalina.startup.Tomcat object.

I've used this technique to configure dummy users so that you can test authentication and authorization in Grails development mode.

eventConfigureTomcat = {tomcat ->
  println "Loading users"
  
  tomcat.addUser("user", "password")
  tomcat.addRole("user", "group")
}

Thanks to Rich Kroll for the orignal approach to this problem. You can read his post at http://krollrich.blogspot.com/2009/12/run-java-web-application-within-grails.html