playframework:如何在控制器动作方法内重定向到一个post调用

gmu*_*mad 1 java playframework-2.0

我有一些路线定义为:

Post /login  controllers.MyController.someMethod()
Run Code Online (Sandbox Code Playgroud)

在内部someMethod我用来DynamicForm从post请求中提取参数.

使用Post方法从浏览器或任何客户端正常工作.

但是如果我需要在一些动作方法中调用这个url(比如说someAnotherMethod)并且想要传递一些参数,我该如何实现呢?我的意思是:

public static Result someAnotherMethod() {
// want to put some data in post request body and
return redirect(routes.MyController.someMethod().url());
Run Code Online (Sandbox Code Playgroud)

bie*_*ior 6

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");
}
Run Code Online (Sandbox Code Playgroud)

2.使用缓存(可能是这些解决方案中POST数据的最佳替换)

您还可以将来自传入请求的数据存储到数据库中,甚至可以"更便宜"地存储到缓存中,然后以其他方法获取它:

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);
}
Run Code Online (Sandbox Code Playgroud)

3.作为普通的GET

最后,您只需创建具有所需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);
}
Run Code Online (Sandbox Code Playgroud)