Class DispatcherServlet

java.lang.Object
jakarta.servlet.GenericServlet
jakarta.servlet.http.HttpServlet
com.bobocode.bring.web.servlet.FrameworkServlet
com.bobocode.bring.web.servlet.DispatcherServlet
All Implemented Interfaces:
jakarta.servlet.Servlet, jakarta.servlet.ServletConfig, Serializable

public class DispatcherServlet extends FrameworkServlet
The DispatcherServlet class extends FrameworkServlet and serves as the central dispatcher for handling HTTP requests in a RESTful web application. It processes incoming requests, resolves appropriate controllers and manages response generation.

The class supports the annotation-based mapping of controllers and provides a flexible mechanism for handling various types of parameters in controller methods.

Key Constants: - REST_CONTROLLER_PARAMS: Key for storing REST controller parameters in the servlet context. - REGEX_STATIC_URL: Regular expression for matching static URLs.

Key Components: - objectMapper: Object mapper for converting between JSON and Java objects.

Since:
1.0
See Also:
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    static final int
     
    private static final String
     
    private final com.fasterxml.jackson.databind.ObjectMapper
     
    static final String
     
    static final String
     

    Fields inherited from class jakarta.servlet.http.HttpServlet

    LEGACY_DO_HEAD
  • Constructor Summary

    Constructors
    Constructor
    Description
    DispatcherServlet(com.fasterxml.jackson.databind.ObjectMapper objectMapper)
     
  • Method Summary

    Modifier and Type
    Method
    Description
    private boolean
    Checks if the given object represents a simple type for direct inclusion in the HTTP response body.
    private boolean
    Checks if any of the given parameters are annotated with PathVariable.
    private boolean
    checkIfUrlIsStatic(String requestPath, String paramPath)
    Checks if the provided request path and parameter path match a static URL pattern.
    private boolean
    checkParams(String requestPath, RestControllerParams params)
    Checks if the given RestControllerParams match the provided request path.
    private void
    extractPathVariable(String requestPath, Object[] args, Parameter[] parameters, int index)
    Extracts the value of a path variable based on the specified annotation and sets it in the corresponding position of the args array.
    private void
    extractRequestBody(jakarta.servlet.http.HttpServletRequest req, Object[] args, Parameter[] parameters, int index)
    Extracts the value of a request body parameter based on the specified annotation and sets it in the corresponding position of the args array.
    private void
    extractRequestHeaderParam(jakarta.servlet.http.HttpServletRequest req, Object[] args, Parameter[] parameters, int index)
    Extracts the value of a request header parameter based on the specified annotation and sets it in the corresponding position of the args array.
    private void
    extractRequestParam(jakarta.servlet.http.HttpServletRequest req, Method method, Object[] args, int index, Parameter[] parameters)
    Extracts the value of a request parameter based on the specified annotation and sets it in the corresponding position of the args array.
    private void
    getParameterValue(jakarta.servlet.http.HttpServletRequest req, jakarta.servlet.http.HttpServletResponse resp, String requestPath, Method method, Parameter[] parameters, Object[] args, int index)
    Extracts the value for the method parameter at index index based on its annotations and type.
    getRestControllerParams(jakarta.servlet.http.HttpServletRequest req)
    Retrieves the RestControllerParams for the given HttpServletRequest.
    private void
    getRestControllerProcessResult(Object instance, Method method, jakarta.servlet.http.HttpServletResponse resp, Object... args)
    Invokes the controller method with the provided arguments and handles the resulting response.
    private void
    performResponse(RestControllerProcessResult processResult, jakarta.servlet.http.HttpServletResponse resp)
    Handles the response generated by a controller method.
    private Object[]
    prepareArgs(jakarta.servlet.http.HttpServletRequest req, jakarta.servlet.http.HttpServletResponse resp, String requestPath, Method method)
    Prepares the arguments for invoking a controller method by populating an array with values obtained from the given HttpServletRequest, HttpServletResponse, and request path.
    void
    processRequest(jakarta.servlet.http.HttpServletRequest req, jakarta.servlet.http.HttpServletResponse resp)
    Overrides the processRequest method of FrameworkServlet.
    private Object
    processResponseEntity(jakarta.servlet.http.HttpServletResponse resp, ResponseEntity<?> entity)
    Processes a ResponseEntity object, setting the HTTP status code and headers in the provided HttpServletResponse.
    private void
    processResponseStatusAnnotation(RestControllerProcessResult processResult, jakarta.servlet.http.HttpServletResponse resp)
    Processes the ResponseStatus annotation, if present, for a controller method.
    private void
    processRestControllerRequest(RestControllerParams params, jakarta.servlet.http.HttpServletRequest req, jakarta.servlet.http.HttpServletResponse resp)
    Processes the HTTP request for a specific RestControllerParams.

    Methods inherited from class com.bobocode.bring.web.servlet.FrameworkServlet

    doDelete, doGet, doHead, doOptions, doPost, doPut, doTrace, init

    Methods inherited from class jakarta.servlet.http.HttpServlet

    getLastModified, service, service

    Methods inherited from class jakarta.servlet.GenericServlet

    destroy, getInitParameter, getInitParameterNames, getServletConfig, getServletContext, getServletInfo, getServletName, init, log, log

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

    • MISSING_APPLICATION_MAPPING_MESSAGE

      private static final String MISSING_APPLICATION_MAPPING_MESSAGE
      See Also:
    • REST_CONTROLLER_PARAMS

      public static final String REST_CONTROLLER_PARAMS
      See Also:
    • REGEX_STATIC_URL

      public static final String REGEX_STATIC_URL
      See Also:
    • HTTP_STATUS_OK

      public static final int HTTP_STATUS_OK
      See Also:
    • objectMapper

      private final com.fasterxml.jackson.databind.ObjectMapper objectMapper
  • Constructor Details

    • DispatcherServlet

      public DispatcherServlet(com.fasterxml.jackson.databind.ObjectMapper objectMapper)
  • Method Details

    • processRequest

      public void processRequest(jakarta.servlet.http.HttpServletRequest req, jakarta.servlet.http.HttpServletResponse resp)
      Overrides the processRequest method of FrameworkServlet. Processes incoming HTTP requests by obtaining REST controller parameters and delegating the processing to processRestControllerRequest.
      Specified by:
      processRequest in class FrameworkServlet
      Parameters:
      req - HttpServletRequest object representing the HTTP request.
      resp - HttpServletResponse object representing the HTTP response.
    • getRestControllerParams

      private RestControllerParams getRestControllerParams(jakarta.servlet.http.HttpServletRequest req)
      Retrieves the RestControllerParams for the given HttpServletRequest. The method uses the request's method and path to find the corresponding controller parameters stored in the servlet context. It filters the parameters based on the path and path variables, then returns the first match. If no match is found, it throws a MissingApplicationMappingException.
      Parameters:
      req - HttpServletRequest object representing the HTTP request.
      Returns:
      The matched RestControllerParams for the request.
      Throws:
      MissingApplicationMappingException - If no explicit mapping is found for the request.
    • checkParams

      private boolean checkParams(String requestPath, RestControllerParams params)
      Checks if the given RestControllerParams match the provided request path. If the controller method has path variables, it shortens the request path accordingly. The method returns true if the paths match, considering path variables and static URLs.
      Parameters:
      requestPath - The path of the HTTP request.
      params - The RestControllerParams to check against.
      Returns:
      True if the paths match; false otherwise.
    • processRestControllerRequest

      private void processRestControllerRequest(RestControllerParams params, jakarta.servlet.http.HttpServletRequest req, jakarta.servlet.http.HttpServletResponse resp)
      Processes the HTTP request for a specific RestControllerParams. Invokes the corresponding controller method with the provided arguments and handles the resulting response.
      Parameters:
      params - The RestControllerParams representing the controller method to invoke.
      req - HttpServletRequest object representing the HTTP request.
      resp - HttpServletResponse object representing the HTTP response.
    • getRestControllerProcessResult

      private void getRestControllerProcessResult(Object instance, Method method, jakarta.servlet.http.HttpServletResponse resp, Object... args) throws IllegalAccessException, InvocationTargetException
      Invokes the controller method with the provided arguments and handles the resulting response. If the method returns a non-null result, it is passed to the performResponse method along with method metadata (e.g., annotations). The response is then written to the provided HttpServletResponse.
      Parameters:
      instance - The instance of the controller.
      method - The controller method to invoke.
      resp - The HttpServletResponse object representing the HTTP response.
      args - The arguments to be passed to the controller method.
      Throws:
      IllegalAccessException - If the method is inaccessible.
      InvocationTargetException - If the invoked method throws an exception.
    • performResponse

      private void performResponse(RestControllerProcessResult processResult, jakarta.servlet.http.HttpServletResponse resp)
      Handles the response generated by a controller method. Checks if the response is an instance of ResponseEntity. If it is, processes the response entity, including HTTP status and headers. Writes the final response (including possible modifications) to the provided HttpServletResponse.
      Parameters:
      processResult - The result of the controller method execution, including metadata.
      resp - The HttpServletResponse object representing the HTTP response.
    • processResponseStatusAnnotation

      private void processResponseStatusAnnotation(RestControllerProcessResult processResult, jakarta.servlet.http.HttpServletResponse resp)
      Processes the ResponseStatus annotation, if present, for a controller method. Sets the HTTP status code of the provided HttpServletResponse based on the annotation value.
      Parameters:
      processResult - The result of the controller method execution, including metadata.
      resp - The HttpServletResponse object representing the HTTP response.
    • processResponseEntity

      private Object processResponseEntity(jakarta.servlet.http.HttpServletResponse resp, ResponseEntity<?> entity)
      Processes a ResponseEntity object, setting the HTTP status code and headers in the provided HttpServletResponse. Retrieves and returns the response body.
      Parameters:
      resp - The HttpServletResponse object representing the HTTP response.
      entity - The ResponseEntity object containing response information.
      Returns:
      The response body extracted from the ResponseEntity.
    • checkIfBodyIsSimple

      private boolean checkIfBodyIsSimple(Object body)
      Checks if the given object represents a simple type for direct inclusion in the HTTP response body. Simple types include instances of CharSequence, Number, Boolean and Character.
      Parameters:
      body - The object to be checked.
      Returns:
      true if the object is a simple type; false otherwise.
    • checkIfUrlIsStatic

      private boolean checkIfUrlIsStatic(String requestPath, String paramPath)
      Checks if the provided request path and parameter path match a static URL pattern. Static URLs are defined by a regular expression specified by REGEX_STATIC_URL.
      Parameters:
      requestPath - The path from the HTTP request.
      paramPath - The path from the controller method parameter.
      Returns:
      true if both paths match the static URL pattern; otherwise, false.
    • checkIfPathVariableAnnotationIsPresent

      private boolean checkIfPathVariableAnnotationIsPresent(Parameter[] parameters)
      Checks if any of the given parameters are annotated with PathVariable.
      Parameters:
      parameters - The array of parameters to check.
      Returns:
      true if at least one parameter is annotated with PathVariable; otherwise, false.
    • prepareArgs

      private Object[] prepareArgs(jakarta.servlet.http.HttpServletRequest req, jakarta.servlet.http.HttpServletResponse resp, String requestPath, Method method)
      Prepares the arguments for invoking a controller method by populating an array with values obtained from the given HttpServletRequest, HttpServletResponse, and request path.
      Parameters:
      req - The HttpServletRequest object representing the HTTP request.
      resp - The HttpServletResponse object representing the HTTP response.
      requestPath - The path from the HTTP request.
      method - The controller method for which arguments are being prepared.
      Returns:
      An array of objects representing the prepared arguments for the controller method.
    • getParameterValue

      private void getParameterValue(jakarta.servlet.http.HttpServletRequest req, jakarta.servlet.http.HttpServletResponse resp, String requestPath, Method method, Parameter[] parameters, Object[] args, int index) throws IOException
      Extracts the value for the method parameter at index index based on its annotations and type. The extracted value is then set in the args array, which represents the prepared arguments for invoking a controller method.
      Parameters:
      req - The HttpServletRequest object representing the HTTP request.
      resp - The HttpServletResponse object representing the HTTP response.
      requestPath - The path from the HTTP request.
      method - The controller method for which arguments are being prepared.
      parameters - The array of parameters of the controller method.
      args - The array of objects representing the prepared arguments.
      index - The index of the current parameter being processed.
      Throws:
      IOException - If an I/O error occurs while processing the request or response.
      MissingRequestParamException - If a required request parameter is not present.
    • extractRequestHeaderParam

      private void extractRequestHeaderParam(jakarta.servlet.http.HttpServletRequest req, Object[] args, Parameter[] parameters, int index)
      Extracts the value of a request header parameter based on the specified annotation and sets it in the corresponding position of the args array.
      Parameters:
      req - The HttpServletRequest object representing the HTTP request.
      args - The array of objects representing the prepared arguments.
      parameters - The array of parameters of the controller method.
      index - The index of the current parameter being processed.
    • extractRequestBody

      private void extractRequestBody(jakarta.servlet.http.HttpServletRequest req, Object[] args, Parameter[] parameters, int index) throws IOException
      Extracts the value of a request body parameter based on the specified annotation and sets it in the corresponding position of the args array.
      Parameters:
      req - The HttpServletRequest object representing the HTTP request.
      args - The array of objects representing the prepared arguments.
      parameters - The array of parameters of the controller method.
      index - The index of the current parameter being processed.
      Throws:
      IOException - If an I/O error occurs while processing the request body.
    • extractRequestParam

      private void extractRequestParam(jakarta.servlet.http.HttpServletRequest req, Method method, Object[] args, int index, Parameter[] parameters)
      Extracts the value of a request parameter based on the specified annotation and sets it in the corresponding position of the args array.
      Parameters:
      req - The HttpServletRequest object representing the HTTP request.
      method - The controller method for which arguments are being prepared.
      args - The array of objects representing the prepared arguments.
      index - The index of the current parameter being processed.
      parameters - The array of parameters of the controller method.
      Throws:
      MissingRequestParamException - If a required request parameter is not present.
    • extractPathVariable

      private void extractPathVariable(String requestPath, Object[] args, Parameter[] parameters, int index)
      Extracts the value of a path variable based on the specified annotation and sets it in the corresponding position of the args array.
      Parameters:
      requestPath - The path from the HTTP request.
      args - The array of objects representing the prepared arguments.
      parameters - The array of parameters of the controller method.
      index - The index of the current parameter being processed.