zoukankan      html  css  js  c++  java
  • 手写Spring MVC框架(一) 实现简易版mvc框架

    前言

    今天,我们来参照Spring MVC执⾏的⼤致原理手写一个自己的mvc框架,可通过以下链接查看Spring MVC工作原理及源码解析系列文章:

    Spring MVC工作原理及源码解析(一) MVC原理介绍、与IOC容器整合原理

    Spring MVC工作原理及源码解析(二)DispatcherServlet实现原理及源码解析

    Spring MVC工作原理及源码解析(三) HandlerMapping和HandlerAdapter实现原理及源码解析

    Spring MVC工作原理及源码解析(四) ViewResolver实现原理及源码解析

    先梳理一下需要实现的功能点:

    • tomcat加载配置文件web.xml;
    • 调用web.xml中指定的前端控制器DispatcherServlet加载指定的配置文件(一般为springmvc.xml,本文中的为springmvc.properties);
    • 扫描相关的类,扫描注解(@Controller,@Service,@RequestMapping,@Autowired);
    • IOC容器进行相应Bean初始化以及依赖注入维护;
    • Spring MVC相关组件的初始化,建立url与method之间的映射关系——HandlerMapping(处理器映射器);
    • 等待请求进来,处理请求。

    实现过程

    闲话少说,直接来看代码。

    1、注解开发

    HardyController:

    package com.hardy.edu.mvcframework.annotations;
    
    import java.lang.annotation.*;
    
    @Documented // 表明这个注解应该被 javadoc 工具记录
    @Target(ElementType.TYPE)   // 用于设定注解使用范围,ElementType.TYPE标明该注解可用于类或者接口上,用于描述类、接口(包括注解类型) 或enum声明
    @Retention(RetentionPolicy.RUNTIME) // 指定生存周期,运行时有效
    public @interface HardyController {
        String value() default "";
    }

    HardyService:

    package com.hardy.edu.mvcframework.annotations;
    
    import java.lang.annotation.*;
    
    @Documented
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface HardyService {
        String value() default "";
    }

    HardyRequestMapping:

    package com.hardy.edu.mvcframework.annotations;
    
    import java.lang.annotation.*;
    
    @Documented
    @Target({ElementType.TYPE,ElementType.METHOD})  // 可用于类、接口或方法上
    @Retention(RetentionPolicy.RUNTIME)
    public @interface HardyRequestMapping {
        String value() default "";
    }

    HardyAutowired:

    package com.hardy.edu.mvcframework.annotations;
    
    import java.lang.annotation.*;
    
    @Documented
    @Target(ElementType.FIELD)  // 可用于域上,用于描述域
    @Retention(RetentionPolicy.RUNTIME)
    public @interface HardyAutowired {
        String value() default "";
    }

    2、Pojo类Handler

    package com.hardy.edu.mvcframework.pojo;
    
    import java.lang.reflect.Method;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.regex.Pattern;
    
    /**
     * @author HardyYao
     * @date 2021/5/13
     * @description 封装handler方法相关的信息
     */
    public class Handler {
    
        private Object controller; // method.invoke(obj,)
    
        private Method method;
    
        private Pattern pattern; // spring中url是支持正则的
    
        private Map<String,Integer> paramIndexMapping; // 参数顺序,是为了进行参数绑定,key是参数名,value代表是第几个参数 此次测试中我们传递的参数那么的map为:<name,2>
    
    
        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) {
            this.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、前端控制器实现

    package com.hardy.edu.mvcframework.servlet;
    
    import com.hardy.edu.mvcframework.annotations.HardyAutowired;
    import com.hardy.edu.mvcframework.annotations.HardyController;
    import com.hardy.edu.mvcframework.annotations.HardyRequestMapping;
    import com.hardy.edu.mvcframework.annotations.HardyService;
    import com.hardy.edu.mvcframework.pojo.Handler;
    import org.apache.commons.lang3.StringUtils;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.lang.reflect.Parameter;
    import java.util.*;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    /**
     * @author HardyYao
     * @date 2021/5/13
     * @description 前端控制器
     */
    public class HardyDispatcherServlet extends HttpServlet {
    
        private Properties properties = new Properties();
    
        // 缓存扫描到的类的全限定类名
        private List<String> classNames = new ArrayList<>();
    
        // ioc容器
        private Map<String,Object> ioc = new HashMap<>();
    
        // handlerMapping
        private List<Handler> handlerMapping = new ArrayList<>();
    
        @Override
        public void init(ServletConfig config) throws ServletException {
            // 1 加载配置文件 springmvc.properties
            String 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("hardy mvc 初始化完成....");
    
            // 6 等待请求进入,处理请求
        }
    
        /**
         * 构造一个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(HardyController.class)) {continue;}
    
                String baseUrl = "";
                if(aClass.isAnnotationPresent(HardyRequestMapping.class)) {
                    HardyRequestMapping annotation = aClass.getAnnotation(HardyRequestMapping.class);
                    baseUrl = annotation.value(); // 等同于/demo
                }
    
                // 获取方法
                Method[] methods = aClass.getMethods();
                for (int i = 0; i < methods.length; i++) {
                    Method method = methods[i];
    
                    //  方法没有标识HardyRequestMapping,就不处理
                    if(!method.isAnnotationPresent(HardyRequestMapping.class)) {continue;}
    
                    // 如果标识,就处理
                    HardyRequestMapping annotation = method.getAnnotation(HardyRequestMapping.class);
                    String methodUrl = annotation.value();  // /query
                    String url = baseUrl + methodUrl;    // 计算出来的url /demo/query
    
                    // 把method所有信息及url封装为一个Handler
                    Handler handler = new Handler(entry.getValue(),method, Pattern.compile(url));
    
                    // 计算方法的参数位置信息  // query(HttpServletRequest request, HttpServletResponse response,String name)
                    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);  // <name,2>
                        }
                    }
                    // 建立url和method之间的映射关系(map缓存起来)
                    handlerMapping.add(handler);
                }
            }
        }
    
        /**
         * 实现依赖注入
         */
        private void doAutoWired() {
            // 如果对象为空,则直接返回
            if (ioc.isEmpty()) {
                return ;
            }
            // 有对象,则进行依赖注入处理
    
            // 遍历ioc中所有对象,查看对象中的字段,是否有@HardyAutowired注解,如果有需要维护依赖注入关系
            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];   //  @HardyAutowired  private IDemoService demoService;
                    if (!declaredField.isAnnotationPresent(HardyAutowired.class)) {
                        continue;
                    }
                    // 有该注解
                    HardyAutowired annotation = declaredField.getAnnotation(HardyAutowired.class);
                    String beanName = annotation.value();  // 需要注入的bean的id
                    if ("".equals(beanName.trim())) {
                        // 没有配置具体的bean id,那就需要根据当前字段类型注入(接口注入)  IDemoService
                        beanName = declaredField.getType().getName();
                    }
                    // 开启赋值
                    declaredField.setAccessible(true);
                    try {
                        declaredField.set(entry.getValue(), ioc.get(beanName));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        /**
         * ioc容器:基于classNames缓存的类的全限定类名,以及反射技术,完成对象创建和管理
         *
         */
        private void doInstance()  {
            if (classNames.size() == 0) {
                return ;
            }
    
            try{
                for (int i = 0; i < classNames.size(); i++) {
                    String className =  classNames.get(i);  // com.hardy.demo.controller.DemoController
    
                    // 反射
                    Class<?> aClass = Class.forName(className);
                    // 区分controller,区分service'
                    if(aClass.isAnnotationPresent(HardyController.class)) {
                        // controller的id此处不做过多处理,不取value了,就拿类的首字母小写作为id,保存到ioc中
                        String simpleName = aClass.getSimpleName();// DemoController
                        String lowerFirstSimpleName = lowerFirst(simpleName); // demoController
                        Object o = aClass.newInstance();
                        ioc.put(lowerFirstSimpleName,o);
                    }else if(aClass.isAnnotationPresent(HardyService.class)) {
                        HardyService annotation = aClass.getAnnotation(HardyService.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();
            }
        }
    
        /**
         * 首字母小写方法
         * @param str
         * @return
         */
        public String lowerFirst(String str) {
            char[] chars = str.toCharArray();
            if ('A' <= chars[0] && chars[0] <= 'Z') {
                chars[0] += 32;
            }
            return String.valueOf(chars);
        }
    
        /**
         * 扫描类:scanPackage: com.hardy.demo  package---->  磁盘上的文件夹(File)  com/hardy/demo
         * @param scanPackage
         */
        private void doScan(String scanPackage) {
            String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\.", "/");
            File pack = new File(scanPackagePath);
    
            File[] files = pack.listFiles();
    
            if (files != null && files.length > 0) {
                for (File file: files) {
                    if(file.isDirectory()) { // 子package
                        // 递归
                        doScan(scanPackage + "." + file.getName());  // com.hardy.demo.controller
                    }else if(file.getName().endsWith(".class")) {
                        String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                        classNames.add(className);
                    }
                }
            }
        }
    
        /**
         * 加载配置文件
         * @param contextConfigLocation
         */
        private void doLoadConfig(String contextConfigLocation) {
            InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
            try {
                properties.load(resourceAsStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        /**
         *  接收处理请求
         * @param req
         * @param resp
         * @throws ServletException
         * @throws IOException
         */
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doPost(req, resp);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            // 处理请求:根据url,找到对应的Method方法,进行调用
            // 获取uri
    //        String requestURI = req.getRequestURI();
    //        Method method = handlerMapping.get(requestURI);// 获取到一个反射的方法
            // 反射调用,需要传入对象,需要传入参数,此处无法完成调用,没有把对象缓存起来,也没有参数!!!!改造initHandlerMapping();
    //        method.invoke() //
    
    
            // 根据uri获取到能够处理当前请求的hanlder(从handlermapping中(list))
            Handler handler = getHandler(req);
    
            // handler为空则返回:404 not found
            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
    
                // 如果参数和方法中的参数匹配上了,填充数据
                if (!handler.getParamIndexMapping().containsKey(param.getKey())) {
                    continue ;
                }
    
                // 方法形参确实有该参数,找到它的索引位置,对应的把参数值放入paraValues
                Integer index = handler.getParamIndexMapping().get(param.getKey());//name在第 2 个位置
    
                paraValues[index] = value;  // 把前台传递过来的参数值填充到对应的位置去
            }
    
            int requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName()); // 0
            paraValues[requestIndex] = req;
    
            int responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName()); // 1
            paraValues[responseIndex] = resp;
    
            // 最终调用handler的method属性
            try {
                handler.getMethod().invoke(handler.getController(), paraValues);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    
        private Handler getHandler(HttpServletRequest req) {
            // 为空则直接返回null
            if (handlerMapping.isEmpty()) {
                return null;
            }
    
            String url = req.getRequestURI();
            // 遍历handlerMapping
            for (Handler handler : handlerMapping) {
                // pattern封装了url,判断其是否匹配url
                Matcher matcher = handler.getPattern().matcher(url);
                // 不匹配则跳过
                if (!matcher.matches()) {
                    continue;
                }
                // 匹配则返回handler
                return handler;
            }
            return null;
        }
    
    }

    4、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>
        <servlet-name>hardymvc</servlet-name>
        <servlet-class>com.hardy.edu.mvcframework.servlet.HardyDispatcherServlet</servlet-class>
        <!-- servlet需要加载的配置文件-->
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>springmvc.properties</param-value>
        </init-param>
      </servlet>
    
      <!--  配置映射,拦截所有  -->
      <servlet-mapping>
        <servlet-name>hardymvc</servlet-name>
        <url-pattern>/*</url-pattern>
      </servlet-mapping>
    </web-app>

    5、springmvc.properties

    scanPackage=com.hardy.demo

    调用过程

    IDemoService:

    package com.hardy.demo.service;
    
    /**
     * @author HardyYao
     * @date 2021/5/13
     * @description
     */
    public interface IDemoService {
    
        String get(String name);
    }

    DemoServiceImpl:

    package com.hardy.demo.service.impl;
    
    import com.hardy.demo.service.IDemoService;
    import com.hardy.edu.mvcframework.annotations.HardyService;
    
    /**
     * @author HardyYao
     * @date 2021/5/13
     * @description
     */
    @HardyService("demoService")
    public class DemoServiceImpl implements IDemoService {
    
        @Override
        public String get(String name) {
            System.out.println("service 实现类中的name参数:" + name) ;
            return name;
        }
    
    }

    DemoController:

    package com.hardy.demo.controller;
    
    import com.hardy.demo.service.IDemoService;
    import com.hardy.edu.mvcframework.annotations.HardyAutowired;
    import com.hardy.edu.mvcframework.annotations.HardyController;
    import com.hardy.edu.mvcframework.annotations.HardyRequestMapping;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * @author HardyYao
     * @date 2021/5/13
     * @description
     */
    @HardyController
    @HardyRequestMapping("/demo")
    public class DemoController {
    
        @HardyAutowired
        private IDemoService demoService;
    
        /**
         * URL: /demo/query?name=zhangsan
         * @param request
         * @param response
         * @param name
         * @return
         */
        @HardyRequestMapping("/query")
        public String query(HttpServletRequest request, HttpServletResponse response, String name) {
            return demoService.get(name);
        }
    
    }

    完整的项目结构如下所示:

    运行结果

    使用插件tomcat运行项目,使用debug模式,运行后访问:http://localhost:8080/,控制台会打印:hardy mvc 初始化完成.... 的消息,如下所示:

    由于没有指明要调用哪个接口,故返回:404 not found,如下所示:

    访问我们前面编写好的接口:/demo/query?name=zhangsan,访问结果如下所示:

     

    由上述结果可知,因为后端接口没有返回对应的视图,故页面返回结果为空,但控制台确实打印出了我们传递的参数信息,可以看到我们的自定义mvc框架实现了它的基本功能。

    分析接口请求参数

    最后我们看一下调试打断点时 各个参数的情况,如下图所示,可以看到handler中封装了controller、访问的接口、匹配到的url及参数顺序等信息:

    接口请求对应的参数类型及参数值如下所示:

    总结

    今天我们自定义了一个mvc框架,该框架实现了:加载配置文件、扫描相关的类,扫描注解、Bean初始化以及依赖注入维护、Spring MVC相关组件的初始化、建立url与method之间的映射关系及接受并处理请求的功能。

    虽然这里仅仅实现了最基本的功能,但是需要学习的东西也还是挺多的,部分代码也是比较复杂的。

    下一篇文章,会在Spring MVC框架的基础上实现访问拦截的功能。

    作者:blayn
    出处:https://www.cnblogs.com/blayn/
    版权:本文版权归作者和博客园共有
    转载:欢迎转载,但未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必究法律责任
  • 相关阅读:
    WebConfig配置文件详解
    python标准库介绍——32 Queue 模块详解
    python标准库介绍——31 threading 模块详解
    python标准库介绍——30 code 模块详解
    python标准库介绍——29 zlib 模块详解
    python标准库介绍——28 sha 模块详解
    python标准库介绍——28 md5 模块详解
    python标准库介绍——27 random 模块详解
    python标准库介绍——26 getopt 模块详解
    python标准库介绍——25 errno 模块详解
  • 原文地址:https://www.cnblogs.com/blayn/p/14716142.html
Copyright © 2011-2022 走看看