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 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 -
Method Summary
Modifier and TypeMethodDescriptionprivate boolean
checkIfBodyIsSimple
(Object body) Checks if the given object represents a simple type for direct inclusion in the HTTP response body.private boolean
checkIfPathVariableAnnotationIsPresent
(Parameter[] parameters) Checks if any of the given parameters are annotated withPathVariable
.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 givenRestControllerParams
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 theargs
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 theargs
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 theargs
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 theargs
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 indexindex
based on its annotations and type.private RestControllerParams
getRestControllerParams
(jakarta.servlet.http.HttpServletRequest req) Retrieves theRestControllerParams
for the givenHttpServletRequest
.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 givenHttpServletRequest
,HttpServletResponse
, and request path.void
processRequest
(jakarta.servlet.http.HttpServletRequest req, jakarta.servlet.http.HttpServletResponse resp) Overrides theprocessRequest
method ofFrameworkServlet
.private Object
processResponseEntity
(jakarta.servlet.http.HttpServletResponse resp, ResponseEntity<?> entity) Processes aResponseEntity
object, setting the HTTP status code and headers in the providedHttpServletResponse
.private void
processResponseStatusAnnotation
(RestControllerProcessResult processResult, jakarta.servlet.http.HttpServletResponse resp) Processes theResponseStatus
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 specificRestControllerParams
.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
-
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 theprocessRequest
method ofFrameworkServlet
. Processes incoming HTTP requests by obtaining REST controller parameters and delegating the processing toprocessRestControllerRequest
.- Specified by:
processRequest
in classFrameworkServlet
- Parameters:
req
- HttpServletRequest object representing the HTTP request.resp
- HttpServletResponse object representing the HTTP response.
-
getRestControllerParams
Retrieves theRestControllerParams
for 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
RestControllerParams
for the request. - Throws:
MissingApplicationMappingException
- If no explicit mapping is found for the request.
-
checkParams
Checks if the givenRestControllerParams
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
- TheRestControllerParams
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 specificRestControllerParams
. Invokes the corresponding controller method with the provided arguments and handles the resulting response.- Parameters:
params
- TheRestControllerParams
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 theperformResponse
method 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
- TheHttpServletResponse
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 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
- TheHttpServletResponse
object representing the HTTP response.
-
processResponseStatusAnnotation
private void processResponseStatusAnnotation(RestControllerProcessResult processResult, jakarta.servlet.http.HttpServletResponse resp) Processes theResponseStatus
annotation, if present, for a controller method. Sets the HTTP status code of the providedHttpServletResponse
based on the annotation value.- Parameters:
processResult
- The result of the controller method execution, including metadata.resp
- TheHttpServletResponse
object representing the HTTP response.
-
processResponseEntity
private Object processResponseEntity(jakarta.servlet.http.HttpServletResponse resp, ResponseEntity<?> entity) Processes aResponseEntity
object, setting the HTTP status code and headers in the providedHttpServletResponse
. Retrieves and returns the response body.- Parameters:
resp
- TheHttpServletResponse
object representing the HTTP response.entity
- TheResponseEntity
object 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
,Boolean
andCharacter
.- Parameters:
body
- The object to be checked.- Returns:
true
if the object is a simple type;false
otherwise.
-
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:
true
if 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:
true
if 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
- TheHttpServletRequest
object representing the HTTP request.resp
- TheHttpServletResponse
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 indexindex
based on its annotations and type. The extracted value is then set in theargs
array, which represents the prepared arguments for invoking a controller method.- Parameters:
req
- TheHttpServletRequest
object representing the HTTP request.resp
- TheHttpServletResponse
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 theargs
array.- Parameters:
req
- TheHttpServletRequest
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 theargs
array.- Parameters:
req
- TheHttpServletRequest
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 theargs
array.- Parameters:
req
- TheHttpServletRequest
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 theargs
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.
-