In the groovy.servlet package we can find the class ServletCategory. We can use this class to access attributes on the servlet context, page context, request and session with the dot notation. The methods putAt and getAt are implemented in this class for all four objects. If we write Groovy code in the context of these object we can use the ServletCategory to make the code more Groovy.
In the following sample we write two servlets that use the ServletCategory to write and read attribute values. We compile the code to Java classes to get executable servlet. Finally we write a Groovy script to run Jetty with our servlets.
// File: Start.groovy
import javax.servlet.http.*
import javax.servlet.*
import groovy.servlet.ServletCategory
class Start extends HttpServlet {
def application
void init(ServletConfig config) {
super.init(config)
application = config.servletContext
use(ServletCategory) {
application.author = 'mrhaki'
}
}
void doGet(HttpServletRequest request, HttpServletRespons response) {
def session = request.session
use (ServletCategory) {
if (session.counter) { // We can use . notation to access session attribute.
session.counter++ // We can use . notation to set value for session attribute.
} else {
session.counter = 1
}
request.pageTitle = 'Groovy Rocks!'
}
application.getRequestDispatcher('/output').forward(request, response)
}
}
// File: Output.groovy
import javax.servlet.http.*
import javax.servlet.*
import groovy.xml.*
import groovy.servlet.ServletCategory
class Output extends HttpServlet {
def context
void init(ServletConfig config) {
super.init(config)
context = config.servletContext
}
void doGet(HttpServletRequest request, HttpServletRespons reponse) {
def html = new MarkupBuilder(response.writer)
def session = request.session
use(ServletCategory) {
html.html {
head {
title request.pageTitle
}
body {
h1 request.pageTitle
h2 "$context.version written by $context.author"
p "You have requested this page $session.counter times."
}
}
}
}
}
// File: run.groovy
import org.mortbay.jetty.*
import org.mortbay.jetty.servlet.*
import groovy.servlet.*
@Grab(group='org.mortbay.jetty', module='jetty-embedded', version='6.1.14')
def startJetty() {
def jetty = new Server(9090)
def context = new Context(jetty, '/', Context.SESSIONS)
context.resourceBase = '.'
context.addServlet Start, '/start'
context.addServlet Output, '/output'
context.setAttribute 'version', '1.0'
jetty.start()
}
startJetty()
In our web browser we open http://localhost:9090/start and get the following output: