James Williams
LinkedInMastodonGithub

Deploying a Ratpack App to a War File

Not much unlike making a deployable app with Ratpack, creating a deployable war file is pretty easy but there are some tweaks we need to make to the gradle file and in a couple of other places.

Under normal conditions, Ratpack spins up an embedded server, removing the need to create a web.xml file, so that's the first thing we need to do. For a basic app, you only need a single servlet as show in the listing below.

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<servlet>
        <servlet-name>BlogServlet</servlet-name>
        <servlet-class>BlogServlet</servlet-class>
</servlet>

<servlet-mapping>
        <servlet-name>BlogServlet</servlet-name>
        <url-pattern>/*</url-pattern>
</servlet-mapping>

</web-app>

The servlet file RatpackServlet assumes that you are using a Groovy script file that it wants to load at run-time. You could alter the gradle war task to include the Groovy file, which is a good solution for a one-off app where all the code is in one file, or you could tweak the RatpackServlet file. The listing below is a snippet from BlogServlet, which essentially the stock RatpackServlet file with some modest tweaks, shown below. The first line of code instantiates the app followed by two lines to derive the relative path of any referenced static assets.

void init() {
        app = new BlogApp().app
        context = this.getServletContext()
        rootDir = context.getRealPath("/")
        // ...
}

Lastly, we need to format the war task in our gradle build file. That includes copying the static files and templates where they need to be, referencing a web.xml file and including the classpath dependencies.

war {
    into('/public') {   
        from('public')
    }

    into('/templates') {
        from('templates')
    }

    classpath fileTree('lib')
    webXml = file('resources/web.xml')
}