SpringMVC架構模擬

此次來學習一下SpringMVC的源碼.前端

對於常見的項目架構模式,好比大名鼎鼎的SSM(SpringMVC,Spring,Mybatis)框架.java

SpringMVC ->web層(Controller層)web

Spring ->service層spring

mybatis ->dao層數組

從SpringMVC層面上講,他的構成以下:瀏覽器

Model ->數據網絡

View ->視圖mybatis

Controller ->業務架構

通過上面的分層,使得數據,視圖(展現效果),業務邏輯進行分離,每一層的變化能夠不影響其餘層,增長程序的可維護性和可擴展性。併發

 

  1. 瀏覽器發出用戶請求,處於web.xml中的dispacherServlet前端控制器進行接收,此時這個前端控制器並不處理請求.而是將用戶發送的url請求轉發到HandleMapping處理器映射器
  2. 第二步:HandlerMapping根據請求路徑找到相對應的HandlerAdapter處理器適配器(處理器適配器就是那些攔截器或者是controller)
  3. 第三步:HandlerAdapter處理器適配器,能夠處理一些功能請求,返回一個ModelAndView對象(包括模型數據/邏輯視圖名)
  4. 第四步:ViewResolver視圖解析器,先根據 ModelAndView中設置的view解析具體視圖
  5. 第五步:而後再將Model模型中的數據渲染到View中

下面咱們實際在項目中進行操做

一丶建立一個帶有web.xml的maven項目

二丶首先本身寫一個類繼承HttpServlet類並重寫它的doGet,doPost方法

package com.spring.mvc.config;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: XiaoZhe
 * @Description:
 * @Date: Created in 17:39 2019/12/16
 */
public class MyDispatchServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("這是調用了doGet方法");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("這是調用了doPost方法");
    }
}

 

三丶修改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>
  <!--註冊servlet-->
  <servlet>
    <!--本身繼承了HttpServlet類的名字-->
    <servlet-name>httpServletTest</servlet-name>
    <!--本身繼承了HttpServlet類的所在路徑-->
    <servlet-class>com.spring.mvc.servlet.MyDispatchServlet</servlet-class>
  </servlet>
  <!--映射servlet-->
  <servlet-mapping>
    <!--上面自定義的servlet-name-->
    <servlet-name>httpServletTest</servlet-name>
    <!--攔截路徑/* -->
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>

 

 

四丶 啓動項目,在地址欄輸入項目地址並回車

能夠看到控制檯打印輸出了咱們定義的話

這是調用了doGet方法
這是調用了doGet方法

 

五丶建立幾個註解@Controller,@RequestMapping

用過SpringMVC框架的人都知道在類上打了@Controller註解的才能被認做是一個Controller,而打了@RequestMapping才能被請求映射。

@MyController

package com.spring.mvc.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @Author: ZhengZhe
 * @Description: 做用於class上的功能相似於Spring的@Controller註解
 * @Date: Created in 10:34 2019/12/17
 */
@Target(ElementType.TYPE)//標識此註解只能做用在類上面
@Retention(RetentionPolicy.RUNTIME)//標識此註解一直存活,可被反射獲取
public @interface MyController {
}

 

@MyRequestMapping

package com.spring.mvc.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @Author: ZhengZhe
 * @Description: 做用於class或者method上的功能相似於Spring的@RequestMapping註解
 * @Date: Created in 10:38 2019/12/17
 */
@Target({ElementType.TYPE,ElementType.METHOD})//標識此註解只能做用在類或者方法上面
@Retention(RetentionPolicy.RUNTIME)//標識此註解一直存活,可被反射獲取
public @interface MyRequestMapping {
    String value();//用來存儲對應的url , 網絡請求路徑
}

 

六丶DispatchServlet

DispatchServlet在MVC引導着很是強大的做用,網絡中的請求傳到DispatchServlet中,由DispatchServlet進行截取分析並傳到對應的由@Controller和@RequestMapping註解的類或方法中,使得網路請求能正確的請求到對應的資源上.

下面咱們自定義一個DispatchServlet實現他所實現的功能

首先看一下源碼中MVC作了什麼

protected void initStrategies(ApplicationContext context) {
        this.initMultipartResolver(context);
        this.initLocaleResolver(context);
        this.initThemeResolver(context);
        this.initHandlerMappings(context);
        this.initHandlerAdapters(context);
        this.initHandlerExceptionResolvers(context);
        this.initRequestToViewNameTranslator(context);
        this.initViewResolvers(context);
        this.initFlashMapManager(context);
    }

 

從上面咱們能夠看到初始化方法的參數是ApplicationContext,這個是IOC的初始化容器,我以前的博客中解析過IOC的源碼,不懂的能夠去裏面解讀.

initStrategies方法的目的就是從容器中獲取已經解析出來的bean資源,並獲取其帶有@Controller和@RequestMapping註解的bean資源.

protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (this.logger.isDebugEnabled()) {
            String resumed = WebAsyncUtils.getAsyncManager(request).hasConcurrentResult() ? " resumed" : "";
            this.logger.debug("DispatcherServlet with name '" + this.getServletName() + "'" + resumed + " processing " + request.getMethod() + " request for [" + getRequestUri(request) + "]");
        }

        Map<String, Object> attributesSnapshot = null;
        if (WebUtils.isIncludeRequest(request)) {
            attributesSnapshot = new HashMap();
            Enumeration attrNames = request.getAttributeNames();

            label108:
            while(true) {
                String attrName;
                do {
                    if (!attrNames.hasMoreElements()) {
                        break label108;
                    }

                    attrName = (String)attrNames.nextElement();
                } while(!this.cleanupAfterInclude && !attrName.startsWith("org.springframework.web.servlet"));

                attributesSnapshot.put(attrName, request.getAttribute(attrName));
            }
        }

        request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.getWebApplicationContext());
        request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
        request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver);
        request.setAttribute(THEME_SOURCE_ATTRIBUTE, this.getThemeSource());
        FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(request, response);
        if (inputFlashMap != null) {
            request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap));
        }

        request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
        request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager);

        try {
            this.doDispatch(request, response);
        } finally {
            if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted() && attributesSnapshot != null) {
                this.restoreAttributesAfterInclude(request, attributesSnapshot);
            }

        }

    }

 

doService方法其實目的就是解析用戶的請求路徑,根據請求路徑找到對應類和方法,使用反射調用.

七丶MyDispatchServlet(自定義前端控制器)

咱們本身寫代碼來實現對應的init方法和Service方法的功能.

package com.spring.mvc.servlet;

import com.spring.mvc.annotation.MyController;
import com.spring.mvc.annotation.MyRequestMapping;

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.lang.reflect.Method;
import java.net.URL;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @Author: ZhengZhe
 * @Description:
 * @Date: Created in 10:56 2019/12/17
 */
public class MyDispatchServlet extends HttpServlet{
    //咱們定義兩個集合去存儲掃描到的帶有@MyController 和 @MyRequestMapping註解的類或者方法
    //存放 被@MyRequestMapping註解修飾的類或者方法
    private ConcurrentHashMap<String,Method> MyMethodsCollection = new ConcurrentHashMap();
    //存放 被@MyController註解修飾的類
    private ConcurrentHashMap<String,Object> MyControllerCollection = new ConcurrentHashMap();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        MyInit(req,resp);

        MyService(req,resp);

    }

    /**
     * 做用是 : 根據配置的包名,掃描全部包含@MyController註解修飾的類和@MyRequestMapping註解修飾的類或者方法
     *並將對應的 beanName放入上面定義的 集合中
     * @param req
     * @param resp
     */
    private void MyInit(HttpServletRequest req, HttpServletResponse resp) {
        //在源碼中,有IOC實現了容器的掃描和初始化,MVC中只是直接拿出來,可是這個方法中咱們就不經過容器去獲取了
        //直接掃描而且存入上面的集合中就能夠了
        String basePackage ="com.spring.mvc";
        //根據傳入的包路徑,掃描包,此時只是將該包下全部的文件資源存入集合中,可是並無篩選加了@MyController和
        //@RequestMapping註解的類,即掃描全部.class字節碼對象並保存起來
        ConcurrentHashMap<String, Class<?>> scannerClass = scannerClass(basePackage);

        //下面直接進行篩選@MyController和@RequestMapping註解的類
        Set<Map.Entry<String, Class<?>>> entrySet = scannerClass.entrySet();
        for (Map.Entry<String, Class<?>> entry : entrySet) {
            //獲取key : 類名稱
            String className = entry.getKey();
            //獲取value : 對應的.class字節碼對象
            Class<?> clazz = entry.getValue();
            //定義MyRequestMapping的url
            String classUrl = "";
            try {
                //該類是否標記了MyController註解
                if (clazz.isAnnotationPresent(MyController.class)){
                    //該類是否標記了MyRequestMapping註解
                    if (clazz.isAnnotationPresent(MyRequestMapping.class)){
                        //若是該類被MyRequestMapping註解所標識,獲取其屬性url值
                        MyRequestMapping requestMapping = clazz.getAnnotation(MyRequestMapping.class);
                        classUrl = requestMapping.value();
                    }
                    //將被標識了MyController註解的類存入集合中
                    MyControllerCollection.put("className",clazz.newInstance());
                    //判斷該類中的方法是否標識了@MyRequestMapping註解,若是標識了存入MyMethodsCollection集合中
                    //獲取該類下的方法
                    Method[] methods = clazz.getMethods();//獲取該類中的方法數組
                    //遍歷該數組
                    for (Method method : methods) {
                        //判斷是否被@MyRequestMapping註解標識
                        if (method.isAnnotationPresent(MyRequestMapping.class)){
                            //已被@MyRequestMapping註解標識
                            //獲取其url
                            MyRequestMapping myRequestMapping = method.getAnnotation(MyRequestMapping.class);
                            //獲取method上的url
                            String methodUrl = myRequestMapping.value();
                            //拼接兩端MyController和method的url
                            MyMethodsCollection.put(classUrl+methodUrl,method);
                        }
                    }


                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    //根據傳入的包路徑,進行bean資源的獲取,通常能夠在xml中設置包路徑.可是咱們直接給出便可(簡單)
    private static ConcurrentHashMap<String, Class<?>> scannerClass(String basePackage) {
        ConcurrentHashMap<String, Class<?>> result = new ConcurrentHashMap<>();
        //把com.spring.mvc 換成com/spring/mvc再類加載器讀取文件
        String basePath = basePackage.replaceAll("\\.", "/");
        try {
            //獲得com/spring/mvc的絕對地址 /D:xxxxx/com/spring/mvc
            String rootPath = MyDispatchServlet.class.getClassLoader().getResource(basePath).getPath();
            //只留com/ming/mvc 目的爲了後續拼接成一個全限定名
            if (rootPath != null) {
                rootPath = rootPath.substring(rootPath.indexOf(basePath));
            }
            Enumeration<URL> enumeration = MyDispatchServlet.class.getClassLoader().getResources(basePath);
            while (enumeration.hasMoreElements()) {
                URL url = enumeration.nextElement();
                if (url.getProtocol().equals("file")) {//若是是個文件
                    File file = new File(url.getPath().substring(1));
                    scannerFile(file, rootPath, result);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;

    }

    //遞歸掃描文件
    private static void scannerFile(File folder, String rootPath, ConcurrentHashMap<String, Class<?>> classes) {
        try {
            File[] files = folder.listFiles();
            for (int i = 0; files != null && i < files.length; i++) {
                File file = files[i];
                if (file.isDirectory()) {
                    scannerFile(file, rootPath + file.getName() + "/", classes);
                } else {
                    if (file.getName().endsWith(".class")) {
                        String className = (rootPath + file.getName()).replaceAll("/", ".");
                        className = className.substring(0, className.indexOf(".class"));//去掉擴展名獲得全限定名
                        //Map容器存儲全限定名和Class
                        classes.put(className, Class.forName(className));
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 做用是 : 解析用戶的請求路徑,,根據請求路徑找到對應的類和方法,並使用反射調用其方法
     * @param req
     * @param resp
     */
    private void MyService(HttpServletRequest req, HttpServletResponse resp) {
        //在MyInit中咱們已將被@MyController和@MyRequestMapping註解標識的類或者方法存入對應的集合中了;
        //下面咱們須要將網絡請求中的url和咱們容器中初始化好的url進行匹配,若是匹配成功,那麼直接執行此方法
        //返回除去host(域名或者ip)部分的路徑(包含)
        String requestURI = req.getRequestURI();//相似test/test
        //返回工程名部分,若是工程映射爲/,此處返回則爲空 (工程名即項目名)
        String contextPath = req.getContextPath();//相似test
        //獲取實際除 ip,端口,項目名外的請求路徑
        //如web.xml中的servlet攔截路徑設置的爲/* 採用下面的方法,若是採用的是/*.do或者/*.action相似的後綴,須要把後面的也去掉
        String requestMappingPath = requestURI.substring(contextPath.length());
        //經過截取到的實際的請求url爲key獲取對應的方法
        Method method = MyMethodsCollection.get(requestMappingPath);
        try {
            if (method == null){
                //此時就是大名鼎鼎的404 了~
                //直接返回404
                resp.sendError(404);
                return;
            }
            //存在,那麼直接執行
            //獲取方法所對應的的class<?>字節碼文件
            Class<?> declaringClass = method.getDeclaringClass();
            //下面按照源碼來講還須要去判斷是不是單例等操做,咱們直接省去
            method.invoke(declaringClass.newInstance());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("這是調用了doPost方法");
    }
}

 

八丶建立ControllerTest測試類

package com.spring.mvc.controller;

import com.spring.mvc.annotation.MyController;
import com.spring.mvc.annotation.MyRequestMapping;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: ZhengZhe
 * @Description:
 * @Date: Created in 15:07 2019/12/17
 */
@MyController
@MyRequestMapping("/hello")
public class ControllerTest {


    @MyRequestMapping("/world")
    public void helloworld(){
        System.out.println("自定義MVC測試成功~ ,如今時間是"+System.currentTimeMillis());
    }
}

 

查看控制檯輸出:

信息: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
[2019-12-17 03:33:26,276] Artifact mvc:war exploded: Artifact is deployed successfully
[2019-12-17 03:33:26,276] Artifact mvc:war exploded: Deploy took 565 milliseconds
自定義MVC測試成功~ ,如今時間是1576568012163

 

————————————————

本人免費整理了Java高級資料,涵蓋了Java、Redis、MongoDB、MySQL、Zookeeper、Spring Cloud、Dubbo高併發分佈式等教程,一共30G,須要本身領取。
傳送門:https://mp.weixin.qq.com/s/osB-BOl6W-ZLTSttTkqMPQ

相關文章
相關標籤/搜索