当前位置: 首页 > 工具软件 > Spray > 使用案例 >

spray 框架_用Spray-Servlet发动战争

景阳平
2023-12-01

spray 框架

我们将使用spray-servlet构建API的war文件。 因此,我们可以在Java应用服务器中运行它。 我假设我们已经有一个正常工作的REST API。 我们将需要src / main / webapp / WEB-INF /下的web.xml:

<?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>

我们需要一个sbt插件来建立战争。 将此添加到project / plugins.sbt中:

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

我们将为build.sbt添加依赖项,并添加其他任务:

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()

我们需要扩展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
}

并在application.conf中添加对该类的引用:

spray.servlet {
boot-class = “Boot”
}

现在我们可以运行sbt package进行战争了。 在sbt中,使用container:start通过我们的应用程序启动tomcat服务器。 和container:stop停止它。

每次更改代码时,重新启动服务器的一种好方法是:

~container:start

翻译自: https://www.javacodegeeks.com/2015/03/building-a-war-with-spray-servlet.html

spray 框架

 类似资料: