How to properly flash a message with spark framework

582 Views Asked by At

How should I properly flash a message (display only once, for example after unsuccessful login once display a red text saying what went wrong) in spark framework? (Template variable is not an option, I need to pair this with a redirect)

1

There are 1 best solutions below

0
On BEST ANSWER

You can set the message in a session attribute. Then ensure that when its read it is deleted from the session.

To set a session attribute:

req.session().attribute(FLASH_MESSAGE, "Message");

Then retrieve it like this, notice it is removed immediately after being retrieved:

public String getFlashMessage() {
    String message = session.attribute(FLASH_MESSAGE);
    session.removeAttribute(FLASH_MESSAGE);
    return message;
}

If you put the getFlashMessage() method in a bean thats set as a template parameter, you can then reference the flashMessage property on that bean, it will get read once and then removed from the session. So if this (or a new) page is reloaded it won't display again.