Filters and Sessions
Explore how to apply filters before and after requests to control web app flow, manage user sessions and cookies, serve static files, and integrate various template engines in Spark Java. This lesson equips you with practical skills to build flexible and secure Java web applications using the Spark framework.
We'll cover the following...
We'll cover the following...
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: