• 【Spring MVC 源码】Spring MVC 如何解析请求


    【Spring MVC 源码】Spring MVC 如何解析请求



    在整个容器和组件初始化完成以后,如果有请求进入,request 则会进入 service() 方法进入分发并解析,整个过程需要之前注册的 HandlerAdapter、HandlerMapping 等进行处理并获取 ModelAndView,并且如果上传的是文件,也会在这个过程中处理。

    一、请求进入

    主要代码:FrameworkServlet#service()

    所有的请求都是会进入 FrameworkServlet 的 service() 方法来区分是什么类型的请求,并且根据这些请求的方法来分别调用不同的方法处理。

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       
    
    	// 判断当前请求使用的方法是什么
    	HttpMethod httpMethod = HttpMethod.resolve(request.getMethod());
    	if (httpMethod == HttpMethod.PATCH || httpMethod == null) {
       
    		// 直接处理请求
    		processRequest(request, response);
    	}
    	else {
       
    		// 如果是其他方法的请求,则会调用父级的 service 进行请求分类并转发
    		super.service(request, response);
    	}
    }
    

    二、请求分类并转发

    主要代码:HttpServlet#service()

    在 HttpServlet 中原生的 service() 会判断 request 中的请求方法是什么类型,比如如果是 GET 方法,则会调用 doGet() 方法,其他同理。

    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       
    	// 获取请求方法
        String method = req.getMethod();
        long lastModified;
        // 根据不同的请求调用不同的方法
        if (method.equals("GET")) {
       
            lastModified = this.getLastModified(req);
            if (lastModified == -1L) {
       
                this.doGet(req, resp);
            } else {
       
                long ifModifiedSince;
                try {
       
                    ifModifiedSince = req.getDateHeader("If-Modified-Since");
                } catch (IllegalArgumentException var9) {
       
                    ifModifiedSince = -1L;
                }
    
                if (ifModifiedSince < lastModified / 1000L * 1000L) {
       
                    this.maybeSetLastModified(resp, lastModified);
                    this.doGet(req, resp);
                } else {
       
                    resp.setStatus(304);
                }
            }
        } else if (method.equals("HEAD")) {
       
            lastModified = this.getLastModified(req);
            this.maybeSetLastModified(resp, lastModified);
            this.doHead(req, resp);
        } else 
  • 相关阅读:
    d八月会议
    羊驼笔记:清算bot
    代码随想录1刷—数组篇
    .NET Evolve 数据库版本管理工具
    JUC三大常用工具类CountDownLatch、CyclicBarrier、Semaphore
    教育现代化浪潮下 “游戏化”教育加速入场
    freeRTOS学习day2任务创建(静态创建)
    【微服务】springboot整合neo4j使用详解
    Android项目升级到AndroidX
    springboot项目:加入购物车
  • 原文地址:https://blog.csdn.net/weixin_41645142/article/details/126959838