【问题标题】:Implementing Controller and Routes in Java在 Java 中实现控制器和路由
【发布时间】:2015-05-25 13:20:14
【问题描述】:

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

路由在文件中定义如下:

"/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

    }
}

我目前有两个控制器,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);
    }
}

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

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

任何有关如何以有效方式执行此操作的建议或示例都会非常有帮助。

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

【问题讨论】:

    标签: java routes front-controller


    【解决方案1】:

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

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

    所以

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

    导致

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

    这将使您更快地实施。

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

    【讨论】:

    • 确实!那很有帮助。谢谢
    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 2023-03-27
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    相关资源
    最近更新 更多