playframework: how to redirect to a post call inside controller action method

落爺英雄遲暮 提交于 2021-02-10 22:41:14

问题


I have some route define as:

Post /login  controllers.MyController.someMethod()

and inside someMethod I use DynamicForm to extract parameters from the post request.

works fine from browser or any client using Post method.

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:


1. With argument (it's not a redirect!)

You can return Result from other method without redirecting:

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. 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. 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);
}


来源:https://stackoverflow.com/questions/13068523/playframework-how-to-redirect-to-a-post-call-inside-controller-action-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!