Package com.bobocode.bring.web.servlet
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
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
FieldsModifier and TypeFieldDescriptionstatic final intprivate static final Stringprivate final com.fasterxml.jackson.databind.ObjectMapperstatic final Stringstatic final StringFields inherited from class jakarta.servlet.http.HttpServlet
LEGACY_DO_HEAD -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprivate booleancheckIfBodyIsSimple(Object body) Checks if the given object represents a simple type for direct inclusion in the HTTP response body.private booleancheckIfPathVariableAnnotationIsPresent(Parameter[] parameters) Checks if any of the given parameters are annotated withPathVariable.private booleancheckIfUrlIsStatic(String requestPath, String paramPath) Checks if the provided request path and parameter path match a static URL pattern.private booleancheckParams(String requestPath, RestControllerParams params) Checks if the givenRestControllerParamsmatch the provided request path.private voidextractPathVariable(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 theargsarray.private voidextractRequestBody(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 theargsarray.private voidextractRequestHeaderParam(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 theargsarray.private voidextractRequestParam(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 theargsarray.private voidgetParameterValue(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 indexindexbased on its annotations and type.private RestControllerParamsgetRestControllerParams(jakarta.servlet.http.HttpServletRequest req) Retrieves theRestControllerParamsfor the givenHttpServletRequest.private voidgetRestControllerProcessResult(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 voidperformResponse(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 givenHttpServletRequest,HttpServletResponse, and request path.voidprocessRequest(jakarta.servlet.http.HttpServletRequest req, jakarta.servlet.http.HttpServletResponse resp) Overrides theprocessRequestmethod ofFrameworkServlet.private ObjectprocessResponseEntity(jakarta.servlet.http.HttpServletResponse resp, ResponseEntity<?> entity) Processes aResponseEntityobject, setting the HTTP status code and headers in the providedHttpServletResponse.private voidprocessResponseStatusAnnotation(RestControllerProcessResult processResult, jakarta.servlet.http.HttpServletResponse resp) Processes theResponseStatusannotation, if present, for a controller method.private voidprocessRestControllerRequest(RestControllerParams params, jakarta.servlet.http.HttpServletRequest req, jakarta.servlet.http.HttpServletResponse resp) Processes the HTTP request for a specificRestControllerParams.Methods inherited from class com.bobocode.bring.web.servlet.FrameworkServlet
doDelete, doGet, doHead, doOptions, doPost, doPut, doTrace, initMethods inherited from class jakarta.servlet.http.HttpServlet
getLastModified, service, serviceMethods inherited from class jakarta.servlet.GenericServlet
destroy, getInitParameter, getInitParameterNames, getServletConfig, getServletContext, getServletInfo, getServletName, init, log, log
-
Field Details
-
MISSING_APPLICATION_MAPPING_MESSAGE
- See Also:
-
REST_CONTROLLER_PARAMS
- See Also:
-
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 theprocessRequestmethod ofFrameworkServlet. Processes incoming HTTP requests by obtaining REST controller parameters and delegating the processing toprocessRestControllerRequest.- Specified by:
processRequestin classFrameworkServlet- Parameters:
req- HttpServletRequest object representing the HTTP request.resp- HttpServletResponse object representing the HTTP response.
-
getRestControllerParams
Retrieves theRestControllerParamsfor the givenHttpServletRequest. 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 aMissingApplicationMappingException.- Parameters:
req- HttpServletRequest object representing the HTTP request.- Returns:
- The matched
RestControllerParamsfor the request. - Throws:
MissingApplicationMappingException- If no explicit mapping is found for the request.
-
checkParams
Checks if the givenRestControllerParamsmatch 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- TheRestControllerParamsto 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 specificRestControllerParams. Invokes the corresponding controller method with the provided arguments and handles the resulting response.- Parameters:
params- TheRestControllerParamsrepresenting 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 theperformResponsemethod along with method metadata (e.g., annotations). The response is then written to the providedHttpServletResponse.- Parameters:
instance- The instance of the controller.method- The controller method to invoke.resp- TheHttpServletResponseobject 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 ofResponseEntity. If it is, processes the response entity, including HTTP status and headers. Writes the final response (including possible modifications) to the providedHttpServletResponse.- Parameters:
processResult- The result of the controller method execution, including metadata.resp- TheHttpServletResponseobject representing the HTTP response.
-
processResponseStatusAnnotation
private void processResponseStatusAnnotation(RestControllerProcessResult processResult, jakarta.servlet.http.HttpServletResponse resp) Processes theResponseStatusannotation, if present, for a controller method. Sets the HTTP status code of the providedHttpServletResponsebased on the annotation value.- Parameters:
processResult- The result of the controller method execution, including metadata.resp- TheHttpServletResponseobject representing the HTTP response.
-
processResponseEntity
private Object processResponseEntity(jakarta.servlet.http.HttpServletResponse resp, ResponseEntity<?> entity) Processes aResponseEntityobject, setting the HTTP status code and headers in the providedHttpServletResponse. Retrieves and returns the response body.- Parameters:
resp- TheHttpServletResponseobject representing the HTTP response.entity- TheResponseEntityobject containing response information.- Returns:
- The response body extracted from the
ResponseEntity.
-
checkIfBodyIsSimple
Checks if the given object represents a simple type for direct inclusion in the HTTP response body. Simple types include instances ofCharSequence,Number,BooleanandCharacter.- Parameters:
body- The object to be checked.- Returns:
trueif the object is a simple type;falseotherwise.
-
checkIfUrlIsStatic
Checks if the provided request path and parameter path match a static URL pattern. Static URLs are defined by a regular expression specified byREGEX_STATIC_URL.- Parameters:
requestPath- The path from the HTTP request.paramPath- The path from the controller method parameter.- Returns:
trueif both paths match the static URL pattern; otherwise,false.
-
checkIfPathVariableAnnotationIsPresent
Checks if any of the given parameters are annotated withPathVariable.- Parameters:
parameters- The array of parameters to check.- Returns:
trueif at least one parameter is annotated withPathVariable; 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 givenHttpServletRequest,HttpServletResponse, and request path.- Parameters:
req- TheHttpServletRequestobject representing the HTTP request.resp- TheHttpServletResponseobject 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 indexindexbased on its annotations and type. The extracted value is then set in theargsarray, which represents the prepared arguments for invoking a controller method.- Parameters:
req- TheHttpServletRequestobject representing the HTTP request.resp- TheHttpServletResponseobject 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 theargsarray.- Parameters:
req- TheHttpServletRequestobject 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 theargsarray.- Parameters:
req- TheHttpServletRequestobject 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 theargsarray.- Parameters:
req- TheHttpServletRequestobject 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 theargsarray.- 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.
-