没啥想说的,就放个表情包吧

1 Spring MVC 执行流程

2 MVC 框架注解开发

自定义注解

(1)MyController

@Documented
@Target(ElementType.TYPE)
// 生命周期
@Retention(RetentionPolicy.RUNTIME)
public @interface MyController {String value() default "";
}

(2)MyService

@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyService {String value() default "";
}

(3)MyAutowired

@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAutowired {String value() default "";
}

(4)MyRequestMapping

@Documented
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyRequestMapping {String value() default "";
}

3 MVC 框架流程结构开发

前端控制器 MyDispatcherServlet

    private Properties properties = new Properties();// 缓存扫描到的类的全限定类名private List<String> classNames = new ArrayList<>(); // ioc容器private Map<String, Object> ioc = new HashMap<String, Object>();// 存储url和Method之间的映射关系private List<Handler> handlerMapping = new ArrayList<>();public void init(ServletConfig config) {// 1 加载配置文件 springmvc.propertiesString contextConfigLocation = config.getInitParameter("contextConfigLocation");doLoadConfig(contextConfigLocation);// 2 扫描相关的类,扫描注解doScan(properties.getProperty("scanPackage"));// 3 初始化bean对象(实现ioc容器,基于注解)doInstance();// 4 实现依赖注入doAutoWired();// 5 构造一个HandlerMapping处理器映射器,将配置好的url和Method建立映射关系initHandlerMapping();System.out.println("my mvc 初始化完成....");// 6 等待请求进入,处理请求
}

web.xml

<web-app><servlet><servlet-name>lgoumvc</servlet-name><servlet-class>com.lagou.edu.mvcframework.servlet.MyDispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>springmvc.properties</param-value></init-param></servlet><servlet-mapping><servlet-name>mymvc</servlet-name><url-pattern>/*</url-pattern></servlet-mapping>
</web-app>

springmvc.properties

scanPackage=com.demo

(1)加载配置文件

private void doLoadConfig(String contextConfigLocation) {InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);try {properties.load(resourceAsStream);} catch (IOException e) {e.printStackTrace();}
}

(2)扫描相关类,扫描注解

// 扫描磁盘路径
private void doScan(String scanPackage) {// 将 com.demo 转为 com/demo String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");File pack = new File(scanPackagePath);File[] files = pack.listFiles();for (File file : files) {// 子package,是目录则继续递归if (file.isDirectory()) {// 递归 com.demo.controllerdoScan(scanPackage + "." + file.getName());} else if (file.getName().endsWith(".class")) {// 获取全限定类名String className = scanPackage + "." + file.getName().replaceAll(".class", "");classNames.add(className);}}}

(3)初始化 Bean 对象

/*** 初始化 bean* 基于classNames缓存的类的全限定类名,以及反射技术,完成对象创建和管理*/
private void doInstance() {if (classNames.size() == 0) return;try {for (int i = 0; i < classNames.size(); i++) {// com.controller.DemoControllerString className = classNames.get(i);// 反射Class<?> aClass = Class.forName(className);// 区分controller,区分service'if (aClass.isAnnotationPresent(MyController.class)) {// controller的id此处不做过多处理,不取value了,就拿类的首字母小写作为id,保存到ioc中// DemoControllerString simpleName = aClass.getSimpleName();// demoControllerString lowerFirstSimpleName = lowerFirst(simpleName);Object o = aClass.newInstance();ioc.put(lowerFirstSimpleName, o);} else if (aClass.isAnnotationPresent(MyService.class)) {LagouService annotation = aClass.getAnnotation(LagouService.class);//获取注解value值String beanName = annotation.value();// 如果指定了id,就以指定的为准if (!"".equals(beanName.trim())) {ioc.put(beanName, aClass.newInstance());} else {// 如果没有指定,就以类名首字母小写beanName = lowerFirst(aClass.getSimpleName());ioc.put(beanName, aClass.newInstance());}// service层往往是有接口的,面向接口开发,此时再以接口名为id,放入一份对象到ioc中,便于后期根据接口类型注入Class<?>[] interfaces = aClass.getInterfaces();for (int j = 0; j < interfaces.length; j++) {Class<?> anInterface = interfaces[j];// 以接口的全限定类名作为id放入ioc.put(anInterface.getName(), aClass.newInstance());}} else {continue;}}} catch (Exception e) {e.printStackTrace();}
}

(4)实现依赖注入

private void doAutoWired() {if (ioc.isEmpty()) {return;}// 有对象,再进行依赖注入处理// 遍历ioc中所有对象,查看对象中的字段,是否有@MyAutowired注解,如果有需要维护依赖注入关系for (Map.Entry<String, Object> entry : ioc.entrySet()) {// 获取bean对象中的字段信息Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();// 遍历判断处理for (int i = 0; i < declaredFields.length; i++) {Field declaredField = declaredFields[i];   if (!declaredField.isAnnotationPresent(MyAutowired.class)) {continue;}// 有该注解// @MyAutowired("") private IDemoService demoService;MyAutowired annotation = declaredField.getAnnotation(MyAutowired.class);String beanName = annotation.value();  // 需要注入的bean的idif ("".equals(beanName.trim())) {// 没有配置具体的bean id,那就需要根据当前字段类型注入(接口注入)  IDemoServicebeanName = declaredField.getType().getName();}// 开启赋值declaredField.setAccessible(true);try {declaredField.set(entry.getValue(), ioc.get(beanName));} catch (IllegalAccessException e) {e.printStackTrace();}}}}

(5)构造一个HandlerMapping处理器映射器,将配置好的url和Method建立映射关系

/*构造一个HandlerMapping处理器映射器最关键的环节目的:将url和method建立关联*/
private void initHandlerMapping() {if (ioc.isEmpty()) {return;}for (Map.Entry<String, Object> entry : ioc.entrySet()) {// 获取ioc中当前遍历的对象的class类型Class<?> aClass = entry.getValue().getClass();if (!aClass.isAnnotationPresent( MyController.class)) {continue;}String baseUrl = "";if (aClass.isAnnotationPresent(MyRequestMapping.class)) {MyRequestMapping annotation = aClass.getAnnotation(MyRequestMapping.class);baseUrl = annotation.value(); }// 获取方法Method[] methods = aClass.getMethods();for (int i = 0; i < methods.length; i++) {Method method = methods[i];//  方法没有标识MyRequestMapping,就不处理if (!method.isAnnotationPresent(MyRequestMapping.class)) {continue;}// 如果标识,就处理MyRequestMapping annotation = method.getAnnotation(MyRequestMapping.class);String methodUrl = annotation.value();  // 计算出来的url /demo/queryString url = baseUrl + methodUrl;    // 建立url和method之间的映射关系(map缓存起来)// private Map<String,Method> handlerMapping = now HashMap<>(); handlerMapping.put(url,method);}}}

存在问题:只保存了方法,没有保存参数,没有保存具体的对象(不知道是哪个对象的方法),无法完成调用

(6)优化 - Handle封装引入

将 controller,要调用的 method,方法的参数,url 封装在一个类里

public class Handler {// method.invoke(对象,)private Object controller; private Method method;// spring中url是支持正则的private Pattern pattern; // 参数顺序,是为了进行参数绑定,key是参数名,value代表是第几个参数 <name,2>private Map<String,Integer> paramIndexMapping;
}
// 获取方法
Method[] methods = aClass.getMethods();
for (int i = 0; i < methods.length; i++) {Method method = methods[i];//  方法没有标识MyRequestMapping,就不处理if (!method.isAnnotationPresent(MyRequestMapping.class)) {continue;}// 如果标识,就处理MyRequestMapping annotation = method.getAnnotation(MyRequestMapping.class);String methodUrl = annotation.value();  // /queryString url = baseUrl + methodUrl;    // 计算出来的url /demo/query// 把method所有信息及url封装为一个HandlerHandler handler = new Handler(entry.getValue(), method, Pattern.compile(url));// 计算方法的参数位置信息  Parameter[] parameters = method.getParameters();for (int j = 0; j < parameters.length; j++) {Parameter parameter = parameters[j];if (parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {// 如果是request和response对象,那么参数名称写HttpServletRequest和HttpServletResponse,便于后续特殊识别这两个参数handler.getParamIndexMapping().put(parameter.getType().getSimpleName(), j);} else {handler.getParamIndexMapping().put(parameter.getName(), j); }}// 建立url和method之间的映射关系(map缓存起来)handlerMapping.add(handler);
}

(7)等待请求进入,处理请求

根据 url 获取 handle

// 根据uri获取到能够处理当前请求的hanlder(从handlermapping中(list))
private Handler getHandler(HttpServletRequest req) {if (handlerMapping.isEmpty()) {return null;}// 从request中获取urlString url = req.getRequestURI();for (Handler handler : handlerMapping) {Matcher matcher = handler.getPattern().matcher(url);if (!matcher.matches()) {continue;}return handler;}return null;}

从request获取参数值,根据相应位置保存到数组

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 根据uri获取到能够处理当前请求的hanlder(从handlermapping中(list))Handler handler = getHandler(req);if (handler == null) {resp.getWriter().write("404 not found");return;}// 参数绑定// 获取所有参数类型数组,这个数组的长度就是我们最后要传入的args数组的长度Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();// 根据上述数组长度创建一个新的数组(参数数组,是要传入反射调用的)Object[] paraValues = new Object[parameterTypes.length];// 以下就是为了向参数数组中塞值,而且还得保证参数的顺序和方法中形参顺序一致Map<String, String[]> parameterMap = req.getParameterMap();// 遍历request中所有参数  (填充除了request,response之外的参数)for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {// name=1&name=2   name [1,2]String value = StringUtils.join(param.getValue(), ",");  // 如同 1,2// 如果参数和方法中的参数匹配上了,填充数据  Map<String,Integer> paramIndexMapping; // 参数顺序,是为了进行参数绑定,key是参数名,value代表是第几个参数 <name,2>if (!handler.getParamIndexMapping().containsKey(param.getKey())) {continue;}// 方法形参确实有该参数,找到它的索引位置,对应的把参数值放入paraValuesInteger index = handler.getParamIndexMapping().get(param.getKey());//name在第 2 个位置paraValues[index] = value;  // 把前台传递过来的参数值填充到对应的位置去}// 获取 HttpServletRequestint requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName()); // 0paraValues[requestIndex] = req;// 获取 HttpServletResponseint responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName()); // 1paraValues[responseIndex] = resp;// 最终调用handler的method属性try {handler.getMethod().invoke(handler.getController(), paraValues);} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}}

学到微笑之 - 自定义 MVC 框架相关推荐

  1. 第一章 自定义MVC框架

    第一章  自定义MVC框架 1.1 MVC模式设计     组成:Model:模型,用于数据和业务的处理           View :视图,用于数据的显示           Controller ...

  2. PHP笔记-自定义MVC框架

    膜拜 膜拜下黑马大佬程序员的项目,学习到了这样的手写MVC框架的方式,受益匪浅,感觉自己在C/C++和Java方面,还有许多要学习的地方,看看能不能抄下这个php自己撸一个C/C++的MVC框架. 下 ...

  3. 自定义MVC框架之工具类-图像处理类

    截止目前已经改造了4个类: ubuntu:通过封装验证码类库一步步安装php的gd扩展 自定义MVC框架之工具类-分页类的封装 自定义MVC框架之工具类-文件上传类 图像处理类: 1,图片加水印处理( ...

  4. 自定义mvc框架复习(crud)

    目录 一.搭建自定义mvc框架的环境 1.1导入框架的jar包依赖 1.2导入框架配套的工具类 1.3导入框架的配置文件 1.4将框架与web容器进行集成,配置web.xml 二.完成实体类与数据库表 ...

  5. java struts2 mvc_struts2自定义MVC框架

    本文实例为大家分享了struts2自定义MVC框架的方法,供大家参考,具体内容如下 自定义MVC:(首先了解Model1和Model2的概念) Model1与Model2: Model1:就是一种纯j ...

  6. 使用Intellij Idea自定义MVC框架

    今天我学习了自定义一个简单的MVC框架,这个我们首先要知道什么是MVC框架! MVC框架: MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(co ...

  7. php mvc自定义框架视频教程,基于PHP面向对象的自定义MVC框架高级项目开发视频教程...

    ├ │  ├01-温故而知新.wmv │  ├02-验证码技术介绍.wmv │  ├03-GD处理图像的基本步骤.wmv │  ├04-画布操作基本步骤-补充.wmv │  ├05-仿制ecshop验 ...

  8. 学写一个 Java Web MVC 框架(四)

    访问请求处理 当客户端发送一个请求,被自定义的过滤器MvcDispatcher拦截,解析请求地址和参数对象跳转到一个控制器的方法中,然后执行进行逻辑处理后返回响应内容给MvcDispatcher输出, ...

  9. 学写一个 Java Web MVC 框架(一)

    当前我们介绍的是一个简单的MVC,用8个类即实现完整Spring MVC核心功能,外加其他实用的小功能.它是怎么实现的呢?让我们来一探究竟! 源码在:https://gitee.com/sp42_ad ...

最新文章

  1. 斯坦福新书《决策算法》,694页PDF免费下载
  2. saltstack的状态文件
  3. [振动力学] 课程考核报告:Matlab 实现邓克利法、瑞利法、里兹法、矩阵迭代法
  4. 【Kafka】Kafka Consumer 管理 Offset 原理
  5. mysql调换数据_mysql互换表中两列数据方法
  6. 《JQuery 能干点啥~》第7讲 层级选择器_2
  7. Redis-03-Redis集群的搭建
  8. 思维导图形式带你读完《大型网站技术架构》中
  9. html下拉框字体大小,select下拉框选择字体大小
  10. 图标搜索引擎:Findicons
  11. 高校GIS系统有何作用?
  12. 获取下一个周几的日期
  13. IDEA中的clean,清除项目缓存
  14. 尼古拉*特斯拉与通古斯大爆炸
  15. 计算机连接投影仪后黑屏咋调试,电脑连上投影仪后黑屏了,怎么处理?
  16. Java应用_模拟微信抢红包
  17. 【探究网络安全与网络安全文化及网络安全防范】计算机网络安全现状
  18. 计算机毕业设计Java学校食堂库存在线管理(源码+系统+mysql数据库+Lw文档)
  19. 主管职称计算机考试报名流程,全国专业技术计算机应用能力考试报名流程详细介绍...
  20. pr字幕模板 富有设计感premiere字幕条pr剪辑模板

热门文章

  1. WATCHMEN 守望者,好看。
  2. 测绘与设计之间的鸿沟:坐标系,教你如何将CAD与测绘数据准确叠加
  3. win10禁用操作系统的服务器,win10服务哪些可以禁止启动 win10哪些服务可以关闭禁用...
  4. OpenCV读取海康4G摄像头
  5. C++之定义动态二维数组
  6. Java类加载与初始化机制实例分析
  7. 虚拟主机和服务器的区别
  8. Uniapp壁纸小程序源码/双端微信抖音小程序源码
  9. XMLWorkerHelper生成pdf文件添加页眉页脚
  10. 未来的计算机 展望未来作文,展望未来作文(通用10篇)