自定義模擬實現springMVC

實現步驟:

  • 加載配置文件 springmvc.properties
  • 掃描相關的類,掃描註解
  • 初始化bean對象(實現ioc容器,基於註解)
  • 實現依賴注入
  • 構造一個HandlerMapping處理器映射器,將配置好的url和Method建立映射關係

具體代碼:

public class DispatcherServlet extends HttpServlet {


    private Properties properties = new Properties();

    private List<String> classNames = new ArrayList<>(); // 緩存掃描到的類的全限定類名

    // ioc容器
    private Map<String,Object> ioc = new HashMap<String,Object>();


    // handlerMapping
    //private Map<String,Method> handlerMapping = now HashMap<>(); // 存儲url和Method之間的映射關係
    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("lagou mvc 初始化完成....");

        // 等待請求進入,處理請求
    }

    /*
        構造一個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(LagouController.class)) {continue;}


            String baseUrl = "";
            if(aClass.isAnnotationPresent(LagouRequestMapping.class)) {
                LagouRequestMapping annotation = aClass.getAnnotation(LagouRequestMapping.class);
                baseUrl = annotation.value(); // 等同於/demo
            }


            // 獲取方法
            Method[] methods = aClass.getMethods();
            for (int i = 0; i < methods.length; i++) {
                Method method = methods[i];

                //  方法沒有標識LagouRequestMapping,就不處理
                if(!method.isAnnotationPresent(LagouRequestMapping.class)) {continue;}

                // 如果標識,就處理
                LagouRequestMapping annotation = method.getAnnotation(LagouRequestMapping.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中所有對象,查看對象中的字段,是否有@LagouAutowired註解,如果有需要維護依賴注入關係
        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];   //  @LagouAutowired  private IDemoService demoService;
                if(!declaredField.isAnnotationPresent(LagouAutowired.class)) {
                    continue;
                }


                // 有該註解
                LagouAutowired annotation = declaredField.getAnnotation(LagouAutowired.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.lagou.demo.controller.DemoController

                // 反射
                Class<?> aClass = Class.forName(className);
                // 區分controller,區分service'
                if(aClass.isAnnotationPresent(LagouController.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(LagouService.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();
        }






    }


    // 首字母小寫方法
    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.lagou.demo  package---->  磁盤上的文件夾(File)  com/lagou/demo
    private void doScan(String scanPackage) {
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
        File pack = new File(scanPackagePath);

        File[] files = pack.listFiles();

        for(File file: files) {
            if(file.isDirectory()) { // 子package
                // 遞歸
                doScan(scanPackage + "." + file.getName());  // com.lagou.demo.controller
            }else if(file.getName().endsWith(".class")) {
                String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                classNames.add(className);
            }
            
        }


    }

    // 加載配置文件
    private void doLoadConfig(String contextConfigLocation) {

        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);

        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    @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);

        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) {
        if(handlerMapping.isEmpty()){return null;}

        String url = req.getRequestURI();

        for(Handler handler: handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(url);
            if(!matcher.matches()){continue;}
            return handler;
        }

        return null;

    }

}


發佈了24 篇原創文章 · 獲贊 11 · 訪問量 5521
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章