手写SpringMVC

项目结构

在这里插入图片描述

springmvc的工作流程?

一:在项目运行时会运行DispatchServlet类,主要干了四件事
1,加载配置文件 
properties HashTable(scanPackage,com.mjy.core)
2,扫描用户设定包下的类,进行初始化
classNames : com.mjy.core.TestController
3,拿到扫描的类,利用反射进行初始化,并放到ioc容器中
ioc(testController,类实例对象)
4,初始化handlerMappimg将url与method对应上
handerMapping("test/test1",方法)
controllerMap("test/test1",类实例)
二:输入url进行访问时
1,先根据handermapping中的url将method取出来
2,获取方法中的参数列表
3,获取参数值
4,利用反射机制调用类中的方法

代码实现

1,三个注解
package com.mjy.annotation;

import java.lang.annotation.*;

/**
 * @classDesc:
 * @Author: mujuyan
 * @createTime: 2019/3/15 10:55
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyController {
    /**
     * 表示给controller注册别名
     */
    String value() default "";
}
package com.mjy.annotation;

import javax.xml.bind.Element;
import java.lang.annotation.*;

/**
 * @classDesc:
 * @Author: mujuyan
 * @createTime: 2019/3/15 10:57
 */
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyRequestMapping {
    /**
     * 表示访问该方法的url
     */
    String value() default "";
}
package com.mjy.annotation;

import java.lang.annotation.*;

/**
 * @classDesc:
 * @Author: mujuyan
 * @createTime: 2019/3/15 11:00
 */
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyRequestParam {
    /**
     * 表示参数的别名,必填
     */
    String value();
}
2,TestController.class
package com.mjy.core.controller;

import com.mjy.annotation.MyController;
import com.mjy.annotation.MyRequestMapping;
import com.mjy.annotation.MyRequestParam;

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

/**
 * @classDesc:
 * @Author: mujuyan
 * @createTime: 2019/3/15 11:02
 */
@MyController
@MyRequestMapping("/test")
public class TestController {
    @MyRequestMapping("/test1")
    public void test1(HttpServletRequest request, HttpServletResponse response, @MyRequestParam("param") String param){
        try{
            response.getWriter().write("this is "+param);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    @MyRequestMapping("/test2")
    public void test2(HttpServletRequest request,HttpServletResponse response){
        try{
            response.getWriter().println("test2...........");
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
3,MyDispatcher.class
package com.mjy.servlet;

import com.mjy.annotation.MyController;
import com.mjy.annotation.MyRequestMapping;

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.Method;
import java.net.URL;
import java.util.*;

/**
 * @classDesc:
 * @Author: mujuyan
 * @createTime: 2019/3/15 11:18
 */
public class MyDispatcherServlet extends HttpServlet {
    private Properties properties = new Properties();

    private List<String> classNames = new ArrayList<>();

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

    private Map<String, Method> handlerMapping = new HashMap<>();

    private Map<String,Object> controllerMap = new HashMap<>();

    @Override
    public void init(ServletConfig config) throws ServletException{

        //1,加载配置文件
        //properties hashtable(scanPackage,com.mjy.core)
        doLoadConfig(config.getInitParameter("contextConfigLocation"));

        //2,初始化所有相关联的类,扫描用户设定的包下面的类
        //classNames  :  com.mjy.core.controller.TestController
        doScanner(properties.getProperty("scanPackage"));

        //3,拿到扫描的类,通过反射机制,实例化,并且放到IOC容器中(k-v beanName-bean) beanName默认是首字母小写
        //ioc(testController,类实例对象)
        doInstance();

        //4,初始化HandlerMapping(将url和method对应上)
        //handlerMapping("/test/test1",方法)
        //controllerMap("/test/test1",类实例)
        initHandlerMapping();

    }

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

    @Override
    protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        try {
            doDispath(request,response);
        }catch (Exception e){
            response.getWriter().write("500!");
        }
    }

    private void doScanner(String packageName){
        URL url = this.getClass().getClassLoader().getResource("/"+packageName.replaceAll("\\.","/"));
        File dir = new File(url.getFile());
        for(File file : dir.listFiles()){
            if(file.isDirectory()){
                //递归读取包
                doScanner(packageName+"."+file.getName());
            }else {
                String className = packageName+"."+file.getName().replace(".class","");
                classNames.add(className);
            }
        }

    }

    private void doDispath(HttpServletRequest request,HttpServletResponse response) throws Exception{
        if(handlerMapping.isEmpty()){
            return;
        }

        String url = request.getRequestURI();
        String contextPath = request.getContextPath();

        //拼接url并把多个/替换成一个
        url = url.replace(contextPath,"").replaceAll("/+","/");

        if(!this.handlerMapping.containsKey(url)){
            response.getWriter().write("404 not found!");
            return;
        }

        Method method = this.handlerMapping.get(url);

        //获取方法的参数列表
        Class<?>[] parameterTypes = method.getParameterTypes();

        //获取请求的参数
        Map<String,String[]> paramterMap = request.getParameterMap();

        //保存参数值
        Object[] paramVaules = new Object[parameterTypes.length];

        //方法的参数列表
        for(int i = 0; i < parameterTypes.length; i++){
            //根据参数名称,做某些处理
            String requestParam = parameterTypes[i].getSimpleName();
            if(requestParam.equals("HttpServletRequest")){
                //参数类型已明确,这边强转类型
                paramVaules[i] = request;
                continue;
            }
            if(requestParam.equals("HttpServletResponse")){
                paramVaules[i] = response;
                continue;
            }
            if(requestParam.equals("String")){
                for(Map.Entry<String,String[]> param : paramterMap.entrySet()){
                    String value = Arrays.toString(param.getValue()).replaceAll("\\[|\\]","").replaceAll(",\\s",",");
                    paramVaules[i] = value;
                }
            }
        }
        //利用反射机制来调用
        try{
            method.invoke(this.controllerMap.get(url),paramVaules);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void doLoadConfig(String location){
        //把web.xml中的contextConfigLocation对应的value值的文件加载到流里面
        InputStream resouceAsStream = this.getClass().getClassLoader().getResourceAsStream(location);
        try{
            //用properties文件加载文件里的内容
            properties.load(resouceAsStream);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关流
            if(null != resouceAsStream){
                try{
                    resouceAsStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }

        }

    }

    private void doInstance(){
        if(classNames.isEmpty()){
            return;
        }
        for (String className : classNames){
            try {
                //把类搞出来,反射实例化
                Class<?> clazz = Class.forName(className);
                if (clazz.isAnnotationPresent(MyController.class)){
                    ioc.put(toLowerFirstWord(clazz.getSimpleName()),clazz.newInstance());
                }
            }catch (Exception e){
                e.printStackTrace();
                continue;
            }
        }
    }


    /**
     * 把字符串首字母小写
     */
    private String toLowerFirstWord(String name){
        char[]  charArray = name.toCharArray();
        charArray[0]+=32;
        return String.valueOf(charArray);
    }

    private void initHandlerMapping(){
        if(ioc.isEmpty()){
            return;
        }
        try{
            for(Map.Entry<String,Object> entry : ioc.entrySet()){
                Class<? extends Object> clazz = entry.getValue().getClass();
                if(!clazz.isAnnotationPresent(MyController.class)){
                    continue;
                }

                //拼接url时,是controller头的url拼上方法上的url
                String baseUrl = "";
                if(clazz.isAnnotationPresent(MyRequestMapping.class)){
                    MyRequestMapping annotation = clazz.getAnnotation(MyRequestMapping.class);
                    baseUrl = annotation.value();
                }
                Method[] methods = clazz.getMethods();
                for(Method method : methods){
                    if(!method.isAnnotationPresent(MyRequestMapping.class)){
                        continue;
                    }
                    MyRequestMapping annotation = method.getAnnotation(MyRequestMapping.class);
                    String url = annotation.value();

                    url = (baseUrl+"/"+url).replaceAll("/+","/");
                    //这里应该放置实例和method
                    handlerMapping.put(url,method);
                    controllerMap.put(url,clazz.newInstance());
                    System.out.println(url+","+method);
                }
            }

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

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值