一、路由注册的实现
路由自动注册实现起来挺简单的,只需拿到所有的Controller配置到路由就行,代码如下
package com.nmtx.route;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jfinal.config.Routes;
import com.jfinal.core.Controller;
import com.nmtx.utils.ClassUtils;
public class AutoRoute extends Routes {
public static Logger log = LoggerFactory. getLogger(AutoRoute.class);
private String packageName;
public AutoRoute(String packageName) {
this.packageName = packageName;
}
@SuppressWarnings("unchecked")
public List<Class<? extends Controller>> getControllerClass() throws ClassNotFoundException {
List<Class<?>> allClass = ClassUtils.scanPackage(packageName);
List<Class<? extends Controller>> controllerClasses = new ArrayList<Class<? extends Controller>>();
for (Class<?> controllerClass : allClass) {
controllerClasses.add((Class<? extends Controller>) controllerClass);
}
return controllerClasses;
}
@Override
public void config() {
try {
List<Class<? extends Controller>> controllerClassList = getControllerClass();
for (Class<? extends Controller> controllerClass : controllerClassList) {
add("/" + controllerClass.getSimpleName().replace("Controller", "").toLowerCase(), controllerClass);
}
} catch (ClassNotFoundException e) {
log.error("auto route exception ",e);
}
}
}
二、使用
/**
* 配置访问路由
*/
@Override
public void configRoute(Routes me) {
me.add(new AutoRoute("com.nmtx.manager.controller"));
}
就可以专心写你的方法了,注解ActionKey可覆盖自动路由的配置
如果你的Controller叫UserController,访问路径就是/user+methodName
是不是很爽,结合自动表注册插件,参数校验插件,增删改的一步封装,用JFinal开发应用,真正的做到了只关注业务,让你有更多时间,陪妹子,陪家人,最后感谢波总的JFinal神器