简介
手写Spring框架第一篇博客(必读): 手写Spring框架
上一篇博客实现了Bean容器和IOC功能, 本篇博客来实现简化版的 Spring MVC. 在看下面的内容之前, 我们首先来回顾下 Spring MVC的架构图:
Spring MVC 最核心部分的就是前端控制器DispatcherServlet, 而DispatcherServlet其实就是一个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为 "请求-处理器" 的映射