-
Notifications
You must be signed in to change notification settings - Fork 0
Home
Kim edited this page Sep 5, 2017
·
1 revision
- 核心启动类/Start
public static void main(String[] args) {
// 扫描包, 寻找Router绑定的对象.
List<Class<? extends Router>> classes = RouterHandler.getRouters(true);
// CollectionUtil是HuTool提供的判断集合是否为空的方法, 可自行替换.
if (CollectionUtil.isNotEmpty(classes)) {
classes.stream().forEach(cls -> {
try {
// 反射执行
Router server = cls.newInstance();
server.getClass().getMethod("route").invoke(server);
} catch (InstantiationException | NoSuchMethodException | SecurityException | IllegalArgumentException| IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
});
} else {
Static.log.warn("No router found.");
}
}
- 控制器/Router
在需要注册为控制器的类上实现
Router
接口的route
方法即可完成一个控制器的实现.
public class IndexRouter implements Router {
@Override
public void route() {
// 这里的Spark是Spark框架提供的, 相关文档请参考Sprak文档. http://sparkjava.com/documentation
Spark.get("/", (request, response) -> {
return "Hello, this is index!";
});
Spark.path("/api", () -> {
Spark.get("/account", IndexController::api);
});
}
private static String api(Request requset, Response response) {
return "Hello, this is api.";
}
}