2012-05-09 32 views
3

在Play中,當重載控制器方法時,這些單獨的方法不能被路由多次,因爲編譯器不喜歡它。在Play Framework 2.0中路由重載功能

有沒有可能的方法來解決這個問題?

說我在我的Product控制器中有兩個功能:getBy(String name)getBy(long id)

而我卻在routes宣佈這些功能的兩種不同的路線:

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

我想用「同一」功能不同的路線,這可能嗎?

回答

3

不,這是不可能的,有兩種解決方案。

首先是使用2名:

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

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

你也應該使用它不同的途徑,否則你會得到類型不匹配

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

解決方法二使用一個使用String參數的方法,並在內部檢查是否可以將其轉換爲長整型

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) 

我知道這不適合您的問題,但至少可以節省您的時間。還要記住,可以有更好的方法來確定字符串是否可以轉換爲數字類型,即在這個問題中:What's the best way to check to see if a String represents an integer in Java?

+0

第二種解決方案對我來說足夠接近。謝謝。 – snnth

+1

雖然爲什麼不允許? – user2601010