原文
Play通過HTTP API與JSON庫(kù)共同支持內(nèi)容類型為JSON的HTTP請(qǐng)求和應(yīng)答蹬耘。
關(guān)于 Controllers, Actions, 和routing的詳細(xì)資料看HTTP Programming
我們將通過設(shè)計(jì)一個(gè)簡(jiǎn)單的RESTful Web服務(wù)來解釋必要的概念踊跟,這個(gè)服務(wù)可以GET 到實(shí)體集合啊鸭,并接收POSTs 創(chuàng)建新的實(shí)體峦筒。并且這個(gè)服務(wù)將對(duì)所有的數(shù)據(jù)使用JSON類型陵且。
這是我們?cè)谖覀兊姆?wù)中將使用的模型:
case class Location(lat: Double, long: Double)
case class Place(name: String, location: Location)
object Place {
var list: List[Place] = {
List(
Place(
"Sandleford",
Location(51.377797, -1.318965)
),
Place(
"Watership Down",
Location(51.235685, -1.309197)
)
)
}
def save(place: Place) = {
list = list ::: List(place)
}
}
以Json形式提供實(shí)體列表
我們將以給我們的Controller添加必須的導(dǎo)入開始:
import play.api.mvc._
import play.api.libs.json._
import play.api.libs.functional.syntax._
object Application extends Controller {
}
在我們寫我們的Action之前货葬,我們將需要探究一下從我們的模型轉(zhuǎn)換為JsValue
形式垢粮。這是通過定義隱式Writes[Place]
實(shí)現(xiàn).
implicit val locationWrites: Writes[Location] = (
(JsPath \ "lat").write[Double] and
(JsPath \ "long").write[Double]
)(unlift(Location.unapply))
implicit val placeWrites: Writes[Place] = (
(JsPath \ "name").write[String] and
(JsPath \ "location").write[Location]
)(unlift(Place.unapply))
接下來我們寫我們的Action
def listPlaces = Action {
val json = Json.toJson(Place.list)
Ok(json)
}
Action 取到Place 對(duì)象列表贴届,使用Json.toJson和我們的隱式Writes[Place]
把他們轉(zhuǎn)換成JsValue ,然后再把它作為結(jié)果Body返回。Play將會(huì)認(rèn)出JSON結(jié)果并相應(yīng)的為應(yīng)答設(shè)置 Content-Type頭和Body值毫蚓。最后一步是把我們的Action 路由添加到conf/routes
:
GET /places controllers.Application.listPlaces
我們可以使用瀏覽器或HTTP工具生成一個(gè)請(qǐng)求測(cè)試Action占键,這個(gè)例子使用了Unix的命令行工具 cURL.
curl --include http://localhost:9000/places
應(yīng)答:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 141
[{"name":"Sandleford","location":{"lat":51.377797,"long":-1.318965}},{"name":"Watership Down","location":{"lat":51.235685,"long":-1.309197}}]
通過JSON創(chuàng)建一個(gè)新的實(shí)體引用
對(duì)于這個(gè)Action ,我們將需要定義一個(gè)隱式的 Reads[Place]
來把JsValue
轉(zhuǎn)換成我們的模型。
implicit val locationReads: Reads[Location] = (
(JsPath \ "lat").read[Double] and
(JsPath \ "long").read[Double]
)(Location.apply _)
implicit val placeReads: Reads[Place] = (
(JsPath \ "name").read[String] and
(JsPath \ "location").read[Location]
)(Place.apply _)
這個(gè)Action 比我們的列表例子復(fù)雜些元潘,一些事情需要注意:
- 這個(gè)Action 要求有一個(gè)Content-Type頭為
text/json
或application/json
畔乙,body 包含需要?jiǎng)?chuàng)建的實(shí)體的JSON形式。 - 它使用JSON指定的BodyParser 翩概,它將 解析請(qǐng)求 并提供做為
JsValue
的request.body
- 我們使用依賴我們的隱式
Reads[Place]
的validate 方法進(jìn)行轉(zhuǎn)換啸澡。 - 為了處理驗(yàn)證結(jié)果,我們使用有錯(cuò)誤和成功流的fold氮帐。這個(gè)模式也類似于使用表單提交.
- Action 也發(fā)送JSON應(yīng)答
Body 解析器可以用Case類嗅虏,隱式的Reads 或接受函數(shù)的方式被輸入。因此我們可以省掉更多的工作上沐,讓Play自動(dòng)把Json解析成Case類并在調(diào)用我們的Action之前進(jìn)行[驗(yàn)證]皮服。(https://www.playframework.com/documentation/2.5.x/ScalaJsonCombinators#Validation-with-Reads)
import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._
implicit val locationReads: Reads[Location] = (
(JsPath \ "lat").read[Double](min(-90.0) keepAnd max(90.0)) and
(JsPath \ "long").read[Double](min(-180.0) keepAnd max(180.0))
)(Location.apply _)
implicit val placeReads: Reads[Place] = (
(JsPath \ "name").read[String](minLength[String](2)) and
(JsPath \ "location").read[Location]
)(Place.apply _)
// This helper parses and validates JSON using the implicit `placeReads`
// above, returning errors if the parsed json fails validation.
def validateJson[A : Reads] = BodyParsers.parse.json.validate(
_.validate[A].asEither.left.map(e => BadRequest(JsError.toJson(e)))
)
// if we don't care about validation we could replace `validateJson[Place]`
// with `BodyParsers.parse.json[Place]` to get an unvalidated case class
// in `request.body` instead.
def savePlaceConcise = Action(validateJson[Place]) { request =>
// `request.body` contains a fully validated `Place` instance.
val place = request.body
Place.save(place)
Ok(Json.obj("status" ->"OK", "message" -> ("Place '"+place.name+"' saved.") ))
}
最后,我們將在conf/routes
文件里添加一個(gè)路由綁定:
POST /places controllers.Application.savePlace
我們將使用有效的和無效的請(qǐng)求測(cè)試Action参咙,以驗(yàn)證我們成功和錯(cuò)誤流龄广。
使用有效的數(shù)據(jù)測(cè)試Action:
curl --include
--request POST
--header "Content-type: application/json"
--data '{"name":"Nuthanger Farm","location":{"lat" : 51.244031,"long" : -1.263224}}'
http://localhost:9000/places
應(yīng)答:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 57
{"status":"OK","message":"Place 'Nuthanger Farm' saved."}
使用沒有“name” 字段的無效數(shù)據(jù)測(cè)試Action:
curl --include
--request POST
--header "Content-type: application/json"
--data '{"location":{"lat" : 51.244031,"long" : -1.263224}}'
http://localhost:9000/places
應(yīng)答:
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
Content-Length: 79
{"status":"KO","message":{"obj.name":[{"msg":"error.path.missing","args":[]}]}}
使用錯(cuò)誤數(shù)據(jù)類型“l(fā)at”的無效數(shù)據(jù)測(cè)試Action
:
curl --include
--request POST
--header "Content-type: application/json"
--data '{"name":"Nuthanger Farm","location":{"lat" : "xxx","long" : -1.263224}}'
http://localhost:9000/places
應(yīng)答:
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
Content-Length: 92
{"status":"KO","message":{"obj.location.lat":[{"msg":"error.expected.jsnumber","args":[]}]}}
總結(jié)
Play是被設(shè)計(jì)來支持REST使用JSON并且開發(fā)這些服務(wù)應(yīng)該是簡(jiǎn)單的。大部分的工作是給你的模型寫Reads
和Writes
蕴侧,這將會(huì)在下一節(jié)中詳細(xì)介紹择同。