Search code examples
javascalaservletsakka-http

akka-http apply javax.servlet.Filter


How does one add a class that implements interface javax.servlet.Filter into an Akka-http service, for instance the example one AkkaHttpMicroservice below:

object AkkaHttpMicroservice extends App with Service {
  override implicit val system = ActorSystem()
  override implicit val executor = system.dispatcher
  override implicit val materializer = ActorMaterializer()

  override val config = ConfigFactory.load()
  override val logger = Logging(system, getClass)

  Http().bindAndHandle(routes, config.getString("http.interface"), config.getInt("http.port"))
}

In Scalatra, one needs to override def init(context: ServletContext), then context.addFilter("mySecurityFilter", SecurityFilter), but its not clear where the ServletContext is accessible in akka-http.


Solution

  • Unfortunately for you Akka-Http is not based on the standard Java Servlet API. Actually the whole HTTP handling is re-implemented from the level of the TCP connection. This is done to fully use the power of Akka/Akka Streams. However it means that you can not apply javax.servlet.Filter to Akka-based application. What you probably want to used instead is Directives.