Class RouteBasedHandler
java.lang.Object
com.ns.tcpframework.reqeustHandlers.RequestHandler
com.ns.tcpframework.reqeustHandlers.RouteBasedHandler
- Direct Known Subclasses:
ToDoHandler
A request handler that routes requests to specific commands based on URL paths.
This class extends RequestHandler to provide route-based request handling,
where different URL paths can be mapped to different RouteCommand implementations.
It supports both exact path matching and parameterized routes with path variables.
Route matching behavior:
- Exact match: If the request path exactly matches a registered route, that route's command is executed
- Parameterized match: If no exact match is found, the handler attempts
to match against a normalized path pattern ending with
/:id
Example usage:
RouteBasedHandler handler = new RouteBasedHandler();
handler.routes.put("/api/users", getUsersCommand);
handler.routes.put("/api/users/:id", getUserByIdCommand);
- See Also:
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected HashMap<String, RouteCommand> Map of URL paths to their corresponding route commands. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionhandle(HTTPRequest request) Handles an HTTP request by routing it to the appropriate command.Methods inherited from class RequestHandler
handle
-
Field Details
-
routes
Map of URL paths to their corresponding route commands.Keys are URL path strings (e.g., "/api/users" or "/api/users/:id"). Values are
RouteCommandimplementations that handle the requests for those paths.This field is protected to allow subclasses to register routes directly.
-
-
Constructor Details
-
RouteBasedHandler
public RouteBasedHandler()
-
-
Method Details
-
handle
Handles an HTTP request by routing it to the appropriate command.This method implements a two-step routing strategy:
- First, attempts to find an exact match for the request path
- If no exact match exists, normalizes the path by replacing the last
path segment with
:idand attempts to match against parameterized routes
Path normalization example:
/api/users/123→/api/users/:id/api/products/456→/api/products/:id
- Specified by:
handlein classRequestHandler- Parameters:
request- The HTTP request to handle.- Returns:
- The HTTP response generated by the matched route command.
- Throws:
Exception- if no matching route is found or if the route command throws an exception during execution.NullPointerException- if no route matches and the normalized path is also not found in the routes map.
-