手写springmvc框架

用了这么久的springmvc框架,被其魅力所打动,所以想手写一个自己的springmvc验证一下对其的理解。我们可以去尝试看它的源码,这里就不做过多解释了,直接上干货。

    protected void initStrategies(ApplicationContext context) {
        //用于处理上传请求。处理方法是将普通的request包装成MultipartHttpServletRequest,后者可以直接调用getFile方法获取File.
        initMultipartResolver(context);
        //SpringMVC主要有两个地方用到了Locale:一是ViewResolver视图解析的时候;二是用到国际化资源或者主题的时候。
        initLocaleResolver(context); 
        //用于解析主题。SpringMVC中一个主题对应一个properties文件,里面存放着跟当前主题相关的所有资源、
        //如图片、css样式等。SpringMVC的主题也支持国际化, 
        initThemeResolver(context);
        //用来查找Handler的。
        initHandlerMappings(context);
        //从名字上看,它就是一个适配器。Servlet需要的处理方法的结构却是固定的,都是以request和response为参数的方法。
        //如何让固定的Servlet处理方法调用灵活的Handler来进行处理呢?这就是HandlerAdapter要做的事情
        initHandlerAdapters(context);
        //其它组件都是用来干活的。在干活的过程中难免会出现问题,出问题后怎么办呢?
        //这就需要有一个专门的角色对异常情况进行处理,在SpringMVC中就是HandlerExceptionResolver。
        initHandlerExceptionResolvers(context);
        //有的Handler处理完后并没有设置View也没有设置ViewName,这时就需要从request获取ViewName了,
        //如何从request中获取ViewName就是RequestToViewNameTranslator要做的事情了。
        initRequestToViewNameTranslator(context);
        //ViewResolver用来将String类型的视图名和Locale解析为View类型的视图。
        //View是用来渲染页面的,也就是将程序返回的参数填入模板里,生成html(也可能是其它类型)文件。
        initViewResolvers(context);
        //用来管理FlashMap的,FlashMap主要用在redirect重定向中传递参数。
        initFlashMapManager(context); 
    }

一、创建一个maven工程,目录结构如下:
在这里插入图片描述
二、创建@MyController @MyService @MyAutowired @MyRequestMapping 注解

MyAutowired

@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAutowired {
    String value() default "";
}

MyController

@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyController {
    String value() default "";
}

MyRequestMapping

@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyRequestMapping {
    String value();
}

MyService

@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyService {
    String value() default "";
}

三、实现MyDispatcherServlet

public class MyDispatcherServlet extends HttpServlet{

	private Logger log=Logger.getLogger("init");

    private Properties properties = new Properties();

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

    private Map<String, Object> ioc = new HashMap();
    //handlerMapping的类型可以自定义为Handler
    private Map<String, Method> handlerMapping = new  HashMap();

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

	    @Override
	    public void init(ServletConfig config) throws ServletException {
	        super.init();
	        log.info("初始化MyDispatcherServlet");
	        //1.加载配置文件,填充properties字段;
	        doLoadConfig(config.getInitParameter("contextConfigLocation"));

	        //2.根据properties,初始化所有相关联的类,扫描用户设定的包下面所有的类
	        doScanner(properties.getProperty("scanPackage"));

	        //3.拿到扫描到的类,通过反射机制,实例化,并且放到ioc容器中(k-v  beanName-bean) beanName默认是首字母小写
	        doInstance();
	        // 4.自动化注入依赖
	        doAutowired();
	        //5.初始化HandlerMapping(将url和method对应上)
	        initHandlerMapping();
	        doAutowired2();
	    }

	    @Override
	    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	        // 注释掉父类实现,不然会报错:405 HTTP method GET is not supported by this URL
	        //super.doPost(req, resp);
	        log.info("执行MyDispatcherServlet的doPost()");
	        try {
	            //处理请求
	            doDispatch(req,resp);
	        } catch (Exception e) {
	            resp.getWriter().write("500!! Server Exception");
	        }
	    }

	    @Override
	    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	        // 注释掉父类实现,不然会报错:405 HTTP method GET is not supported by this URL
	        //super.doGet(req, resp);
	        log.info("执行MyDispatcherServlet的doGet()");
	        try {
	            //处理请求
	            doDispatch(req,resp);
	        } catch (Exception e) {
	            resp.getWriter().write("500!! Server Exception");
	        }
	    }

	    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
	        if(handlerMapping.isEmpty()){
	            return;
	        }
	        String url =req.getRequestURI();
	        String contextPath = req.getContextPath();
	        url=url.replace(contextPath, "").replaceAll("/+", "/");
	        // 去掉url前面的斜杠"/",所有的@MyRequestMapping可以不用写斜杠"/"
	        if(url.lastIndexOf('/')!=0){
	            url=url.substring(1);
	        }
	        if(!this.handlerMapping.containsKey(url)){
	            resp.getWriter().write("404 NOT FOUND!");
	            log.info("404 NOT FOUND!");
	            return;
	        }
	        Method method =this.handlerMapping.get(url);
	        //获取方法的参数列表
	        Class<?>[] parameterTypes = method.getParameterTypes();

	        //获取请求的参数
	        Map<String, String[]> parameterMap = req.getParameterMap();
	        //保存参数值
	        Object [] paramValues= new Object[parameterTypes.length];
	        //方法的参数列表
	        for (int i = 0; i<parameterTypes.length; i++){
	            //根据参数名称,做某些处理
	            String requestParam = parameterTypes[i].getSimpleName();
	            if (requestParam.equals("HttpServletRequest")){
	                //参数类型已明确,这边强转类型
	                paramValues[i]=req;
	                continue;
	            }
	            if (requestParam.equals("HttpServletResponse")){
	                paramValues[i]=resp;
	                continue;
	            }
	            if(requestParam.equals("String")){
	                for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
	                    String value =Arrays.toString(param.getValue()).replaceAll("\\[|\\]", "").replaceAll(",\\s", ",");
	                    paramValues[i]=value;
	                }
	            }
	        }
	        //利用反射机制来调用
	        try {
	            //第一个参数是method所对应的实例 在ioc容器中
	            //method.invoke(this.controllerMap.get(url), paramValues);
	            method.invoke(this.controllerMap.get(url), paramValues);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }

	    /**
	     * Description:  根据配置文件位置,读取配置文件中的配置信息,将其填充到properties字段
	     * Params:
	      * @param location: 配置文件的位置
	     * return: void
	     * Date: 2018/6/16 19:07
	     */
	    private void  doLoadConfig(String location){
	        //把web.xml中的contextConfigLocation对应value值的文件加载到流里面
	        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(location);
	        try {
	            //用Properties文件加载文件里的内容
	            log.info("读取"+location+"里面的文件");
	            properties.load(resourceAsStream);
	        } catch (IOException e) {
	            e.printStackTrace();
	        }finally {
	            //关流
	            if(null!=resourceAsStream){
	                try {
	                    resourceAsStream.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
	    }

	    /**
	     * Description:  将指定包下扫描得到的类,添加到classNames字段中;
	     * Params:
	      * @param packageName: 需要扫描的包名
	     * return: void
	     * Date: 2018/6/16 19:05
	     */
	    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);
	            }
	        }
	    }

	    /**
	     * Description:  将classNames中的类实例化,经key-value:类名(小写)-类对象放入ioc字段中
	     * Params:
	      * @param :
	     * return: void
	     * Date: 2018/6/16 19:09
	     */
	    private void doInstance() {
	        if (classNames.isEmpty()) {
	            return;
	        }
	        for (String className : classNames) {
	            try {
	                //把类搞出来,反射来实例化(只有加@MyController需要实例化)
	                Class<?> clazz =Class.forName(className);
	                if(clazz.isAnnotationPresent(MyController.class)){
	                    ioc.put(toLowerFirstWord(clazz.getSimpleName()),clazz.newInstance());
	                }else if(clazz.isAnnotationPresent(MyService.class)){
	                    MyService myService=clazz.getAnnotation(MyService.class);
	                    String beanName=myService.value();
	                    if ("".equals(beanName.trim())){
	                        beanName=toLowerFirstWord(clazz.getSimpleName());
	                    }
	                    Object instance= clazz.newInstance();
	                    ioc.put(beanName,instance);
	                    Class[] interfaces=clazz.getInterfaces();
	                    for (Class<?> i:interfaces){
	                        ioc.put(i.getName(),instance);
	                    }
	                }
	                else{
	                    continue;
	                }
	            } catch (Exception e) {
	                e.printStackTrace();
	                continue;
	            }
	        }
	    }

	    /**
	     * Description:自动化的依赖注入
	     * Params:
	      * @param :
	     * return: void
	     * Date: 2018/6/16 20:40
	     */
	    private void doAutowired(){
	        if (ioc.isEmpty()){
	            return;
	        }
	        for (Map.Entry<String,Object> entry:ioc.entrySet()){
	            //包括私有的方法,在spring中没有隐私,@MyAutowired可以注入public、private字段
	            Field[] fields=entry.getValue().getClass().getDeclaredFields();
	            for (Field field:fields){
	                if (!field.isAnnotationPresent(MyAutowired.class)){
	                    continue;
	                }
	                MyAutowired autowired= field.getAnnotation(MyAutowired.class);
	                String beanName=autowired.value().trim();
	                if ("".equals(beanName)){
	                    beanName=field.getType().getName();
	                }
	                field.setAccessible(true);
	                try {
	                    field.set(entry.getValue(),ioc.get(beanName));
	                }catch (Exception e){
	                    e.printStackTrace();
	                    continue;
	                }
	            }
	        }
	    }

	    private void doAutowired2(){
	        if (controllerMap.isEmpty()){ return; }
	        for (Map.Entry<String,Object> entry:controllerMap.entrySet()){
	            //包括私有的方法,在spring中没有隐私,@MyAutowired可以注入public、private字段
	            Field[] fields=entry.getValue().getClass().getDeclaredFields();
	            for (Field field:fields){
	                if (!field.isAnnotationPresent(MyAutowired.class)){
	                    continue;
	                }
	                MyAutowired autowired= field.getAnnotation(MyAutowired.class);
	                String beanName=autowired.value().trim();
	                if ("".equals(beanName)){
	                    beanName=field.getType().getName();
	                }
	                field.setAccessible(true);
	                try {
	                    field.set(entry.getValue(),ioc.get(beanName));
	                }catch (Exception e){
	                    e.printStackTrace();
	                    continue;
	                }
	            }
	        }
	    }

	    /**
	     * Description:  初始化HandlerMapping(将url和method对应上)
	     * Params:
	      * @param :
	     * return: void
	     * Date: 2018/6/16 19:12
	     */
	    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("/+", "/");
	                    handlerMapping.put(url,method);
	                    controllerMap.put(url,clazz.newInstance());
	                    System.out.println(url+","+method);
	                }
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }

	    /**
	     * Description:  将字符串中的首字母小写
	     * Params:
	      * @param name:
	     * return: java.lang.String
	     * Date: 2018/6/16 19:13
	     */
	    private String toLowerFirstWord(String name){
	        char[] charArray = name.toCharArray();
	        charArray[0] += 32;
	        return String.valueOf(charArray);
	    }
}

四、创建一个测试Controller

@MyController
@MyRequestMapping("hello")
public class HelloController {

	@MyAutowired
	HelloService helloservice;
	
	@MyRequestMapping("test")
    public void myTest(HttpServletRequest request, HttpServletResponse response){
        try {
            response.getWriter().write( "success");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	@MyRequestMapping("testservice")
	public void myTest2(HttpServletRequest request, HttpServletResponse response){
		try {
			helloservice.sayHello();
			response.getWriter().write( "success  HAHAHAHA");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

五、web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>MyMVC</servlet-name>
        <servlet-class>com.cheng.servlet.MyDispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>application.properties</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyMVC</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.cheng</groupId>
  <artifactId>springmvc</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
  <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <java.version>1.8</java.version>
   </properties>
  
  
  <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
 </dependencies>
  
  
</project>

经测试,都能得到预期的效果。大家可以多多练习以加深对springmvc的理解。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

行走在江湖

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

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

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

打赏作者

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

抵扣说明:

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

余额充值