【JAVA】手写Spring框架(2)

上篇文章已经将基础的准备好了,接下来开始核心代码的编写,主要在DisServlet类中

 

DisServlet

package com.servlet;

import com.annotation.Autowired;
import com.annotation.RequestMapping;
import com.annotation.RestController;
import com.annotation.Service;

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.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: SpringMvc
 * @description: servlet
 * @author: Deng.Hua
 * @create: 2019-02-22 09:43
 **/
public class DisServlet extends HttpServlet {
    ArrayList<String> classList = new ArrayList();
    Map<String, Object> iocMap = new HashMap<>();
    Map<String, Object> urlMap = new HashMap<String, Object>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = req.getRequestURI();
        String path = req.getContextPath();
        /**
         * 处理请求的路径
         */
        String methodPath = url.replace(path, "").replace("/", "");
        Method method = (Method) urlMap.get(methodPath);
        Object[] args = {req, resp};
        method.getName();
        try {
            /**
             * 根据获取到的方法,获取其方法所在控制器
             */
            method.invoke(iocMap.get(method.getDeclaringClass().getName().toLowerCase()), args);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

    }

    @Override
    public void init() throws ServletException {
        //扫描控制类,并将其放入到容器中
        doInit("com");
        //将容器中的类实例化
        doInstace();
        //依赖注入,
        doPj();
        //地址映射
        doYingShe();

    }


    private void doInit(String basePath) {
        URL path = this.getClass().getClassLoader().getResource("/" + basePath.replaceAll("\\.", "/"));
        String fileStr = path.getFile();
        File file = new File(fileStr);
        String[] fileList = file.list();
        for (String f : fileList) {
            File filePath = new File(fileStr + f);
            if (filePath.isDirectory()) {
                doInit(basePath + "." + f);
            } else {
                classList.add(basePath + "." + f);
            }
        }


    }

    private void doInstace() {
        try {
            for (String className : classList) {
                String classPath = className.replace(".class", "");
                Class<?> clazz = Class.forName(classPath);
                if (clazz.isAnnotationPresent(RestController.class)) {
                    //判断是否为控制类,是将其放入IOC容器中
                    Object object = clazz.newInstance();
                    String key = clazz.getName().toLowerCase();
                    iocMap.put(key, object);
                } else if (clazz.isAnnotationPresent(Service.class)) {
                    Object object = clazz.newInstance();
                    String key = clazz.getName().toLowerCase();
                    iocMap.put(key, object);
                } else {
                    continue;
                }

            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    private void doPj() {
        for (Map.Entry<String, Object> beans : iocMap.entrySet()) {
            Object instance = beans.getValue();
            Class<?> clazz = instance.getClass();
            if (clazz.isAnnotationPresent(RestController.class)) {
                Field[] fields = clazz.getDeclaredFields();
                for (Field field : fields) {
                    if (field.isAnnotationPresent(Autowired.class)) {
                        Autowired autowired = field.getAnnotation(Autowired.class);
                        Object object = iocMap.get(field.getType().getName().toLowerCase());
                        field.setAccessible(true);
                        try {
                            field.set(instance, object);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }

                    }
                }

            } else {
                continue;
            }
        }


    }

    private void doYingShe() {
        for (Map.Entry<String, Object> beans : iocMap.entrySet()) {
            Object instance = beans.getValue();
            Class<?> clazz = instance.getClass();
            if (clazz.isAnnotationPresent(RestController.class)) {
                RequestMapping requestMapping = clazz.getAnnotation(RequestMapping.class);
                String clas = requestMapping.value();
                Method[] methods = clazz.getMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(RequestMapping.class)) {
                        RequestMapping mapping = method.getAnnotation(RequestMapping.class);
                        String methodPaht = mapping.value();
                        urlMap.put((clas + methodPaht).replace("/", ""), method);
                    }
                }

            } else {
                continue;
            }
        }


    }

}

有变动的类

package com.controller;

import com.annotation.Autowired;
import com.annotation.RequestMapping;
import com.annotation.RestController;
import com.service.TestService;
import com.service.impl.TestServiceImpl;
import com.sun.deploy.net.HttpRequest;
import com.sun.deploy.net.HttpResponse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @program: JavaStudy
 * @description: 测试控制器
 * @author: Deng.Hua
 * @create: 2019-02-22 09:08
 **/

@RestController
@RequestMapping("cs")
public class TestController{
    @Autowired
    private TestServiceImpl testService;
    @RequestMapping(value = "/test")
    public  void  Test(HttpServletRequest request, HttpServletResponse response){
         try {
            PrintWriter printWriter=response.getWriter();
            printWriter.write( testService.test());
        } catch (IOException e) {
            e.printStackTrace();
        }
     }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天空~华

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值