Filters and Sessions

Learn about filters, sessions, and cookies in Spark.

Filters

Filters can be run before or after requests and can read the request, can read and modify the response, and even stop processing of a request (using halt).

Before-filters are evaluated before each request. Here’s an example:

before((request, response) -> {
    boolean authenticated;
    // ... check if authenticated
    if (!authenticated) {
       halt(401, "You are not welcome here");
    }
});

Filters optionally take a pattern, causing them to be evaluated only if the request path matches that pattern:

before("/protected/*", (request, response) -> {
     // if !authenticated
     halt(401, "Go Away!");
});

After-filters are evaluated after each request. Here’s an example:

 ...