我有一些路线定义为:
Post /login controllers.MyController.someMethod()
和someMethod
内部我使用DynamicForm
从帖子请求中提取参数。
使用Post方法从浏览器或任何客户端正常工作。
但是如果我需要在一些动作方法中调用这个url(比如说someAnotherMethod
)并且想要传递一些参数,我该如何实现呢?我的意思是:
public static Result someAnotherMethod() {
// want to put some data in post request body and
return redirect(routes.MyController.someMethod().url());
答案 0 :(得分:6)
您可以在不重定向的情况下从其他方法返回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");
}
此外,您可以将来自传入请求的数据存储到数据库,甚至可以“更便宜”地存储到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);
}
最后,你可以只创建带有必需args的方法,并在第一种方法中传递它们(接收请求)。
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);
}