手写Spring框架之MVC

本文详述了手写Spring MVC框架的过程,包括映射处理器的实现,前端控制器的构造,以及具体实例的创建。从请求类、处理器类到前端控制器的Servlet配置,逐步解析了Spring MVC的核心组件和工作流程。
摘要由CSDN通过智能技术生成

简介

手写Spring框架第一篇博客(必读): 手写Spring框架

上一篇博客实现了Bean容器和IOC功能, 本篇博客来实现简化版的 Spring MVC. 在看下面的内容之前, 我们首先来回顾下 Spring MVC的架构图:
在这里插入图片描述

Spring MVC 最核心部分的就是前端控制器DispatcherServlet, 而DispatcherServlet其实就是一个Servlet, 所以我们有必要先了解下Servlet的知识点, 如下:

Servlet基础

handwritten-mvc-framwork 实现

映射处理器

(1) Request类

请求类中的方法和路径对应 @RequestMapping 注解里的方法和路径.

public class Request {
    /**
     * 请求方法
     */
    private String requestMethod;

    /**
     * 请求路径
     */
    private String requestPath;

    public Request(String requestMethod, String requestPath) {
        this.requestMethod = requestMethod;
        this.requestPath = requestPath;
    }

    public String getRequestMethod() {
        return requestMethod;
    }

    public String getRequestPath() {
        return requestPath;
    }

    @Override
    public int hashCode() {
        int result = 17;
        result = 31 * result + requestMethod.hashCode();
        result = 31 * result + requestPath.hashCode();
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof Request)) return false;
        Request request = (Request) obj;
        return request.getRequestPath().equals(this.requestPath) && request.getRequestMethod().equals(this.requestMethod);
    }
}

(2) Handler类

Handler类为一个处理器, 封装了Controller的Class对象和Method方法.

public class Handler {

    /**
     * Controller 类
     */
    private Class<?> controllerClass;

    /**
     * Controller 方法
     */
    private Method controllerMethod;

    public Handler(Class<?> controllerClass, Method controllerMethod) {
        this.controllerClass = controllerClass;
        this.controllerMethod = controllerMethod;
    }

    public Class<?> getControllerClass() {
        return controllerClass;
    }

    public Method getControllerMethod() {
        return controllerMethod;
    }
}

(3) 实现映射处理器

ControllerHelper 助手类定义了一个"请求-处理器" 的映射 REQUEST_MAP, REQUEST_MAP 就相当于Spring MVC里的映射处理器, 接收到请求后返回对应的处理器.

REQUEST_MAP 映射处理器的实现逻辑如下:

首先通过 ClassHelper 工具类获取到应用中所有Controller的Class对象, 然后遍历Controller及其所有方法, 将所有带 @RequestMapping 注解的方法封装为处理器, 将 @RequestMapping 注解里的请求路径和请求方法封装成请求对象, 然后存入 REQUEST_MAP 中.

public final class ControllerHelper {

    /**
     * REQUEST_MAP为 "请求-处理器" 的映射
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值