Routing overloaded functions in Play Framework 2.0

落花浮王杯 提交于 2020-01-23 08:35:14

问题


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?

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

And I had two different routes for these functions declared in routes:

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?


回答1:


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

First is to use 2 names:

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)

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);
    }
}

route:

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

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?



来源:https://stackoverflow.com/questions/10524047/routing-overloaded-functions-in-play-framework-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!