concept filter in category scalatra

appears as: filters, filter, filter
Scalatra in Action

This is an excerpt from Manning's book Scalatra in Action.

Scalatra before/after filters are not servlet filters

If you’re coming from a Java background, you may be used to thinking of filters as servlet filters, which are a way of operating on the request at the servlet level.

Although Scalatra classes can be filters in this sense, when we talk about filters in this section, we’re talking about the equivalent of Sinatra’s filters, which are (confusingly) called the same thing.

4.4.1. Selectively running filters

It’s possible to define multiple filters at once, and to run filters selectively. If you wanted to set the content type before every request, but only open and close the database connection when it’s in use on a specific route, you could set up your filters as follows.

Listing 4.16. Multiple and selective filters

Listing 4.16 defines two before filters. The first one will set the contentType before every request.

val devSettings = Seq()

val prodSettings = Seq(
  pipelineStages := Seq(filter),
  includeFilter in filter := "*.less" || "*.css.map"
)

val stage = sys.props.getOrElse("stage", "production")
val webSettings = {
  if (stage == "dev") devSettings
  else prodSettings
}