美文网首页
springMVC的实现原理

springMVC的实现原理

作者: 陈柴盐 | 来源:发表于2019-04-28 11:22 被阅读0次

    前情提要:

    servlet忘了的看这个:https://www.jianshu.com/p/6c2d22b00293
    反射忘了的看这个:https://www.jianshu.com/p/a15245e52a31
    注解与反射结合看这个:https://www.jianshu.com/p/e8daaa56d70f

    目录结构:


    image.png

    步骤:

    1.自定义注解

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

    2.定义Controller层

    @DefineController("/test")
    public class TestController {
    
        @DefineRequestMapping("/test")
        public String test(){
            return "index";
        }
    }
    

    3.定义Servlet(重点)

    import com.demo.web.annotation.DefineController;
    import com.demo.web.annotation.DefineRequestMapping;
    import com.demo.web.utils.ClassUtils;
    
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.List;
    import java.util.concurrent.ConcurrentHashMap;
    
    public class DefineDispatcherServlet extends HttpServlet {
        
        //用來存放spring mvc的bean
        private ConcurrentHashMap<String,Object> springMVCBeans = new ConcurrentHashMap<>();
        //url與類映射
        private ConcurrentHashMap<String,Object> urlBeans = new ConcurrentHashMap<>();
         //url與方法映射
        private ConcurrentHashMap<String,String> urlMethod = new ConcurrentHashMap<>();
    
        /**
         * 服务器启动时会读取web.xml中的servlet,自动执行Servlet的init方法
         * init要完成的工作:获取含有@DefineController的类
         *                             获取含有@DefineRequestMapping的修饰的方法
         */
        @Override
        public void init() throws ServletException {
            System.out.println("DefineDispatcherServlet开始初始化");
            //获取包下的所有类
            String packages = "com.demo.web.controller";
            List<Class<?>> classList= null;
            try {
                classList = ClassUtils.getClassName(packages);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            //将含有@DefineController注解的类放入Map中
            findAndInitMyControllerClass(classList);
            //将含有@DefineRequestMapping注解的方法,根据url与方法生产Map
            handlerMapping(springMVCBeans);
            super.init();
        }
    
        //将含有@DefineController注解的类放入Map中
        private void findAndInitMyControllerClass(List<Class<?>> classList)  {
            try {
                for (Class c : classList){
                    DefineController annotation = (DefineController) c.getAnnotation(DefineController.class);
                    if (annotation != null){
                        Object o = c.newInstance();
                        /*获取类名首字母小写*/
                        String simpleName = c.getSimpleName();
                        String name = (simpleName.charAt(0)+"").toLowerCase()+simpleName.substring(1);
                        springMVCBeans.put(name, o);
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        
        // //将含有@DefineRequestMapping注解的方法,根据url与方法生产Map
        private void handlerMapping(ConcurrentHashMap<String, Object> springMVCBeans) {
            for (String key : springMVCBeans.keySet()){
                Object o = springMVCBeans.get(key);
                DefineController defineController = o.getClass().getAnnotation(DefineController.class);
                Method[] methods = o.getClass().getMethods();
                String url = "";
                for (Method method : methods){
                    DefineRequestMapping defineRequestMapping = method.getAnnotation(DefineRequestMapping.class);
                    if (defineRequestMapping != null){
                        //1.拼接url
                        url = defineController.value() + defineRequestMapping.value();
                        //2.url與方法映射
                        urlMethod.put(url, method.getName());
                    }
                }
                //3.url與類映射
                urlBeans.put(url, o);
            }
        }
    
    
        @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 {
            try {
                doDispatch(req,resp);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    
    
        /**
         * 无论是走doGet还是走doPost最终都还是走doDispatch
         * 步骤:1.获取请求的连接
         *         2.获取根据连接的url从urlMethod中获取方法名
         *         3.反射执行方法,这时可以从TestController中的test方法中获取到跳转地址index
         *         4. 进入视图解析器
         */
        private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws  IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, ServletException{
            //获取请求连接
            String url = req.getRequestURI();
            Object o = urlBeans.get(url); //返回值:/test/test
    
            if (o == null) {
                resp.getWriter().println("404 not found");
            }
    
            //反射执行方法
            String methodName = urlMethod.get(url);
            Method method = o.getClass().getMethod(methodName);
            Class<?>[] parameterTypes = method.getParameterTypes();
            Object result = method.invoke(o, parameterTypes);
            
            //视图解析器
            viewResolver((String) result,req,resp);
        }
    
        private void viewResolver(String pageName, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String suffix = ".jsp";
            String prefix = "/";
            req.getRequestDispatcher(prefix + pageName + suffix).forward(req, resp);
        }
    
    
    }
    
    

    ClassUtils

    import java.io.File;
    import java.net.URL;
    import java.net.URLClassLoader;
    import java.util.ArrayList;
    import java.util.Enumeration;
    import java.util.List;
    import java.util.jar.JarEntry;
    import java.util.jar.JarFile;
    
    public class ClassUtils {
    
        /**
         * 获取某包下(包括该包的所有子包)所有类
         * @param packageName 包名
         * @return 类的完整名称
         */
        public static List<Class<?>> getClassName(String packageName) throws ClassNotFoundException {
            return getClassName(packageName, true);
        }
    
        /**
         * 获取某包下所有类
         * @param packageName 包名
         * @param childPackage 是否遍历子包
         * @return 类的完整名称
         */
        public static List<Class<?>> getClassName(String packageName, boolean childPackage) throws ClassNotFoundException {
            List<Class<?>> fileNames = null;
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            String packagePath = packageName.replace(".", "/");
            URL url = loader.getResource(packagePath);
            if (url != null) {
                String type = url.getProtocol();
                if (type.equals("file")) {
                    fileNames = getClassNameByFile(url.getPath(), null, childPackage);
                } else if (type.equals("jar")) {
                    fileNames = getClassNameByJar(url.getPath(), childPackage);
                }
            } else {
                fileNames = getClassNameByJars(((URLClassLoader) loader).getURLs(), packagePath, childPackage);
            }
            return fileNames;
        }
    
        /**
         * 从项目文件获取某包下所有类
         * @param filePath 文件路径
         * @param className 类名集合
         * @param childPackage 是否遍历子包
         * @return 类的完整名称
         */
        private static List<Class<?>> getClassNameByFile(String filePath, List<Class<?>> className, boolean childPackage) throws ClassNotFoundException {
            List<Class<?>> myClassName = new ArrayList<Class<?>>();
            File file = new File(filePath);
            File[] childFiles = file.listFiles();
            for (File childFile : childFiles) {
                if (childFile.isDirectory()) {
                    if (childPackage) {
                        myClassName.addAll(getClassNameByFile(childFile.getPath(), myClassName, childPackage));
                    }
                } else {
                    String childFilePath = childFile.getPath();
                    if (childFilePath.endsWith(".class")) {
                        childFilePath = childFilePath.substring(childFilePath.indexOf("\\classes") + 9, childFilePath.lastIndexOf("."));
                        childFilePath = childFilePath.replace("\\", ".");
                        myClassName.add(Class.forName(childFilePath));
                    }
                }
            }
    
            return myClassName;
        }
    
        /**
         * 从jar获取某包下所有类
         * @param jarPath jar文件路径
         * @param childPackage 是否遍历子包
         * @return 类的完整名称
         */
        private static List<Class<?>> getClassNameByJar(String jarPath, boolean childPackage) {
            List<Class<?>> myClassName = new ArrayList<Class<?>>();
            String[] jarInfo = jarPath.split("!");
            String jarFilePath = jarInfo[0].substring(jarInfo[0].indexOf("/"));
            String packagePath = jarInfo[1].substring(1);
            try {
                JarFile jarFile = new JarFile(jarFilePath);
                Enumeration<JarEntry> entrys = jarFile.entries();
                while (entrys.hasMoreElements()) {
                    JarEntry jarEntry = entrys.nextElement();
                    String entryName = jarEntry.getName();
                    if (entryName.endsWith(".class")) {
                        if (childPackage) {
                            if (entryName.startsWith(packagePath)) {
                                entryName = entryName.replace("/", ".").substring(0, entryName.lastIndexOf("."));
                                myClassName.add(Class.forName(entryName));
                            }
                        } else {
                            int index = entryName.lastIndexOf("/");
                            String myPackagePath;
                            if (index != -1) {
                                myPackagePath = entryName.substring(0, index);
                            } else {
                                myPackagePath = entryName;
                            }
                            if (myPackagePath.equals(packagePath)) {
                                entryName = entryName.replace("/", ".").substring(0, entryName.lastIndexOf("."));
                                myClassName.add(Class.forName(entryName));
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return myClassName;
        }
    
        /**
         * 从所有jar中搜索该包,并获取该包下所有类
         * @param urls URL集合
         * @param packagePath 包路径
         * @param childPackage 是否遍历子包
         * @return 类的完整名称
         */
        private static List<Class<?>> getClassNameByJars(URL[] urls, String packagePath, boolean childPackage) {
            List<Class<?>> myClassName = new ArrayList<Class<?>>();
            if (urls != null) {
                for (int i = 0; i < urls.length; i++) {
                    URL url = urls[i];
                    String urlPath = url.getPath();
                    // 不必搜索classes文件夹
                    if (urlPath.endsWith("classes/")) {
                        continue;
                    }
                    String jarPath = urlPath + "!/" + packagePath;
                    myClassName.addAll(getClassNameByJar(jarPath, childPackage));
                }
            }
            return myClassName;
        }
    }
    

    4.web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://java.sun.com/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
             version="3.0">
    
        <servlet>
            <servlet-name>dispatcher</servlet-name>
            <servlet-class>com.demo.web.servlet.DefineDispatcherServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>dispatcher</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
    </web-app>
    
    

    5.index.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
      <head>
        <title></title>
      </head>
      <body>
                 你好世界
      </body>
    </html>
    

    6.启动与访问


    image.png

    过程:
    启动tomcat->
    加载web.xml->
    通过web.xml的配置获取DefineDispatcherServlet->
    执行init方法获取Controller层的类和方法以及对应的url->
    用户浏览器输入url->
    服务器根据用户的url获取对应的方法->
    执行对应的方法结果返回需要跳转的路径->
    通过视图解析器跳转到对应的连接

    相关文章

      网友评论

          本文标题:springMVC的实现原理

          本文链接:https://www.haomeiwen.com/subject/nuirnqtx.html