gpt4 book ai didi

java - 用 Java 实现 Controller 和路由

转载 作者:行者123 更新时间:2023-11-30 08:10:35 25 4
gpt4 key购买 nike

我正在实现一个网络应用程序,它使用路由器来验证传入的请求并将其映射到 Controller 中的操作。

路由在如下文件中定义:

"/users/all","UserController.all"
"/users/user_id","UserController.get"
"/posts/add","PostController.add"
"/posts/post_id","PostContoller.get"

Routes 类如下:

public class Routes {

HashMap<String,String> routes;

public Routes() {
this.routes = new HashMap<String,String>();
readRoutes();
}

public HttpResponse route(HttpRequest request) {
String mapper[] = routes.get(request.getUri()).split(".");
try {
return (HttpResponse) Class.forName(mapper[0]).getMethod(mapper[1],HttpRequest.class).invoke(null, request);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}

private void readRoutes() {
// Reads the routes file and loads the routes hash map

}
}

我目前有两个 Controller ,User 和 Post,如下所示:

public class UserController {

public static Collection<String> all(HttpRequest request) {
return DB.Users.all();
}

public static String get(HttpRequest request) {
// Extract id from request
return DB.Users.get(id);
}
}

public class PostController {

public static void add(HttpRequest request) {
// Get the data from the request and do the processing
return DB.Posts.add(data);
}

public static String get(HttpRequest request) {
// Extract id from request
return DB.Posts.get(id);
}
}

上面的例子只是为了说明我想要实现的目标。对任何异常的明显检查都被忽略了。

我的问题是:路由类将路由 HashMap 中的值(字符串)转换为 Controller 中的方法并调用它。这是一种有效的方法吗?我读到以这种方式调用方法是一种不好的编码方式,应该避免,但我不确定如何实现这一点。每次匹配请求时,路由都会进行此映射,这会减慢应用程序的速度吗?

任何有关如何有效地做到这一点的建议或示例都会非常有帮助。

我知道有很多我可以使用的 MVC 框架,但我真的很想澄清以上内容。

最佳答案

预先计算或缓存这些事先已知的信息:

Class.forName(mapper[0]).getMethod(mapper[1], HttpRequest.class)

所以

this.routes = new HashMap<String, Method>()

导致

routes.get(request.getUri()).invoke(null, request)

它会让您更快地实现。

除此之外,这是一种合理的方法。

关于java - 用 Java 实现 Controller 和路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30439394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com