在Play Framework 2.0中路由重载函数 [英] Routing overloaded functions in Play Framework 2.0

查看:136
本文介绍了在Play Framework 2.0中路由重载函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Play中,当重载控制器方法时,那些单独的方法不能被多次路由,因为编译器不喜欢它。

In Play, when overloading controller methods, those individual methods cant be routed more than once cause the complier doesn't like it.

有没有办法可以绕过这个?

Is there a possible way to get around this?

假设我的 Product 控制器中有两个函数: getBy (字符串名称) getBy(长id)

Say if I had two functions in my Product controller: getBy(String name) and getBy(long id).

我有两个在路线中声明的这些功能的不同路线

GET /p/:id            controllers.Product.getBy(id: Long)
GET /p/:name          controllers.Product.getBy(name: String)

我想对不同的路线使用相同功能,这可能吗?

I want to use the "same" function for different routes, is this possible?

推荐答案

不,这是不可能的,有两种解决方案。

No, it's not possible, there are two solutions.

首先使用2个名称:

public static Result getByLong(Long id) {
    return ok("Long value: " + id);
}

public static Result getByString(String name) {
    return ok("String value: " + name);
}

你也应该为它使用单独的路线,否则你会得到类型不匹配

also you should use separate routes for it, otherwise you'll get type mismatch

GET   /p-by-long/:id         controllers.Monitor.getByLong(id: Long)
GET   /p-by-string/:name     controllers.Monitor.getByString(name: String)

第二个解决方案使用一个带String参数的方法,并在内部检查是否可以转换为Long

Second solution is using one method with String argument and check internally if it can be converted to Long

public static Result getByArgOfAnyType(String arg) {
    try {
        Long.parseLong(arg);
        return ok("Long: " + arg);
    } catch (Exception e) {
        return ok("String: " + arg);
    }
}

路线:

GET   /p/:arg     controllers.Monitor.getByArgOfAnyType(arg : String)

我知道这不适合你的问题,但至少可以节省你的时间。还要记住,可以有更好的方法来确定String是否可以转换为数字类型,即在这个问题中:什么是最好的检查方式查看String是否表示Java中的整数?

I know that doesn't fit your question but at least will save your time. Also keep in mind that there could be better ways to determine if String can be converted to numeric type, ie in this question: What's the best way to check to see if a String represents an integer in Java?

这篇关于在Play Framework 2.0中路由重载函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆