How to set flash with Java version 2.7.0-M4 API

The value of Flash in View is not get.
How is it correct to migrate?

Controller

public class HomeController extends Controller {

    public Result index() {

        // The value of Flash in View is not get.
        // "FLASH_KEY" has been added to cookies.
        // After Reload, the value of Flash is get.
        Map map = new HashMap();
        map.put("key", "value");
        return ok(index.render("New Flash test.")).withFlash(map);

        // Http.Context.current().flash().put("deprecated_key", "deprecated_value");
        // return ok(index.render("Flash test."));

        // Even in the first case, the value of Flash is get.
        // flash("deprecated_key", "deprecated_value");
        // return ok(index.render("Flash test."));
    }
}

View

@(message: String)

@flash.get("deprecated_key")<br>
@flash.get("key")<br>

I think your code does not make sense. Why do you want to display the flash inside the template BEFORE you refresh the page? Actually flash should be used to transport data between two requests so the data is availabe in the next/second request. So that is working correctly.

In your example you always want to display a value from the flash, even when there was no data in the flash (because there was no previous request of course).
I think you were just using the flash feature in a wrong way. Can you maybe give a real world exampe what you want to try to achieve?

public class HomeController extends Controller {
    public Result index() {
        Http.Request request = ctx().request(); // Get the current request

        // You want to transport this data to the NEXT request
        Map map = new HashMap();
        map.put("key", "value");

        return ok(index.render(request, "New Flash test."))
                .withFlash(map); // Now we put that data into the response so it's available in the next request
    }
}
@(Http.Request request, message: String)

Now we display the data the _previous_ response gave us:
@request.flash().get("key")

BTW: @flash in the template will be deprecated in Play 2.7-RC1 as well. You should just pass the request into the template like I did.

1 Like

Thanks.

  • I understood that it is wrong usage of Flash.
  • With code that is going to be deprecated, Flash values could be acquired with View, so I used it for passing errors.
  • I will try to fix it in the way taught.