我有一些路线定义为:
Post /login controllers.MyController.someMethod()
在 someMethod
中,我使用 DynamicForm
从 post 请求中提取参数。
在浏览器或任何使用 Post 方法的客户端上工作正常。
但是如果我需要在某些操作方法(比方说someAnotherMethod
)中调用此 url 并且还想传递一些参数,我该如何实现呢?我的意思是:
public static Result someAnotherMethod() {
// want to put some data in post request body and
return redirect(routes.MyController.someMethod().url());
最佳答案
1。带有参数(这不是重定向!)
您可以从其他方法返回 Result
而无需重定向:
public static Result someMethod(){
DynamicForm dynamicForm = form().bindFromRequest();
return otherMethod(dynamicForm);
}
public static Result otherMethod(DynamicForm dataFromPrevRequest) {
String someField = dataFromPrevRequest.get("some_field");
Logger.info("field from request is: " + someField);
return ok("Other method's Result");
}
2。使用缓存(可能是这些解决方案中 POST 数据的最佳替代品)
您还可以将来自传入请求的数据存储到数据库,甚至“更便宜”到 Cache然后用其他方法获取它。:
public static Result someMethod(){
DynamicForm dynamicForm = form().bindFromRequest();
Cache.set("df.from.original.request", dynamicForm, 60);
return redirect(routes.Application.otherMethod());
}
public static Result otherMethod() {
DynamicForm previousData = (DynamicForm) Cache.get("df.from.original.request");
if (previousData == null) {
return badRequest("No data received from previous request...");
}
// Use the data somehow...
String someData = previousData.get("someField");
// Clear cache entry, by setting null for 0 seconds
Cache.set("df.from.original.request", null, 0);
return ok("Previous field value was " + someData);
}
3。作为普通 GET
最后,您可以只使用必需的参数创建方法,并在第一个方法(接收请求)中传递它们。
public static Result someMethod(){
DynamicForm df = form().bindFromRequest();
return redirect(routes.Application.otherMethod(df.get("action"), df.get("id")));
}
public static Result otherMethod(String action, Long id) {
return ok("The ID for " + action +" action was" + id);
}
关于java - 游戏框架 : how to redirect to a post call inside controller action method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13068523/