发现做的项目里每个controller的路由基本用的都是controller的名字,直接自动生成吧。
有黑名单,可以排除一些特殊情况的uri,黑名单匹配规则做的比较简陋,确实项目比较小只有登录页需要排除(项目做的前后分离restful接口类型的,使用的jwt验证身份,所以除了登录页,其他的路径要加验证身份的拦截器,需要把login页面的路由单独写),匹配规则仅为单纯的字符串匹配,没有正则表达式什么的,所黑名单以需要一个一个添加。这个代码是用controller名转化后的uri做排除的,黑名单写不需要生成的uri(如"/login"),也可自行改为按照controller名进行排除(如"loginController"),其实是差不多一个意思吧。
自动添加路由类(有些多余的备注没有删除):
package com.demo.router;
import com.demo.common.ClassUtil;
import com.demo.interceptor.AuthInterceptor;
import com.jfinal.config.Routes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainRouter extends Routes {
//将每个controller的类名首字母转为小写,并去除Controller,作为路由路径(如:LoginController → /login)
private final static ArrayList<String> routerBlackList = new ArrayList<String>(Arrays.asList("/login")); //不再此加进路由的uri
public void config() {
//addInterceptor(new AuthInterceptor());//此处是添加身份认证拦截器
List<Class<?>> classes = new ArrayList<>();
try {
classes = ClassUtil.getClasses("com.demo.controller");//controller包名
} catch (Exception e) {
e.printStackTrace();
}
for (Class c : classes) {
//去除扫描时,类中包含私有方法时中出现同名controller且有后缀$1、$2的情况
if (!c.getName().contains("$")) {
String className = c.getName().substring(c.getName().lastIndexOf(".")+1).replace("Controller","");
className = "/" + className.substring(0, 1).toLowerCase() + className.substring(1);
if (!routerBlackList.contains(className))
System.out.println(className);
add(className, c);
}
}
//代替了以下添加路由语句
// add("/dashboard", DashboardController.class);
// add("/combatQuery", CombatQueryController.class);
// add("/cultureFeature", CultureFeatureController.class);
// add("/cultureFeatureMap", CultureFeatureMapController.class);
// add("/cultureFeatureType", CultureFeatureTypeController.class);
// add("/dangerousChemicals", DangerousChemicalsController.class);
// add("/dangerousChemicalsType", DangerousChemicalsTypeController.class);
// add("/importantCompany", ImportantCompanyController.class);
// add("/material", MaterialController.class);
// add("/index", IndexController.class);
// add("/knowledgeBase", KnowledgeBaseController.class);
// add("/knowledgeBaseType", KnowledgeBaseTypeController.class);
// add("/loginPagePolitics", LoginPagePoliticsController.class);
// add("/notification", NotificationController.class);
// add("/notificationTree", NotificationTreeController.class);
// add("/notificationView", NotificationViewController.class);
// add("/addressBook", AddressBookController.class);
// add("/combatantInfo", CombatantInfoController.class);
// add("/leave", LeaveController.class);
// add("/leaveFlow", LeaveFlowController.class);
// add("/main", MainController.class);
// add("/company", CompanyController.class);
// add("/loginPageImage", LoginPageImageController.class);
// add("/loginPageNews", LoginPageNewsController.class);
// add("/password", PasswordController.class);
// add("/post", PostController.class);
// add("/role", RoleController.class);
// add("/user", UserController.class);
}
}
以下为ClassUtil 辅助类(有多余的方法代码没有删除,用来获取指定包名下的Controller的):
package com.demo.common;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class ClassUtil {
public static void main(String[] args) {
try {
List<Class<?>> classes = getClasses("com.demo.controller");
for (Class c : classes) {
//System.out.println(c.getName());
}
} catch (Exception e) {
e.printStackTrace();
}
}
// private static Logger log = Logger.getLogger(ClassUtil.class);
public static List<Class<?>> getClasses(String packageName) throws ClassNotFoundException, IOException {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String path = packageName.replace(".", "/");
//System.out.println("path:" + path);
Enumeration<URL> resources = classLoader.getResources(path);
//System.out.println("获取资源路径" + resources);
ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
while (resources.hasMoreElements()) {
//System.out.println("resources.hasMoreElements()");
URL resource = resources.nextElement();
//System.out.println(resource.getProtocol());
//System.out.println(resource.getPath());
String protocol = resource.getProtocol();
if ("file".equals(protocol)) {
File file = new File(resource.getFile());
classes.addAll(findClasses(file, packageName));
} else if ("jar".equals(protocol)) {
//System.out.println("jar类型的扫描");
String jarpath = resource.getPath();
jarpath = jarpath.replace("file:/", "");
jarpath = jarpath.substring(0, jarpath.indexOf("!"));
return getClasssFromJarFile(jarpath, path);
}
}
return classes;
}
private static List<Class<?>> findClasses(File directory, String packageName)
throws ClassNotFoundException {
//System.out.println("directory.exists()=" + directory.exists());
//System.out.println("directory.getName()=" + directory.getName());
ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
if (!directory.exists()) {
return classes;
}
File[] files = directory.listFiles();
for (File file : files) {
if (file.isDirectory()) {
assert !file.getName().contains(".");
classes.addAll(findClasses(file, packageName + "." + file.getName()));
} else if (file.getName().endsWith(".class")) {
classes.add(Class.forName(packageName + "." + file.getName().replace(".class", "")));
}
}
return classes;
}
/**
* 从jar文件中读取指定目录下面的所有的class文件
*
* @param jarPaht jar文件存放的位置
* @param filePaht 指定的文件目录
* @return 所有的的class的对象
*/
public static List<Class<?>> getClasssFromJarFile(String jarPaht, String filePaht) {
List<Class<?>> clazzs = new ArrayList<Class<?>>();
JarFile jarFile = null;
try {
jarFile = new JarFile(jarPaht);
List<JarEntry> jarEntryList = new ArrayList<JarEntry>();
Enumeration<JarEntry> ee = jarFile.entries();
while (ee.hasMoreElements()) {
JarEntry entry = (JarEntry) ee.nextElement();
// 过滤我们出满足我们需求的东西
if (entry.getName().startsWith(filePaht)
&& entry.getName().endsWith(".class")) {
jarEntryList.add(entry);
}
}
for (JarEntry entry : jarEntryList) {
String className = entry.getName().replace('/', '.');
className = className.substring(0, className.length() - 6);
try {
clazzs.add(Thread.currentThread().getContextClassLoader().loadClass(className));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException e1) {
//System.out.println("解析jar包文件异常");
} finally {
if (null != jarFile) {
try {
jarFile.close();
} catch (Exception e) {
}
}
}
return clazzs;
}
}
懒惰使人进步。。。