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:

after((request, response) -> {
      response.header("x-api-key", "set by after filter");
});

After-after-filters are evaluated following after-filters. Think of them like a finally block.

afterAfter((request, response) -> {
    response.header("x-my-data", "set by afterAfter filter");
});

Filters are helpful for implementing common functionality for many different paths in your application.

Sessions, cookies, and more

Spark has support for sessions, cookies, serving static files, views and templates, and much more.

Sessions

To get at the session object, use the request.session method:

request.session(true); // create and return session

Passing in true (as above) will force the creation of a new session if there is not one already for the current user’s request.

Spark’s session object has many helpful methods:

request.session().attribute("user"); // 1
request.session().attribute("user","foo"); // 2
request.session().removeAttribute("user"); // 3
request.session().attributes(); // 4
request.session().id(); // 5
  1. Gets `session().attribute (“user”).
  2. Sets session().attribute (“user”) to foo.
  3. Removes session().attribute (“user”).
  4. Gets all session attributes.
  5. Gets the session ID.

Cookies

Likewise, Spark has great support for Cookies:

request.cookies(); // 1
request.cookie("foo"); // 2
response.cookie("foo", "val"); // 3
response.cookie("foo", "val", 3600); // 4
response.cookie("foo", "val", 3600, true); // 5
response.removeCookie("foo"); // 6
  1. Get the map of all request cookies.
  2. Access request cookie by name (foo).
  3. Set cookie with a value (name of foo, with value, val).
  4. Set cookies with a max-age in seconds.
  5. Sets a secured cookie.
  6. Removes a cookie named foo.

Static Files

You can serve static files using the staticFiles.location method. For example:

staticFiles.location("/public");

Templates

Spark has community-provided wrappers for a lot of popular template engines, including Velocity, Freemarker, Mustache, Handlebars, Jade, Thymeleaf, and others.

First, add the dependency:

compile 'com.sparkjava:spark-template-freemarker:2.7.1'

Then, you can use the corresponding template-engine to render your model and view:

import spark.ModelAndView;
import spark.template.freemarker.FreeMarkerEngine;
// ...later on in the code:
get("template-example", (req, res) -> {
        Map<String, Object> model = new HashMap<>();
       // set various parts of the model...
       // then render:
       return new FreeMarkerEngine().render(
           new ModelAndView(model, "path-to-template")
        );
});

For more details, check out the excellent online documentation.

Get hands-on with 1200+ tech skills courses.