- Objective: Create a class extending
javax.servlet.http.HttpServlet.
- Mechanism: Use the
init() method to configure routes.
- DSL Style: Leverage Groovy's closure delegation or builder pattern to allow syntax like
get "/path", { ... }.
- Execution: Map incoming HTTP methods and paths to the stored closures in the
service method.
- Verification: Check for valid Groovy syntax and standard Servlet API usage.
Here is a detailed solution for constructing a Groovy Servlet with a DSL-like route definition block.
Reasoning and Design
- The Servlet Foundation: We need a class that extends
HttpServlet. The core lifecycle methods are init() (for setup) and service() (for handling requests).
- The DSL Mechanism: To achieve a DSL syntax like
get "/path", { ... }, we can use a Builder object or a delegate object within the init method. This object will intercept method calls (like get, post, delete) and map them to internal data structures.
- Data Structure: We need a Map to store the routes. A good key is a combination of the HTTP Method and the Path (e.g.,
"GET:/api/users"). The value will be the Groovy Closure handling the logic.
- Request Dispatching: In the
service method, we reconstruct the key from the incoming request and look it up in our map. If found, we execute the closure; otherwise, we return a 404.
The Solution
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.ServletException
class RouterServlet extends HttpServlet {
// Map to store route definitions: "METHOD:/path" -> Closure
private Map<String, Closure> routeMap = [:]
@Override
void init() throws ServletException {
// Define the DSL Context
// This class captures the 'get', 'post', etc. calls
def routerDsl = new Object() {
void get(String path, Closure handler) {
routeMap["GET:${path}"] = handler
}
void post(String path, Closure handler) {
routeMap["POST:${path}"] = handler
}
void put(String path, Closure handler) {
routeMap["PUT:${path}"] = handler
}
void delete(String path, Closure handler) {
routeMap["DELETE:${path}"] = handler
}
}
// Execute the DSL block
// 'with' delegates all method calls inside the closure to 'routerDsl'
routerDsl.with {
// --- Route Definitions Start Here ---
get("/hello") { HttpServletRequest req, HttpServletResponse resp ->
resp.writer << "Hello from GET route!"
}
post("/submit") { req, resp ->
def body = req.reader.text
resp.status = 201
resp.writer << "Received: $body"
}
get("/json") { req, resp ->
resp.contentType = "application/json"
resp.writer << '{"status": "ok"}'
}
// --- Route Definitions End Here ---
}
}
@Override
void service(HttpServletRequest req, HttpServletResponse resp) {
// Construct the lookup key based on request method and path info
String pathInfo = req.pathInfo ?: "/" // Handle root context
String key = "${req.method}:${pathInfo}"
Closure handler = routeMap[key]
if (handler) {
try {
// Execute the stored closure, passing request and response
handler.call(req, resp)
} catch (Exception e) {
resp.sendError(500, "Internal Server Error: ${e.message}")
}
} else {
// No route found
resp.sendError(404, "Route not found for ${key}")
}
}
}
Verification of the Solution
- Inheritance: The class
RouterServlet correctly extends HttpServlet, making it deployable in any standard Java Servlet container (like Tomcat or Jetty).
- DSL Implementation: Inside
init(), an anonymous object is created with methods get, post, etc. Using routerDsl.with { ... } changes the delegate of the closure, allowing the clean DSL syntax inside the block.
- Routing Logic:
- The
routeMap correctly aggregates the mappings during initialization.
- The
service method dynamically looks up the handler based on the HTTP verb and path.
- Groovy Syntax: The code utilizes Groovy features like operator overloading (
<< for streams), GStrings ("${req.method}..."), and closure delegation effectively.