Cra*_*ezz 5 java overloading playframework
如何在Play项目中的Application.java中设置重载方法?
这是我正在做的一些例子:
Application.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);
}
}
Run Code Online (Sandbox Code Playgroud)
路线
# 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}
Run Code Online (Sandbox Code Playgroud)
考试:
getData不带参数调用http://localhost:9000/datagetData使用参数调用http://localhost:9000/data?name=test结果:
我想要的结果是什么:
我很感激你的帮助.谢谢...
以下是基于Daniel Alexiuc建议我正在做的事情:
Application.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);
}
}
Run Code Online (Sandbox Code Playgroud)
路线
GET / Application.index
GET /default Application.getData
GET /dataString Application.getDataName
Run Code Online (Sandbox Code Playgroud)
Application.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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
路线
GET /data Application.getData
GET /data/{name} Application.getData
GET /data/{name}/{age} Application.getData
Run Code Online (Sandbox Code Playgroud)
而对于电话:
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"
Run Code Online (Sandbox Code Playgroud)
我认为不可能像您想要的那样在路由文件中重载它。
但你可以这样做:
public static void getData(String name) {
if (name == null) {
renderText("Without Parameter");
} else {
renderText("With Parameter name = " + name);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1546 次 |
| 最近记录: |