This will be a serial of posts to understand how a HTTP request sent to Spring finally be handled by our business logical code and returned.
Today, we will start from a HTTP request to invoke this code:
// http://localhost:8080/testMapStr2?a=1&b=2
@GetMapping("/testMapStr")
public String testMapStr(@RequestParam Map<String, String> m) {
return m.toString();
}
HTTP Request Format
The essence of a protocol is the requested/conventional format of byte of data, which often starts with header, then data item.
HTTP is not the special case. A post request is like following:
POST /foo?bar=2
Accept-Language: en
other headers
optinal body
Server Handle
So, when the server receive the http message from socket, it will interpret them as needed.
In our case, we are using a Java server, so it will parse the URL (and check whether this URL meet the RFC of URL), extract method and headers, handle session etc. Then, It will construct a HttpRequest
and HttpResponse
and invoke a servlet according to the settings in web.xml
or annotations.
Spring Handle
Because we use spring, we will dispatch all request to spring’s servlet DispatcherServlet
. In this class, doService
will be invoked as a common servlet which handle the request and return response, spring dispatch this request according to spring MVC config.
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
//...
try {
doDispatch(request, response);
} finally {}
}
Then the content of dispatch:
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
//...
// find handler for this
mappedHandler = getHandler(processedRequest);
if (mappedHandler == null || mappedHandler.getHandler() == null) {
noHandlerFound(processedRequest, response);
return;
}
//...
// pre-handle, apply interceptors
if (!mappedHandler.applyPreHandle(processedRequest, response)) {...}
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
//...
mappedHandler.applyPostHandle(processedRequest, response, mv);
}
The process to find a the handler (which is the method to execute and interceptors to it) is to iterate several handler mappings:
protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
for (HandlerMapping hm : this.handlerMappings) {
HandlerExecutionChain handler = hm.getHandler(request);
//...
}
}
Invoke Chain
We have already saw the procedure from a HTTP message arrival to the mapped handler is invoked.
Now, we focus on how parameter for our handler is resolved, which will be useful for next post.
First, we start from DispatcherServelt#doDispatch()
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
then, a serial of call stack:
AbstractHandlerMethodAdapter#handle()
=>
RequestMappingHandlerAdapter#handleInternal()
=>
RequestMappingHandlerAdapter#invokeHandlerMethod()
=>
ServletInvocableHandlerMethod#invokeAndHandle()
=>
InvocableHandlerMethod#invokeForRequest()
=>
InvocableHandlerMethod#getMethodArgumentValues()
=>
HandlerMethodArgumentResolverComposite#resolveArgument()
=>
HandlerMethodArgumentResolver#resolveArgument()
=>
<= //... return from request invocation
HandlerMethodReturnValueHandler#handleReturnValue()
Conversion
The HandlerMethodArgumentResolver
is a interface which represent the different strategies to resolve argument.
/**
* Resolves a method parameter into an argument value from a given request.
* A {@link ModelAndViewContainer} provides access to the model for the
* request. A {@link WebDataBinderFactory} provides a way to create
* a {@link WebDataBinder} instance when needed for data binding and
* type conversion purposes.
* @param parameter the method parameter to resolve. This parameter must
* have previously been passed to {@link #supportsParameter} which must
* have returned {@code true}.
*/
Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception;
If we have following signature of method:
@GetMapping("/testMapStr")
public String testMapStr(@RequestParam Map<String, String> m) {
return m.toString();
}
Then RequestParamMapMethodArgumentResolver
is the specific strategy:
Class<?> paramType = parameter.getParameterType();
// this parameter map is get from HttpRequest, which is parsed by server
Map<String, String[]> parameterMap = webRequest.getParameterMap();
// put to Map or MultiValueMap according to paramType
Question
What’s the strategy for a interface like following:
public SimpleResponse fileRename(@RequestParam Long id) {
}
Answer
Through ‘step in’ functionality of debugging, we can find it:
AbstractNamedValueMethodArgumentResolver
Question
How to make this interface working if enum need customized converter:
// url: /events?c=notColorString
// Color is enum
public String test(@RequestParam Color c) {
}
Answer
If the info we sent is the ordinal or name of that enum, we need no any special conversion. But if we need customized conversion, this question told us the answer: add our converter or data binder (data binder has many converters and that is why we sent string and spring can automatically change it to long).
In conclusion, in order to customize the parameter conversion, we can
- add our converter
- use our data binder
- add jackson deserializer
Real Invocation
Finally, invocation in InvocableHandlerMethod#invokeForRequest()
Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);
// invoke method via reflection: method.invoke(getBean(), args)
Object returnValue = doInvoke(args);
Then the return value will be handled by interface of:
HandlerMethodReturnValueHandler#handleReturnValue
Written with StackEdit.
评论
发表评论