如何手写一个简易的SpringMVC框架

背景

为了练习手写一个简易的SpringMVC框架,实现了ioc以及Request和对应注解方法映射

思路

1.我们知道SpringMVC是基于Servlet实现的,所以首先要在web.xml中配置一个类,拦截所有的请求

 

2.这个类分别有init方法和doGet/doPost方法。在init方法中实现ioc。在doPost方法中执行url和ioc中定义类的映射。

        init:

                1 加载配置文件 springmvc.properties

                2 扫描相关的类,扫描注解

                3 初始化bean对象(实现ioc容器,基于注解)

                4 实现依赖注入

                5 构造一个HandlerMapping处理器映射器,将配置好的url和Method建立映射关系

        doPost:

                1 根据uri获取到能够处理当前请求的hanlder(从handlermapping中(list))

                2 参数绑定

                3 最终调用handler的method属性

 

具体实现

除了自定义的Servlet之外我们还要定义一些注解,比如@Autowired,@RequestMapping,@Controller,对应就是原框架原有注解的功能。

当然还有一个核心实体类Handler,它封装了我们根据url调用方法功能的相应参数

public class Handler {

    private Object controller; // method.invoke(obj,)

    private Method method;   //应当调用的方法

    private Pattern pattern; // spring中url是支持正则的

    private Map<String,Integer> paramIndexMapping; // 参数顺序,是为了进行参数绑定,key是参数名,value代表是第几个参数 <name,2>

    private Set<String> users ; //允许访问的用户们,用set可以少一步去重操作


    /**全参构造,getter,setter*/
}

 

 

接下来是核心的LgDispatcherServlet方法了。我直接全部写上了,几个重点逻辑我在下面会提出来细说一下

package com.lagou.edu.mvcframework.servlet;

import com.lagou.demo.service.IDemoService;
import com.lagou.edu.mvcframework.annotations.*;
import com.lagou.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.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LgDispatcherServlet 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();

            //获取类上标注的允许访问的用户
            Set<String> users = new HashSet<>();
            if(aClass.isAnnotationPresent(Security.class)) {
                Security annotation = aClass.getAnnotation(Security.class);
                String[] value = annotation.value();
                for (String s : value) {
                    users.add(s);
                }
            }

            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];

                //获取方法上标识的用户
                if(method.isAnnotationPresent(Security.class)){
                    Security a = method.getAnnotation(Security.class);
                String[] value = a.value();
                    for (String s : value) {
                        users.add(s);
                    }
                }




                //  方法没有标识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),users);


                // 计算方法的参数位置信息  // 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 {

            String name = req.getParameter("username");

            if(handler.isUserExist(name))
                handler.getMethod().invoke(handler.getController(),paraValues);
            else {
                resp.getWriter().write("have no Security for "+name);
            }
        } 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;

    }


}

重点代码

  初始化主要就是四步

    1.先通过递归把之前配置包下的目录都扫到className容器中(doScan)

    2.再通过这个className,把标有Controller或者Service的类实例化加到ioc容器中(doInstance)

    3.依赖注入,这里没有用三级缓存也无法解决循环依赖的问题

    4.最后扫描ioc容器中的所有class的方法,看哪个标注了RequestMapping,就会把为这个创建一个Handler加到HandlerMapping中

 执行转发就更简单了

    1.获得url对应handler

    2.参数对饮填充

    3.调用method.invoke方法

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
AOP(Aspect Oriented Programming)是一种面向切面编程的编程范式,它可以在程序运行时动态地将代码插入到指定方法的前面、后面或者中间,从而实现对方法的增强。 下面是手写一个简单的AOP框架的步骤: 1. 定义注解 定义一个自定义注解,用于标注需要增强的方法。例如: ```java @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { } ``` 2. 定义切面 定义一个切面类,该类包含需要增强的方法以及增强逻辑。例如: ```java public class MyAspect { public void before() { System.out.println("before"); } public void after() { System.out.println("after"); } } ``` 3. 定义代理类 定义一个代理类,该类通过反射机制获取需要增强的方法以及切面类中的增强逻辑,并在方法执行前后调用切面类中的增强逻辑。例如: ```java public class MyProxy { public static Object getProxy(Object target) { return Proxy.newProxyInstance( target.getClass().getClassLoader(), target.getClass().getInterfaces(), (proxy, method, args) -> { Method targetMethod = target.getClass().getMethod(method.getName(), method.getParameterTypes()); if (targetMethod.isAnnotationPresent(MyAnnotation.class)) { MyAspect aspect = new MyAspect(); aspect.before(); Object result = method.invoke(target, args); aspect.after(); return result; } else { return method.invoke(target, args); } }); } } ``` 4. 使用代理类 通过代理类获取代理对象,并使用该对象调用需要增强的方法。例如: ```java public class Main { public static void main(String[] args) { MyClass myClass = new MyClass(); MyClass myProxy = (MyClass) MyProxy.getProxy(myClass); myProxy.method(); } } class MyClass { @MyAnnotation public void method() { System.out.println("method"); } } ``` 当调用代理对象的`method()`方法时,会先调用`MyAspect`中的`before()`方法,然后调用原始对象`MyClass`中的`method()`方法,最后再调用`MyAspect`中的`after()`方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值