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/:
spray.servlet.Initializer
SprayConnectorServlet
spray.servlet.Servlet30ConnectorServlet
true
SprayConnectorServlet
/*
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:
```conf` spray.servlet { boot-class = "Boot" }
[on spray.io is a good example application](https://github.com/spray/spray-template/tree/on_jetty_1.3_scala-2.11) 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