Jfinal 2.1版本,JFinalConfig里自动配置路由的代码实现,直接晒代码

背景:java

一、我使用的jfinal2.1;工具

二、我喜欢用@ActionKey("/admin/index")这一个功能,代码复制性强,不喜欢在controller的类上加注解,很差打理;code

三、不想每次新增一个controller类都要在JFinalConfig的public void configRoute(Routes me),手动加入,但愿代码本身去找,就能够了;路由

四、其实,我主要就是用它加载一下controller类文件,我不关心【controllerkey】叫什么名字,由于,我用【actionKey】开发项目;开发

参考代码:get

public class MyConfig extends JFinalConfig {//不相关的代码,这里就不显示了
    /*** 配置路由*/
    public void configRoute(Routes me) {
	//【IndexController.classs】该类能够本身定义,做用,带头大哥,出卖全部controller的位置。
		String filePath =  IndexController.class.getResource("").getPath();
		File fileDir = new File(filePath);
		//包名
		String controllerPackage = fileDir.getAbsolutePath().substring(fileDir.getAbsolutePath().indexOf("com")).replace("\\", ".");
        //包内的controller类名的集合
		List<String> controllerNames = new ArrayList<String>();
		if(fileDir.isDirectory()) {
			File[] list = fileDir.listFiles();
			for(File file : list) {
				String fileName = file.getName();
				//屏蔽内部类,好比:IndexController$1.classs
				if(fileName.indexOf("$") == -1) {
					controllerNames.add(fileName);
					
					String controllerName = fileName.substring(0,fileName.indexOf(".class"));
					String controllerKey = StrKit.firstCharToLowerCase(controllerName);
					try {
						@SuppressWarnings("unchecked")
						Class<Controller> controllerClass = (Class<Controller>) Class.forName(controllerPackage+"."+controllerName);
						//jfinal载入controller
						me.add(controllerKey, controllerClass);
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					}
				}
			}
		}
    }
}

  固然上面的内部方法,能够封装成一个工具类。起个名字叫 SubRoutes extends Routes string

  

之后代码JfinalConfig的配置路由代码就能够这样写it

public void configRoute(Routes me) {
    me.add(new SubRoutes(AdminIndexController.class));//后台路由--加载后台的全部controller类
    me.add(new SubRoutes(WebIndexController.class));//前台路由--加载前台的全部controller类
}

固然,这里io

AdminIndexController和WebIndexController不在同一个包里面,是分开的,不在同一个文件夹
打完收工。
相关文章
相关标签/搜索