Hiding the nuts and bolts of what happens behind the scenes in Grails web applications is one of its strong points. 99% of the time we use controllers and actions, we access the ‘params’ parameter map to see what’s been passed to our code and respond accordingly without never needing to think any further as to what’s going on under the hood.
As I say, this is great.. 99% of the time… sometimes, however, we need that extra little bit of control. Sometimes we need to write our own ‘Servlets’.
If the term Servlet is new to you, don’t fret. Remember Grails is built on top of many Java frameworks, one of them, being Servlets. Servlets, for example, are responsible for providing you with both HttpRequest and HttpResponse objects in your actions.
The goal of this article is not to cover Servlets in detail, rather I want to show you how to write your own Servlet, wire it up, and be able to access it within an existing Grails web application.
I will be using the latest version of Grails, (4.0.1 at this time of writing) and you will be able to find the entire source code on github to refer to if needed.

Incidentally, If you don’t know anything about Servlets but are working with Grails then I wholeheartedly recommend you read further into them as it will give you a deeper understanding of what is going on behind the scenes in your application.
The Head First Servlets & JSP book is an excellent resource, as are most of the Head First series.
Assumptions
I assume you know how to setup a new application already and simply want to see how you can write / wire in a new servlet.
For the purpose of demonstration, we’re going to create a servlet that simply responds to a ‘GET’ request with some basic JSON text.
Servlets have multiple methods we can override mirror HTTP verbs to respond to i.e. GET, POST, PUT, DELETE, OPTIONS etc.
Implementation
So assuming you’ve created a new app or have an existing application, the first thing is to create the servlet itself. We then extend HttpServlet and override the methods we want to provide functionality for, e.g. we override doGet() to respond to GET requests.
Our class will look something like:
package com.tucanoo.grailsservlets
import groovy.util.logging.Slf4j
import javax.servlet.ServletException
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
@Slf4j
class MyCustomServlet extends HttpServlet {
/**
* Initialize the servlet.
* @see HttpServlet#init().
*/
void init() throws ServletException {
log.debug("Initialising Custom Servlet");
}
/**
* Process GET request.
* @see HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse).
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log.debug("FileServlet processRequest");
// Send back some JSON
response.setContentType("application/json")
response.getWriter().print("{result:'OK'}")
log.debug("FileServlet processRequest --");
}
}
The class is marked with the @Slf4J annotation to inject a Logger so we can call log.debug to see what’s going on.
I’ve also overridden the init() method so we can include a debug statement here to see the servlet initialising at startup.
Similar to your Grails actions, the method doGet will provide us with a HttpRequest and a HttpResponse instance.
For the simplest demonstration, we’re sending back a JSON formatted string using the response writer.
Wiring it up
To make our application aware of the new Servlet, we’re going to define a Spring Bean. There are multiple approaches, this I feel is just as good as any.
Open your conf/spring/resources.groovy file and define a bean similarly as below that references the new Servlet class.
// Place your Spring DSL code here
beans = {
customServlet(ServletRegistrationBean) { bean ->
System.out.println("REGISTERING SERVLET");
servlet = new MyCustomServlet()
urlMappings = ["/custom/test"]
}
}
I’ve added a little println statement so we can see the regitration of the Servlet during app startup.
The urlMappings array is a key parameter, this defines for which URLs our servlet will be called for. If this was not here, it would be called on every request. In this case, I only want it to be called whenever we call the URL /custom/test
Note wildcards can also be specified, so if the urlMappings read [“/custom/*”] – then our servlet would be called for any request with /custom/ in the url.
Additional Steps
As we want to see log output from our Servlet, we’ll need to add a declaration in logback.groovy, such as:
logger("com.tucanoo",DEBUG, ['STDOUT'],false)
That is all we need to do to 1. Create a new traditional Servlet, and 2. wire it up for access within our Grails Application.
You may be wondering why, and when we might ever need to be using servlets within Grails applications. In the follow up to this tutorial, I will give you a good example. Serving Media. What if you wanted to allow your app to serve and play MP3’s, or Video files?
Fine, you can create links to a controller action that sends back the file as a binary stream BUT, your users will NOT be able to skip, pause or resume the playback.
Likewise, if you are serving large files, you should have some ability to allow users to pause, or resume the download if their connection is interrupted. Standard responses via Grails actions will not allow you to do that, you need finer control over the request and response, hence Servlets to the rescue!