Class RouteBasedHandler

java.lang.Object
com.ns.tcpframework.reqeustHandlers.RequestHandler
com.ns.tcpframework.reqeustHandlers.RouteBasedHandler
Direct Known Subclasses:
ToDoHandler

public class RouteBasedHandler extends RequestHandler
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 Details

    • routes

      protected HashMap<String, RouteCommand> 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 RouteCommand implementations 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

      public HTTPResponse handle(HTTPRequest request) throws Exception
      Handles an HTTP request by routing it to the appropriate command.

      This method implements a two-step routing strategy:

      1. First, attempts to find an exact match for the request path
      2. If no exact match exists, normalizes the path by replacing the last path segment with :id and attempts to match against parameterized routes

      Path normalization example:

      • /api/users/123/api/users/:id
      • /api/products/456/api/products/:id
      Specified by:
      handle in class RequestHandler
      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.