您的位置:首页 > 编程语言 > Java开发

写出一个你自己的MVC框架-基于对springMVC源码实现和理解(5):数据初始化(四)

2015-03-12 16:13 489 查看
DispatcherServlet中的数据初始化:

重写init():

[java]
view plaincopy

@Override  
    public void init() throws ServletException {  
  
        logger.info("=====================MyDispatcherServlet init=====================");  
  
        logger.info("============================加载配置文件:===========================");  
        loadConfigFile();  
  
        logger.info("=============================初始化参数============================");  
        initParameter();  
  
        logger.info("=============================加载控制器============================");  
        loadController();  
  
        logger.info("========================预映射URL和requestMap======================");  
        mapMethod();  
  
        logger.info("=============================加载拦截器============================");  
        loadInterceptor();  
  
        logger.info("=============================初始化完毕============================");  
  
    }  

加载配置文件:

[java]
view plaincopy

/* 
     * 加载配置文件 
     */  
    private void loadConfigFile() {  
        String mvcConfigLocation = getInitParameter("mvcConfigLocation");  
        logger.info(mvcConfigLocation);  
        InputStream inputStream = this.getServletContext().getResourceAsStream(  
                mvcConfigLocation);  
  
        p = new Properties();  
  
        try {  
            p.load(inputStream);  
        } catch (IOException e1) {  
            e1.printStackTrace();  
        }  
    }  

初始化部分参数:

[java]
view plaincopy

/* 
     * 初始化部分参数 
     */  
    private void initParameter() {  
        viewPath = p.getProperty("myview.path");  
        logger.info("映射view目录:" + viewPath);  
    }  

加载控制器:

[java]
view plaincopy

/* 
     * 加载控制器 
     */  
    private void loadController() {  
  
        String controllerPath = p.getProperty("controller.annotated.path");  
        String filePath = "";  
        String classPath = this.getClass().getClassLoader().getResource("")  
                .getPath();  
  
        filePath = classPath + controllerPath;  
        List<String> allClassName = new ArrayList<String>();  
  
        MvcUtil.getAllClassName(classPath, filePath, allClassName);  
  
        for (String s : allClassName) {  
            try {  
  
                Class<?> c = Class.forName(s);  
                if (c.isAnnotationPresent(MyController.class)) {  
                    cs.add(c);  
                    logger.info("加载controller:" + c.getName());  
                }  
            } catch (ClassNotFoundException e) {  
                e.printStackTrace();  
            }  
        }  
    }  

 这里用了反射的方式加载被Controller注解的类,用到的工具类中的方法getAllClassName():

[java]
view plaincopy

public static List<String> getAllClassName(String classPath ,String filePath ,List<String> allClassName) {   
        File dir = new File(filePath);  
        File[] fs = dir.listFiles(); //包括子目录  
          
        String className = "";  
          
        for (File f : fs) {   
            if (f.isDirectory()) {   
                getAllClassName(classPath,f.getAbsolutePath(),allClassName);   
            } else {   
                className = f.getPath().replace(classPath.substring(1).replace("/", "\\"), "").replace("\\", ".").replace(".class", "");  
                allClassName.add(className);         
            }   
        }   
        return allClassName;  
    }  

映射控制器方法并实例化hs中:

[java]
view plaincopy

/* 
     * 映射控制器方法 
     */  
    private void mapMethod() {  
  
        Method[] ms = null;  
        String rm = null;  
        for (Class<?> c : cs) {  
            ms = c.getMethods();  
            String mappingUrl = "";  
            for (Method m : ms) {  
                if (m.isAnnotationPresent(MyRequestMapping.class)) {  
                    mappingUrl = this.getServletContext().getContextPath()  
                            + m.getAnnotation(MyRequestMapping.class).value()  
                                    .trim();  
                    rm = m.getAnnotation(MyRequestMapping.class).method()  
                            .trim().toUpperCase();  
                    logger.info("映射url:" + mappingUrl);  
                      
                    try {  
                        hs.put(mappingUrl + rm, new Handler(c.newInstance(), m, rm));// 先直接拼接字符串当key,以后再优化  
                    } catch (InstantiationException e) {  
                        e.printStackTrace();  
                    } catch (IllegalAccessException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        }  
    }  

加载拦截器存放在os中:

[java]
view plaincopy

/* 
     * 加载控制器 
     */  
    private void loadInterceptor() {  
        String controllerPath = p.getProperty("interception.path").trim();  
        String filePath = "";  
        String classPath = this.getClass().getClassLoader().getResource("")  
                .getPath();  
  
        filePath = classPath + controllerPath;  
        List<String> allClassName = new ArrayList<String>();  
  
        MvcUtil.getAllClassName(classPath, filePath, allClassName);  
  
        String[] mappingPath = {};  
        String interceptorMethod = "";  
        int index = 0;  
        for (String s : allClassName) {  
            try {  
                Class<?> c = Class.forName(s);  
                if (c.isAnnotationPresent(MyInterceptor.class)) {  
                    mappingPath = c.getAnnotation(MyInterceptor.class)  
                            .mappingPath();  
                    interceptorMethod = c.getAnnotation(MyInterceptor.class)  
                            .interceptionMethod();  
                    index = c.getAnnotation(MyInterceptor.class).index();  
  
                    os.add(new Obstruct(  
                            InterceptorFactory.createInterceptor(c),  
                            mappingPath, interceptorMethod, index));  
                    logger.info("加载interceptor:" + c.getName());  
                }  
            } catch (ClassNotFoundException e) {  
                e.printStackTrace();  
            }  
        }  
        Collections.sort(os, new ComparatorObstructUtil());  
    }  

至此数据初始化过程结束
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  springmvc 源码
相关文章推荐