1. 回顾SpringMVC执⾏的⼤致原理

后续根据这个模仿⼿写⾃⼰的mvc框架
image.png

2. 框架端开发

2.1 ⼿写MVC框架之注解开发

LagouController

  1. package com.lagou.edu.mvcframework.annotations;
  2. import java.lang.annotation.*;
  3. @Documented
  4. @Target(ElementType.TYPE) //表示该注解只能加在类上
  5. @Retention(RetentionPolicy.RUNTIME) //表示JVM运行后仍然生效
  6. public @interface LagouController {
  7. String value() default "";
  8. }

LagouService

  1. package com.lagou.edu.mvcframework.annotations;
  2. import java.lang.annotation.*;
  3. @Documented
  4. @Target(ElementType.TYPE) //表示该注解只能加在类上
  5. @Retention(RetentionPolicy.RUNTIME) //表示JVM运行后仍然生效
  6. public @interface LagouService {
  7. String value() default "";
  8. }

LagouAutowired

  1. package com.lagou.edu.mvcframework.annotations;
  2. import java.lang.annotation.*;
  3. @Documented
  4. @Target(ElementType.FIELD) //表示该注解只能加在字段上
  5. @Retention(RetentionPolicy.RUNTIME) //表示JVM运行后仍然生效
  6. public @interface LagouAutowired {
  7. String value() default "";
  8. }

LagouRequestMapping

  1. package com.lagou.edu.mvcframework.annotations;
  2. import java.lang.annotation.*;
  3. @Documented
  4. @Target({ElementType.TYPE,ElementType.METHOD}) //表示该注解只能加在类和方法上
  5. @Retention(RetentionPolicy.RUNTIME) //表示JVM运行后仍然生效
  6. public @interface LagouRequestMapping {
  7. String value() default "";
  8. }

2.2 适配器映射器

LagouDispatcherServlet

  1. package com.lagou.edu.mvcframework.servlet;
  2. import com.lagou.edu.mvcframework.annotations.LagouAutowired;
  3. import com.lagou.edu.mvcframework.annotations.LagouController;
  4. import com.lagou.edu.mvcframework.annotations.LagouRequestMapping;
  5. import com.lagou.edu.mvcframework.annotations.LagouService;
  6. import com.lagou.edu.mvcframework.pojo.Handler;
  7. import org.apache.commons.lang3.StringUtils;
  8. import javax.servlet.ServletConfig;
  9. import javax.servlet.ServletException;
  10. import javax.servlet.http.HttpServlet;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13. import java.io.File;
  14. import java.io.IOException;
  15. import java.io.InputStream;
  16. import java.lang.reflect.Field;
  17. import java.lang.reflect.InvocationTargetException;
  18. import java.lang.reflect.Method;
  19. import java.lang.reflect.Parameter;
  20. import java.util.*;
  21. import java.util.regex.Matcher;
  22. import java.util.regex.Pattern;
  23. public class LaogouDispatcherServlet extends HttpServlet {
  24. // 用于存储配置文件
  25. private Properties properties = new Properties();
  26. // 缓存扫描到的类的全限定类名
  27. private List<String> classNames = new ArrayList<>();
  28. // ioc容器
  29. private Map<String, Object> iocMap = new HashMap<String, Object>();
  30. // 存储url和Method的映射关系(不够使用,需进行改造)
  31. // private Map<String, Method> handleMapping = new HashMap<>();
  32. // 存储handler集合
  33. private List<Handler> handlerMapping = new ArrayList<>();
  34. @Override
  35. public void init(ServletConfig config) throws ServletException {
  36. // 1.加载配置文件springmvc.properties
  37. String contextConfigLocation = config.getInitParameter("contextConfigLocation");
  38. doLoadConfig(contextConfigLocation);
  39. // 2.扫描相关类,扫描注解
  40. doScan(properties.getProperty("scanPackage"));
  41. // 3.初始化bean(基于注解实现IOC容器)
  42. doInstance();
  43. // 4.实现依赖注入
  44. doAutowired();
  45. // 5.构造一个handleMapping处理器映射器,实现url跟Method的映射
  46. initHandleMapping();
  47. System.out.println("lagou mvc 初始化完成");
  48. // 6.等待请求进入,处理请求
  49. }
  50. @Override
  51. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  52. doPost(req, resp);
  53. }
  54. @Override
  55. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  56. // 方法请求
  57. // 获取URL
  58. // StringBuffer requestURL = req.getRequestURL();
  59. // 通过反射获取URL对应的方法
  60. // Method method = handleMapping.get(requestURL);
  61. // 调用方法method.invoke(); 这里需要传入对应和参数,但是我们的handleMapping中并没有存储,故需要改造initHandleMapping()方法
  62. // 根据url获取到能够处理当前请求的handler
  63. Handler handler = getHandler(req);
  64. if (handler == null) {
  65. resp.getWriter().write("404 not found!");
  66. return;
  67. }
  68. // 参数绑定
  69. // 获取所有的参数类型数组,得到该数组的长度,用于新建一个数组存放最后匹配的参数
  70. Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
  71. // 根据上述数组长度创建一个新的数组(参数数组,是要传入反射调用的)
  72. Object[] paraValues = new Object[parameterTypes.length];
  73. // 从请求中获取参数集合,再利用该参数集合与上述对应的handler方法的参数进行比对,将符合的存储进paraValues
  74. Map<String, String[]> parameterMap = req.getParameterMap();
  75. // 遍历该参数集合,进行比对处理
  76. for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
  77. // name=1&name=2 name [1,2]
  78. String value = StringUtils.join(param.getValue(), ","); // 处理参数值,如同 1,2
  79. // 如果请求参数和方法参数匹配上,则填充数据
  80. if (!handler.getParamIndexMapping().containsKey(param.getKey())){continue;}
  81. // 参数匹配上后,获取参数的位置信息
  82. Integer index = handler.getParamIndexMapping().get(param.getKey());
  83. // 把前台传递过来的参数值填充到对应的位置去
  84. paraValues[index] = value;
  85. }
  86. // 处理参数为请求类型时的匹配处理
  87. int requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName()); // 0
  88. paraValues[requestIndex] = req;
  89. int responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName()); // 1
  90. paraValues[responseIndex] = resp;
  91. // 最终调用handler的method属性
  92. try {
  93. handler.getMethod().invoke(handler.getController(), paraValues);
  94. } catch (IllegalAccessException e) {
  95. e.printStackTrace();
  96. } catch (InvocationTargetException e) {
  97. e.printStackTrace();
  98. }
  99. }
  100. // 根据url获取到能够处理当前请求的handler
  101. private Handler getHandler(HttpServletRequest req) {
  102. if (handlerMapping.isEmpty()) {return null;}
  103. String url = req.getRequestURI();
  104. // 遍历handlerMapping找到与url对应的handler
  105. for (Handler handler : handlerMapping) {
  106. Matcher matcher = handler.getPattern().matcher(url);
  107. if (!matcher.matches()) {continue;}
  108. return handler;
  109. }
  110. return null;
  111. }
  112. // 加载配置文件
  113. private void doLoadConfig(String contextConfigLocation) {
  114. InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
  115. try {
  116. properties.load(resourceAsStream);
  117. } catch (IOException e) {
  118. e.printStackTrace();
  119. }
  120. }
  121. // 扫描相关类,扫描注解
  122. // scanPackage : com.lagou.edu.demo
  123. private void doScan(String scanPackage) {
  124. // 因为扫描路径无法识别包路径,需要转换成磁盘路径(先获取classpath的磁盘路径再进行拼接)
  125. String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
  126. File pack = new File(scanPackagePath);
  127. File[] files = pack.listFiles();
  128. for (File file : files) {
  129. if (file.isDirectory()) {
  130. // 如果为路径,则说明是子package,需递归调用该方法进行扫描
  131. doScan(scanPackage + "." + file.getName());
  132. } else if (file.getName().endsWith(".class")) {
  133. // 获取全限定类名时需要将后缀去掉
  134. String classname = scanPackage + "." + file.getName().replaceAll(".class", "");
  135. classNames.add(classname);
  136. }
  137. }
  138. }
  139. // 实现IOC容器,实例化bean对象
  140. private void doInstance() {
  141. // 利用doScan()方法扫描出的全限定类名进行实例化bean对象
  142. if (classNames.size() == 0) {
  143. return;
  144. }
  145. try {
  146. for (int i = 0; i < classNames.size(); i++) {
  147. String classname = classNames.get(i); //con.lagou.edu.demo.controller.DemoController
  148. // 反射
  149. Class<?> aClass = Class.forName(classname);
  150. // 区分Controller,区分Service
  151. if (aClass.isAnnotationPresent(LagouController.class)) {
  152. // LagouController注解不做过多处理,这里默认取其方法名,将首字母改为小写作为id,保存到ioc容器
  153. String simpleName = aClass.getSimpleName(); //DemoController
  154. String lowerFirstSimpleName = lowerFirst(simpleName); //demoController
  155. iocMap.put(lowerFirstSimpleName, aClass.newInstance());
  156. } else if (aClass.isAnnotationPresent(LagouService.class)) {
  157. // LagouService注解需进一步判断注解上有无规定id,若有则按规定的进行存储,若无则将方法名的首字母小写作为id进行存储
  158. LagouService annotation = aClass.getAnnotation(LagouService.class);
  159. // 获取注解value值
  160. String beanName = annotation.value();
  161. if (!"".equals(beanName.trim())) {
  162. iocMap.put(beanName, aClass.newInstance());
  163. } else {
  164. beanName = lowerFirst(aClass.getSimpleName());
  165. iocMap.put(beanName, aClass.newInstance());
  166. }
  167. // service往往是有接口的,面向接口开发,此时再以接口名为id,放入一份对象到ioc容器中,便于后面实现依赖注入
  168. Class<?>[] interfaces = aClass.getInterfaces();
  169. for (int j = 0; j < interfaces.length; j++) {
  170. Class<?> anInterface = interfaces[j];
  171. iocMap.put(anInterface.getName(), aClass.newInstance());
  172. }
  173. } else {
  174. continue;
  175. }
  176. }
  177. } catch (Exception e) {
  178. e.printStackTrace();;
  179. }
  180. }
  181. // 实现依赖注入
  182. private void doAutowired() {
  183. // 若ioc容器中没有对象则不需要进行依赖注入
  184. if (iocMap.isEmpty()) { return;}
  185. // 若ioc容器中有对象,再去判断对象中的属性是否使用了LagouAutowired注解
  186. // 遍历所有的对象,查看对象中的字段是否使用了LagouAutowired注解,如果有再进行依赖注入管理
  187. for (Map.Entry<String, Object> entry : iocMap.entrySet()) {
  188. // 获取对象中的字段
  189. Field[] declaredFields = entry.getValue().getClass().getDeclaredFields(); //private IDemoService demoService;
  190. // 数组遍历快捷键itar,集合遍历快捷键itli
  191. for (int i = 0; i < declaredFields.length; i++) {
  192. Field declaredField = declaredFields[i];
  193. if (!declaredField.isAnnotationPresent(LagouAutowired.class)) {
  194. continue;
  195. }
  196. // 字段有LagouAutowired注解
  197. LagouAutowired annotation = declaredField.getAnnotation(LagouAutowired.class);
  198. // 获取该注解对应的id
  199. String beanName = annotation.value();
  200. // 如果没有声明id,则用当前字段的类型注入(接口注入) IDemoService,如果有声明id则用声明的id值进行注入
  201. if ("".equals(beanName.trim())) {
  202. beanName = declaredField.getType().getName();
  203. }
  204. // 强制开启赋值
  205. declaredField.setAccessible(true);
  206. // 字段编辑,前者是对象值,后者是注入的bean对象
  207. try {
  208. declaredField.set(entry.getValue(), iocMap.get(beanName));
  209. } catch (IllegalAccessException e) {
  210. e.printStackTrace();
  211. }
  212. }
  213. }
  214. }
  215. // 构造一个handleMapping处理器映射器
  216. private void initHandleMapping() {
  217. // 若ioc容器中没有对象则不需要进行映射
  218. if (iocMap.isEmpty()) { return;}
  219. // 进行映射的主要思路是获取url和method,存储在map集合中
  220. // 遍历所有的对象
  221. for (Map.Entry<String, Object> entry : iocMap.entrySet()) {
  222. // 获取ioc容器中对象的class类型
  223. Class<?> aClass = entry.getValue().getClass();
  224. // 如果对象没有使用LagouController注解,则无需处理
  225. if (!aClass.isAnnotationPresent(LagouController.class)) {continue;}
  226. // 存储url路径的基础路径,即方法上LagouRequestMapping的value值
  227. String baseUrl = "";
  228. if (aClass.isAnnotationPresent(LagouRequestMapping.class)) {
  229. LagouRequestMapping lagouRequestMapping = aClass.getAnnotation(LagouRequestMapping.class);
  230. baseUrl = lagouRequestMapping.value();
  231. // 获取方法
  232. Method[] methods = aClass.getMethods();
  233. for (int i = 0; i < methods.length; i++) {
  234. Method method = methods[i];
  235. // 如果方法上没有使用LagouRequestMapping注解,则不需要处理
  236. if (!method.isAnnotationPresent(LagouRequestMapping.class)) {continue;}
  237. LagouRequestMapping annotation = method.getAnnotation(LagouRequestMapping.class);
  238. String methodUrl = annotation.value();
  239. String url = baseUrl + methodUrl;
  240. // 将信息封装成一个handler
  241. Handler handler = new Handler(entry.getValue(), method, Pattern.compile(url));
  242. // 计算方法的参数位置信息
  243. Parameter[] parameters = method.getParameters();
  244. for (int j = 0; j < parameters.length; j++) {
  245. Parameter parameter = parameters[j];
  246. // 需要区分参数类型,请求类型和普通类型(query(HttpServletRequest request, HttpServletResponse response, String name))
  247. // 若为请求类型,参数名采用其类型名
  248. if (parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {
  249. handler.getParamIndexMapping().put(parameter.getType().getSimpleName(),j);
  250. } else {
  251. // 若为普通类型,参数名采用其参数名
  252. handler.getParamIndexMapping().put(parameter.getName(), j);
  253. }
  254. }
  255. // 封装url、Object、Method、parameter之间的映射关系
  256. handlerMapping.add(handler);
  257. }
  258. }
  259. }
  260. }
  261. // 首字母小写方法
  262. public String lowerFirst(String str) {
  263. char[] chars = str.toCharArray();
  264. if('A' <= chars[0] && chars[0] <= 'Z') {
  265. chars[0] += 32;
  266. }
  267. return String.valueOf(chars);
  268. }
  269. }

2.3 Pojo类

Handler

package com.lagou.edu.mvcframework.pojo;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class Handler {

    // 存储controller对象
    private Object controller;
    // 存储方法
    private Method method;
    // 存储URL,类似String,但它支持正则表达式
    private Pattern pattern;
    // 存储参数及参数顺序,key是参数名,value代表是第几个参数 <name,2>
    private Map<String, Integer> paramIndexMapping;

    public Handler(Object controller, Method method, Pattern pattern) {
        this.controller = controller;
        this.method = method;
        this.pattern = pattern;
        this.paramIndexMapping = new HashMap<>();
    }

    public Object getController() {
        return controller;
    }

    public void setController(Object controller) {
        controller = controller;
    }

    public Method getMethod() {
        return method;
    }

    public void setMethod(Method method) {
        this.method = method;
    }

    public Pattern getPattern() {
        return pattern;
    }

    public void setPattern(Pattern pattern) {
        this.pattern = pattern;
    }

    public Map<String, Integer> getParamIndexMapping() {
        return paramIndexMapping;
    }

    public void setParamIndexMapping(Map<String, Integer> paramIndexMapping) {
        this.paramIndexMapping = paramIndexMapping;
    }
}

3. 使用端开发

3.1 service层

接口IDemoService

package com.lagou.edu.demo.service;

public interface IDemoService {
    public String getName(String name);
}

实现类DemoService

package com.lagou.edu.demo.service.impl;

import com.lagou.edu.demo.service.IDemoService;
import com.lagou.edu.mvcframework.annotations.LagouService;

@LagouService
public class DemoService implements IDemoService {
    @Override
    public String getName(String name) {
        System.out.println("service 实现类中的name参数:" + name);
        return name;
    }
}

3.2 controller层

DemoController

package com.lagou.edu.demo.controller;

import com.lagou.edu.demo.service.IDemoService;
import com.lagou.edu.mvcframework.annotations.LagouAutowired;
import com.lagou.edu.mvcframework.annotations.LagouController;
import com.lagou.edu.mvcframework.annotations.LagouRequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@LagouController
@LagouRequestMapping("/demo")
public class DemoController {

    @LagouAutowired
    private IDemoService demoService;

    @LagouRequestMapping("/query")
    public String query(HttpServletRequest request, HttpServletResponse response, String name) {
        return demoService.getName(name);
    }
}

4. 资源配置及前端开发

4.1 pom、resources配置

pom

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.lagou.edu</groupId>
  <artifactId>mvc</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>mvc Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.9</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <!--编译插件定义编译细节-->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>11</source>
          <target>11</target>
          <encoding>utf-8</encoding>
          <!--告诉编译器,编译的时候记录下形参的真实名称-->
          <compilerArgs>
            <arg>-parameters</arg>
          </compilerArgs>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <port>8080</port>
          <path>/</path>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

springmvc.properties

scanPackage=com.lagou.edu.demo

4.2 前端配置

web.xml配置

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <servlet>
    <servlet-name>laogoumvc</servlet-name>
    <servlet-class>com.lagou.edu.mvcframework.servlet.LaogouDispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>springmvc.properties</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>laogoumvc</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>