使用GET或POST,可以输入参数,如下:
import org.scalatra._
import scalate.ScalateSupport
import com.google.gson.Gson
import java.util.concurrent.TimeUnit
import java.util.Date
class Queue(var id: String, var act: String, var waitSec: Int) {
override def toString = id + ", " + act + ", " + waitSec.toString
}
class MyScalatraServlet extends ScalatraServlet with ScalateSupport {
get("/hello/:query") {
<html>
<body>
<pre>
{params("query")}
</pre>
</body>
</html>
}
post("/hello") {
println("A request comes: " + "%tF %<tT" format new Date)
val jsonString = request.body
try {
val gson = new Gson
val queue = gson.fromJson(jsonString, classOf[Queue])
// for debugging
println("Your name: " + queue)
if (queue.act.equals("stop")) {
println("Wait for: " + queue.waitSec.toString)
TimeUnit.SECONDS.sleep(queue.waitSec)
}
response.addHeader("ACK", "GOT IT")
} catch {
case e: Exception =>
e.printStackTrace
response.addHeader("ACK", "BOOM!")
}
}
notFound {
// Try to render a ScalateTemplate if no route matched
findTemplate(requestPath) map { path =>
contentType = "text/html"
layoutTemplate(path)
} orElse serveStaticResource() getOrElse resourceNotFound()
}
}
- 获取
你应该参考Scalatra 2.4 guide ... Routes
您可以通过访问http://localhost:8080/hello/query查看输入的查询
但是,我认为通过查询输入文件路径并不好。
- 发布
上面的例子,你可以让它停止处理servlet。
遵循 JSON 对处理此代码很有用。
{"id":"001","act":"stop","waitSec":100}
像这样执行卷曲:
$ curl -i -X POST -d "{\"id\":\"001\",\"act\":\"stop\",\"waitSec\":100}" http://localhost:8080/hello -H "Content-Type: application/json"
例如,您可以将 JSON 键值替换为文件路径。