美文网首页
Spring Boot Web 请求参数之Servlet API

Spring Boot Web 请求参数之Servlet API

作者: Tinyspot | 来源:发表于2022-12-03 21:28 被阅读0次

    1. Servlet API

    • ServletRequest
    • HttpSession
    • InputStream

    1.1 HttpServletRequest

    @GetMapping("/request")
    public Map<String, Object> request(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        Map<String, String[]> parameterMap = request.getParameterMap();
        map.put("parameterMap", parameterMap);
        map.put("locale", request.getLocale());
        return map;
    }
    

    2. 参数解析原理

    image.png

    三个核心组件:
    Handler
    HandlerMapping
    HandlerAdapter

    2.1 流程

    1. DispatcherServlet#doDispatch
    2. 在 handlerMappings 找处理请求的 Handler
    3. 为 Handler 找一个适配器 HandlerAdapter (RequestMappingHandlerAdapter)
    4. 执行目标方法 RequestMappingHandlerAdapter#invokeHandlerMethod
    5. 参数解析器 this.argumentResolvers
    public class DispatcherServlet extends FrameworkServlet {
        protected void doDispatch(HttpServletRequest request, HttpServletResponse response) {
            // ...
            mappedHandler = getHandler(processedRequest);
            HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
            mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
        }
    }
    

    2.2 四种适配器

    • RequestMappingHandlerAdapter
    • HandlerFunctionAdapter
    • HttpRequestHandlerAdapter
    • SimpleControllerHandlerAdapter

    2.3 执行目标方法

    • RequestMappingHandlerAdapter#invokeHandlerMethod
    • invocableMethod.invokeAndHandle(webRequest, mavContainer);
    • InvocableHandlerMethod#getMethodArgumentValues
    // ServletInvocableHandlerMethod
    Object returnValue = invokeForRequest(webRequest, mavContainer, providedArgs);
    

    2.4 参数解析器

    private HandlerMethodArgumentResolverComposite argumentResolvers;
    List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>();
    
    public interface HandlerMethodArgumentResolver {
    
        boolean supportsParameter(MethodParameter parameter);
    
        Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
                NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception;
    }
    
    image.png

    2.5 返回值处理器

    image.png

    相关文章

      网友评论

          本文标题:Spring Boot Web 请求参数之Servlet API

          本文链接:https://www.haomeiwen.com/subject/zodmfdtx.html