Class RsFlash

  • All Implemented Interfaces:
    Body, Head, Response

    public final class RsFlash
    extends RsWrap
    Forwarding response.

    This class helps you to automate the flash message mechanism, by adding flash messages to your responses.

    The flash concept is taken from Ruby on Rails, it is actually the ability to pass temporary variables between requests which is particularly helpful especially in case of a redirect.

    The flash message mechanism is meant to be used in case you have a dynamic content to render in which you want to add success or error messages. The typical use case is when you have a form that the user can submit and you want to be able to indicate whether the request was successful or not.

    The flash mechanism is a stateful mechanism based on a cookie so it is not meant to be used to implement stateless components such as a RESTful service.

    Here is a simple example that shows how to properly use it:

    public final class TkDiscussion implements Take {
       @Override
       public Response act(final Request req) throws IOException {
         return new RsForward(new RsFlash("thanks for the post"));
       }
     }

    This decorator will add the required "Set-Cookie" header to the response. This is all it is doing. The response is added to the cookie in URL-encoded format, together with the logging level. Flash messages could be of different severity, we're using Java logging levels for that, for example:

    public final class TkDiscussion implements Take {
       @Override
       public Response act(final Request req) throws IOException {
         return new RsForward(
           new RsFlash(
             "can't save your post, sorry",
             java.util.logging.Level.SEVERE
           )
         );
       }
     }

    This is how the HTTP response will look like (simplified):

     HTTP/1.1 303 See Other
     Set-Cookie: RsFlash=can%27t%20save%20your%20post%2C%20sorry/SEVERE

    Here, the name of the cookie is RsFlash. You can change this default name using a constructor of RsFlash.

    To clean up the cookie in the following requests, you will need to decorate your Take with TkFlash.

    The class is immutable and thread-safe.

    Since:
    0.1