问题描述
我有一些路由定义为:
Post /login controllers.MyController.someMethod()
在 someMethod
中,我使用 DynamicForm
从 post 请求中提取参数.
and inside someMethod
I use DynamicForm
to extract parameters from the post request.
在浏览器或使用 Post 方法的任何客户端都可以正常工作.
works fine from browser or any client using Post method.
但是如果我需要在某个操作方法中调用这个 url(比如 someAnotherMethod
)并且还想传递一些参数,我该如何实现呢?我的意思是:
But if I need to call this url inside some action method (lets say someAnotherMethod
) and want to pass some parameters also, how can I achieve this? What I mean is:
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 数据替换)
此外,您还可以将传入请求中的数据存储到数据库,甚至可以更便宜"地存储到缓存然后用其他方法获取它.:
2. With cache (probably best replacement of POST data in these solutions)
Also you can store data from incoming request to the database or even 'cheaper' to the Cache and then fetch it in other method.:
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
最后,您可以只使用所需的参数创建方法并将它们传递到第一个方法中(接收请求).
3. As common GET
Finally you can just create method with required args only and pass them in the first method (receiving request).
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);
}
这篇关于playframework:如何重定向到控制器动作方法内的后期调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!