http4s on the servlet container

Naoki Takezoe
2 min readMay 5, 2018

http4s is a typeful, functional and streaming HTTP toolkit covering both client and server. In particular, it’s useful to build JSON based API servers because it has excellent routing DSL and JSON support.

Of course, we know that Akka HTTP is a strong competitor in this field. Akka HTTP is maintained by Akka team in Lightbend and it’s used as a backend of Play Framework which is the most popular web framework in Scala. However http4s has some advantages against Akka HTTP.

One of them is that it supports servlet containers, not only thier own blaze library. Even if we have to use Scala with servlet containers for uncontrollable reason, http4s would be help for us to build modern Scala applications.

How to enable servlet support

To enable servlet support in http4s, add a following dependency to build.sbt instead of a http4s-blaze-server dependency.

"org.http4s" %% "http4s-servlet" % Http4sVersion

Then add xsbt-web-plugin to develop servlet based applications in your sbt project by adding follows to project/plugin.sbt:

addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "4.0.1")

Also you have to add follows to build.sbt to enable this plugin (xsbt-web-plugin also supports TomcatPlugin).

enablePlugins(JettyPlugin)

When you use blaze (used in default), you should have a bootstrap class. Instead, when you use servlet containers, you have to create a servlet context listener to setup http4s on the servlet container like this:

package com.example.quickstart

import javax.servlet.annotation.WebListener
import javax.servlet.{ServletContextEvent, ServletContextListener}
import org.http4s.servlet.syntax.ServletContextSyntax

@WebListener
class Bootstrap extends ServletContextListener
with ServletContextSyntax {
def helloWorldService[F[_]: Effect]
= new HelloWorldService[F].service
override def contextInitialized(sce: ServletContextEvent) = {
val context = sce.getServletContext
context.mountService("helloService", helloWorldService)
}
override def contextDestroyed(sce: ServletContextEvent) = ()
}

Now you can run your http4s application bysbt ~jetty:start and create a war file by sbt package using xsbt-web-plugin. See the documentation to know more about xsbt-web-plugin.

Anyway, http4s is a precious modern web framework which supports servlet containers in the Scala world. It makes possible to build our applications functionally even on servlet containers.

In fact, we had to use a servlet container to integrate GitServlet which is provided a part of JGit with our Scala application to add Git server functionallity. In another case, using a servlet container was a request from our customer which is caused by infrastructure restriction.

While we’ve used another servlet based web frameworks unti now, but they were not enough to use to build modern Scala application. Now http4s would be a great help for us in such situations!

--

--