Search code examples
javahttpflash-messagespark-framework

How to properly flash a message with spark framework


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)


Solution

  • 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.