【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 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瞎叨叨的一天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值