ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

SpringMVC进阶(二)手写MVC框架

2022-01-07 09:03:53  阅读:169  来源: 互联网

标签:进阶 SpringMVC MVC handler 参数 lagou Handler class String


一.手写MVC框架实现功能

(一)SpringMVC请求处理流程回顾

(二)手写MVC框架主要实现功能

二. 准备阶段

(一)自定义注解

package com.lagou.edu.mvcframework.annotations;

import java.lang.annotation.*;

@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LagouAutowired {
    String value() default "";
}
package com.lagou.edu.mvcframework.annotations;

import java.lang.annotation.*;

@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface LagouController {
    String value() default "";
}
package com.lagou.edu.mvcframework.annotations;

import java.lang.annotation.*;

@Documented
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LagouRequestMapping {
    String value() default "";
}
package com.lagou.edu.mvcframework.annotations;

import java.lang.annotation.*;

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

(二) 准备Handler方法

package com.lagou.demo.controller;

import com.lagou.demo.service.IDemoService;
import com.lagou.edu.mvcframework.annotations.LagouAutowired;
import com.lagou.edu.mvcframework.annotations.LagouController;
import com.lagou.edu.mvcframework.annotations.LagouRequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@LagouController
@LagouRequestMapping("/demo")
public class DemoController {


    @LagouAutowired
    private IDemoService demoService;


    /**
     * URL: /demo/query?name=lisi
     * @param request
     * @param response
     * @param name
     * @return
     */
    @LagouRequestMapping("/query")
    public String query(HttpServletRequest request, HttpServletResponse response,String name) {
        return demoService.get(name);
    }
}

(三)准备封装Handler方法相关信息及url和Method之间的映射关系

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>


    public Handler(Object controller, Method method, Pattern pattern) {
        this.controller = controller;
        this.method = method;
        this.pattern = pattern;
        this.paramIndexMapping = new HashMap<>();
    }
...
一堆get、set
...

(四)准备包扫描,扫描注解相关工作

    1.准备包扫描路径:springmvc.properties

scanPackage=com.lagou.demo

      2. web.xml配置<servlet>

  <servlet>
    <servlet-name>lgoumvc</servlet-name>
    <servlet-class>com.lagou.edu.mvcframework.servlet.LgDispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>springmvc.properties</param-value>
    </init-param>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>lgoumvc</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>

(五)准备好前端控制器 LgDispatcherServlet

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

    // Handler的集合
    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 初始化完成....");
        
    }

}

 

三. 初始化阶段(全部在LgDispatcherServlet类里完成)

(一)加载配置文件,获取扫描路径

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

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

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

    }

(二)扫描相关的类、扫描注解

// 扫描类
    // scanPackage: com.lagou.demo  package---->  磁盘上的文件夹(File)  com/lagou/demo
    private void doScan(String scanPackage) {
        //拿到com.lagou.demo所在的真实的磁盘路径,Thread.currentThread().getContextClassLoader().getResource("").getPath()获取到当前的classPATH,然后拼接com.lagou.demo
        //拼接的时候,要把com.lagou.demo中的点替换成反斜杠,最后变成classPath真实路径+com/lagou/demo
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
       //以com.lagou.demo这个包的真实磁盘路径新new一个文件对象
        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
            //如果下面没有子目录,判断遍历到的文件是否是.class结尾的
            }else if(file.getName().endsWith(".class")) {
                String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                classNames.add(className);
            }
            
        }


    }

(三)初始化bean对象(基于注解实现IOC容器)

基于classNames缓存的类的全限定类名,以及反射技术,完成对象创建和管理

// 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();
        }

(四)基于注解实现依赖注入

//  实现依赖注入
    private void doAutoWired() {
        if(ioc.isEmpty()) {return;}

        // 有对象,再进行依赖注入处理

        // 遍历ioc中所有对象,查看对象中的字段,是否有@LagouAutowired注解,如果有需要维护依赖注入关系
        for(Map.Entry<String,Object> entry: ioc.entrySet()) {
            // 获取bean对象中的所有字段信息
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
            // 遍历判断处理某个字段上是否有LagouAutowired注解
            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();
                }

            }


        }

(五)初始化处理器映射器

1. 初始化思路解析

(1)在IOC容器里找到被LagouController标注的类

(2)获取该类的类与方法上的LagouRequestMapping注解值组合起来形成的URL

(3)将该类的实例化对象、被标注LagouRequestMapping注解的方法信息以及URL封装到Handler

(4)计算被标注LagouRequestMapping注解的方法的参数位置信息并封装到Handler的paramIndexMapping属性中

(5)将一个个封装好的Handler缓存到handlerMapping集合中,以建立一个个URL和method之间的映射关系。

2. 代码示例

/*
        构造一个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];

                    //往handler对象的ParamIndexMapping属性中存入方法的参数信息
                    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);

            }


        }

    }

 以上代码中有个地方要注意:在往handler对象的ParamIndexMapping属性中存入方法的参数信息时,如果是request和response对象,那么参数名称写HttpServletRequest和HttpServletResponse,如果是其它参数直接存入方法名。这么做是为了在之后做匹配取出时将request和response参数与其它参数分开匹配。因为request和response参数是固定的,而其它参数不固定。

四. MVC处理请求阶段

(一)前端控制器获取REQUEST请求中的url,并调用处理器映射器获取对应的Handler

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

    // 根据uri获取到能够处理当前请求的hanlder(从handlermapping中(list))
        Handler handler = getHandler(req);
}

 private Handler getHandler(HttpServletRequest req) {
        if(handlerMapping.isEmpty()){return null;}

        //从Request里面获取一个URL
        String url = req.getRequestURI();

        //从Handler集合handlerMapping里面匹配从Request里获取的URL与handler里面的Pattern是否一直,如果一致,则返回这个handler
        for(Handler handler: handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(url);
            if(!matcher.matches()){continue;}
            return handler;
        }

        return null;

    }

(二)执行Handler前的准备工作

1. 思路

(1)从获取到的对应的Handler所缓存的方法信息中,取出该方法对应的参数个数

(2)以这个参数个数为长度新建一个参数对象数组paraValues,反射调用做为参数传入时使用

(3)从对应的Handler中取出属性ParamIndexMapping,把ParamIndexMapping中所缓存的方法参数按照原位置顺序存入paraValues中。

2. 代码示例

// 参数绑定
        // 获取所有参数类型数组,这个数组的长度就是我们最后要传入的args数组的长度
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();


        // 根据上述数组长度创建一个新的数组(参数数组,是要传入反射调用的)
        Object[] paraValues = new Object[parameterTypes.length];

        // 以下就是为了向参数数组中塞值,而且还得保证参数的顺序和方法中形参顺序一致
        //首先从前段传入的request里获取所有参数
        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  将数组以符号或其他字符串为间隔组成新的字符串

            // 如果参数和方法中的参数匹配上了,填充数据,通过getParamIndexMapping().containsKey(param.getKey())判断Request里拿出来的参数是否与handler里面保存的方法参数一致,如果从handler取不出数据u,证明没有匹配的参数
            if(!handler.getParamIndexMapping().containsKey(param.getKey())) {continue;}

            // 方法形参确实有该参数,找到它的索引位置,对应的把参数值放入paraValues
            //通过
            Integer index = handler.getParamIndexMapping().get(param.getKey());//name在第 2 个位置

            paraValues[index] = value;  // 把前台传递过来的参数值填充到对应的位置去

        }

        //填充Request参数
        int requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName()); // 0
        paraValues[requestIndex] = req;

        //填充Response参数
        int responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName()); // 1
        paraValues[responseIndex] = resp;

(三)通过反射技术执行Handler

// 最终调用handler的method属性
        try {
            //到这里等同与哪到了要执行方法所在类的对象以及方法参数,一起做为形参代入,执行invoke方法,等同于DemoController类中的query方法被执行
            handler.getMethod().invoke(handler.getController(),paraValues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

五. 完整代码展示

手写SpringMVC框架完整代码示例

标签:进阶,SpringMVC,MVC,handler,参数,lagou,Handler,class,String
来源: https://blog.csdn.net/enterpc/article/details/122355378

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有