如何在 Play Project 的 Application.java 中设置重载方法?
这是我目前正在做的一些例子:
应用程序.java
public class Application extends Controller {
public static void index() {
render();
}
public static void getData() {
renderText("Without Parameter");
}
public static void getData(String name) {
renderText("With Parameter name = " + name);
}
}
路线
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
# Home page
GET / Application.index
GET /data Application.getData
# Ignore favicon requests
GET /favicon.ico 404
# Map static resources from the /app/public folder to the /public path
GET /public/ staticDir:public
# Catch all
* /{controller}/{action} {controller}.{action}
考试:
getData
无参数调用http://localhost:9000/data
getData
带参数调用http://localhost:9000/data?name=test
结果:
- 使用参数名称 = null
- 使用参数名称 = 测试
我想要的结果:
- 无参数
- 使用参数名称 = 测试
我非常感谢您的帮助。谢谢...
更新解决方案
这是我根据Daniel Alexiuc的建议正在做的事情:
应用程序.java
public class Application extends Controller {
public static void index() {
render();
}
public static void getData() {
/**
* Do some process before call getDataName method
* and send the result of the process as the parameter.
* That's why I do this way that look like redundancy process.
**/
getDataName(null);
}
public static void getDataName(String name) {
// Didn't use ternary operation here because will become error 'not a statement'
if(name == null)
renderText("Without Parameter");
else
renderText("With Parameter name = " + name);
}
}
路线
GET / Application.index
GET /default Application.getData
GET /dataString Application.getDataName
更新解决方案 (26/07)
应用程序.java
public class Application extends Controller {
public static void index() {
render();
}
public static void getData(String name, Integer age) {
if (name == null && age == null) {
renderText("Data null");
} else if (name != null && age == null) {
renderText("Name: " + name);
} else if (name != null && age != null) {
renderText("Name: " + name + "\n" + "Age: " + age);
}
}
}
路线
GET /data Application.getData
GET /data/{name} Application.getData
GET /data/{name}/{age} Application.getData
对于通话:
1. http://localhost:9000/data -> Display "Data null"
2. http://localhost:9000/data/Crazenezz -> Display "Name: Crazenezz"
3. http://localhost:9000/data/Crazenezz/24 -> Display "Name: Crazenezz
Age: 24"