Scala
Building a war with spray-servlet
We will use spray-servlet to build a war file of our API. So we can run it in a java app server. I assume we already have a working REST API. We will need a web.xml, under src/main/webapp/WEB-INF/:
<?xml version="1.0"?> <web-app> <listener> <listener-class>spray.servlet.Initializer</listener-class> </listener> <servlet> <servlet-name>SprayConnectorServlet</servlet-name> <servlet-class>spray.servlet.Servlet30ConnectorServlet</servlet-class> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SprayConnectorServlet</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>
We need an sbt plugin to build wars. Add this to project/plugins.sbt:
addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "1.0.0")
We’ll add dependencies to build.sbt, and also extra tasks:
name := "exampleAPI" version := "1.0" scalaVersion := "2.11.2" libraryDependencies ++= { val akkaVersion = "2.3.6" val sprayVersion = "1.3.2" Seq( "io.spray" %% "spray-can" % sprayVersion, "io.spray" %% "spray-servlet" % sprayVersion, //We need spray-servlet "io.spray" %% "spray-routing" % sprayVersion, "io.spray" %% "spray-json" % "1.3.1", "io.spray" %% "spray-testkit" % sprayVersion % "test", "org.scalatest" %% "scalatest" % "2.2.4" % "test", "com.typesafe.akka" %% "akka-actor" % akkaVersion, "com.typesafe.akka" %% "akka-testkit" % akkaVersion % "test", "com.typesafe.akka" %% "akka-slf4j" % akkaVersion, "ch.qos.logback" % "logback-classic" % "1.1.2" ) } //This adds tomcat dependencies, you can also use jetty() tomcat()
We’ll need to extend spray.servlet.WebBoot:
import akka.actor.{Props, ActorSystem} import spray.servlet.WebBoot // this class is instantiated by the servlet initializer // it needs to have a default constructor and implement // the spray.servlet.WebBoot trait class Boot extends WebBoot { //we need an ActorSystem to host our application in implicit val system = ActorSystem("SprayApiApp") //create apiActor val apiActor = system.actorOf(Props[ApiActor], "apiActor") // the service actor replies to incoming HttpRequests val serviceActor = apiActor }
And add a reference to this class in application.conf:
spray.servlet { boot-class = “Boot” }
Now we can run sbt package
to build a war. And in sbt, use container:start
to start a tomcat server with our application. And container:stop
to stop it.
A good way to restart the server every time we change code is:
~container:start
Reference: | Building a war with spray-servlet from our JCG partner Tammo Sminia at the JDriven blog. |