Spray.io搭建Rest — 支持Twirl模板并部署

Spray.io尝试 html

Spray.io 支持Twirl模板并部署

       今天咱们在上一篇的基础上添加集成Twirl模板功能以及怎样去打包运行。 java

项目地址:http://git.oschina.net/for-1988/Simples/tree/master/SpraySimple

Twirl

       TwirlPlay Framework 的scala默认模板引擎,它是能够独立运行在任何一个Scala项目中的,并不依赖任何Play的东西。Twirl受.NET MVC的Razor灵感启发,语法跟Razor十分类似,写.net的时候用过一次。感受很是不错。Twirl模板经过sbt-twirl插件会被预先编译成scala代码,而后在咱们的代码中能够直接调用这个模板对象,给它参数,而后渲染。因此它并不依赖web环境,任何scala工程均可以直接使用。 git

添加Twirl支持

添加sbt-twirl插件,咱们在工程的project中新增plugin-twirl.sbt文件 github

resolvers += Classpaths.sbtPluginSnapshots

addSbtPlugin("io.spray" %% "sbt-twirl" % "0.7.0")

而后在build.sbt文件中,加入Twirl的配置 web

import twirl.sbt.TwirlPlugin.Twirl

//... Other setting

Seq(Twirl.settings: _*)

在工程中,添加source目录 src.main.twirl 并建立index.scala.html文件 shell

路由返回HTML

path("html" / Segment) {
          message => get {
            respondWithMediaType(`text/html`) {
              encodeResponse(Gzip) {
                complete(page.html.index(message).toString())
              }
            }
          }
        } ~

    让一个请求返回Html格式的代码,只需经过respondWithMediaType来指定返回的Content-Type的值 json

返回json的话,能够让咱们的类继承于Json4sSupport,而后实现隐式方法 implicit def json4sFormats: Formats = DefaultFormats  就能够了,可是这样作若是你的一个处理类须要同时支持json跟html的话,就会出现问题。因此咱们下面作了一下简单的封装 app

同时支持模板和Json

import spray.routing._
import spray.routing.directives.RespondWithDirectives
import spray.http.MediaTypes._
import spray.httpx.marshalling.Marshaller
import spray.http.ContentTypes
import org.json4s.native.Serialization
import org.json4s.{DefaultFormats, Formats}
import spray.httpx.encoding.Gzip
import akka.actor.ActorSystem

/**
 * Created by JiangFeng on 2014/4/29.
 */
trait DefaultDirectives extends Directives {

  this: RespondWithDirectives =>

  implicit def json4sFormats: Formats = DefaultFormats

  def responseJson(obj: AnyRef): Route = {
    respondWithMediaType(`application/json`) {
      implicit def json4sMarshaller[T <: AnyRef] =
        Marshaller.delegate[T, String](ContentTypes.`application/json`)(Serialization.write(_))
      complete {
        obj
      }
    }
  }

  def responseHtml(html: String)(implicit system: ActorSystem): Route = {
    respondWithMediaType(`text/html`) {
      encodeResponse(Gzip) {
        complete(html)
      }
    }
  }

}



而后让咱们的类继承与咱们本身写的 DefaultDirectives来替代 spray.routing. Directives  

class IndexActor extends Actor with ActorLogging {
  override def receive = {
    case None =>
  }
}

class IndexService(index: ActorRef)(implicit system: ActorSystem) extends DefaultDirectives {

  lazy val route =
      path("echo" / Segment) {
        message => get {
          responseHtml {
            page.html.index(message).toString()
          }
        }
      } ~
      path("person") {
        get {
          responseJson {
            val person = new Person("Feng Jiang", 26)
            person
          }
        }
      }
}
 

打包运行

    spray.io是经过main方法启动,因此咱们须要将工程打包成Runable JAR。咱们须要借助 sbt-assembly 插件。一样的project 目录中添加 plugin-assembly.sbt文件 ide

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.11.2")

    咱们再在工程的根目录下添加一个 assembly.sbt 文件 ui

import sbtassembly.Plugin._
import AssemblyKeys._

assemblySettings

jarName in assembly := "SpraySimple.jar"

name := "SpraySimple"

version := "1.0"

scalaVersion  := "2.10.3"

scalacOptions := Seq("-unchecked", "-deprecation", "-encoding", "utf8")
而后进入工程的根目录,也就是assembly文件所在的目录。打开cmd的窗口,输入
> sbt

而后执行 assembly 命令

sbt > assembly

而后,咱们能够看到打包生成到的目录 ~\target\scala-2.10 下面,执行该JAR文件

> java -jar SpraySimple.jar
就能够启动咱们所写的工程了。 
相关文章
相关标签/搜索