跳至主要内容

A Request Sent to Spring(1)

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.

评论

此博客中的热门博文

Spring Boot: Customize Environment

Spring Boot: Customize Environment Environment variable is a very commonly used feature in daily programming: used in init script used in startup configuration used by logging etc In Spring Boot, all environment variables are a part of properties in Spring context and managed by Environment abstraction. Because Spring Boot can handle the parse of configuration files, when we want to implement a project which uses yml file as a separate config file, we choose the Spring Boot. The following is the problems we met when we implementing the parse of yml file and it is recorded for future reader. Bind to Class Property values can be injected directly into your beans using the @Value annotation, accessed via Spring’s Environment abstraction or bound to structured objects via @ConfigurationProperties. As the document says, there exists three ways to access properties in *.properties or *.yml : @Value : access single value Environment : can access multi

Elasticsearch: Join and SubQuery

Elasticsearch: Join and SubQuery Tony was bothered by the recent change of search engine requirement: they want the functionality of SQL-like join in Elasticsearch! “They are crazy! How can they think like that. Didn’t they understand that Elasticsearch is kind-of NoSQL 1 in which every index should be independent and self-contained? In this way, every index can work independently and scale as they like without considering other indexes, so the performance can boost. Following this design principle, Elasticsearch has little related supports.” Tony thought, after listening their requirements. Leader notice tony’s unwillingness and said, “Maybe it is hard to do, but the requirement is reasonable. We need to search person by his friends, didn’t we? What’s more, the harder to implement, the more you can learn from it, right?” Tony thought leader’s word does make sense so he set out to do the related implementations Application-Side Join “The first implementation

Implement isdigit

It is seems very easy to implement c library function isdigit , but for a library code, performance is very important. So we will try to implement it and make it faster. Function So, first we make it right. int isdigit ( char c) { return c >= '0' && c <= '9' ; } Improvements One – Macro When it comes to performance for c code, macro can always be tried. #define isdigit (c) c >= '0' && c <= '9' Two – Table Upper version use two comparison and one logical operation, but we can do better with more space: # define isdigit(c) table[c] This works and faster, but somewhat wasteful. We need only one bit to represent true or false, but we use a int. So what to do? There are many similar functions like isalpha(), isupper ... in c header file, so we can combine them into one int and get result by table[c]&SOME_BIT , which is what source do. Source code of ctype.h : # define _ISbit(bit) (1 << (