遵循Scala + Play教程后的错误

时间:2018-04-19 19:30:40

标签: scala

我的基本应用程序中有一些错误,我希望你能帮忙解决。

我正在关注此tutorial

这是我结束的代码:

这是我的app/controllers/HomeController.scala文件:

package controllers

import javax.inject._
import play.api._
import play.api.mvc._

/**
 * This controller creates an `Action` to handle HTTP requests to the
 * application's home page.
 */
@Singleton
class HomeController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {

  /**
   * Create an Action to render an HTML page.
   *
   * The configuration in the `routes` file means that this method
   * will be called when the application receives a `GET` request with
   * a path of `/`.
   */
  def index() = Action { implicit request: Request[AnyContent] =>
    Ok(views.html.index())
  }

  def greet(name: String) = Action {
    Ok("Hello " + name)
  }

  def loginCount(userId: String) = Action {
    Ok(14)
  }
}

这是我的conf/routes文件:

# Routes
# This file defines all application routes (Higher priority routes first)
# https://www.playframework.com/documentation/latest/ScalaRouting
# ~~~~

# An example controller showing a sample home page
GET     /                           controllers.HomeController.index

# Map static resources from the /public folder to the /assets URL path
GET     /assets/*file               controllers.Assets.versioned(path="/public", file: Asset)

GET     /greet                      controllers.HomeController.greet(name)

GET     /user/:userId/login/count          controllers.HomeController.loginCount(userId)

但是当我去localhost:9000时,我得到了:

 /Users/jwan/Desktop/programming/scala_play/playstarter/app/controllers/HomeController.scala:30:7: Cannot write an instance of Int to HTTP response. Try to define a Writeable[Int]
[error]     Ok(14)
[error]       ^
[error] one error found
[error] (Compile / compileIncremental) Compilation failed
[error] application -

! @77jnoh18m - Internal server error, for (GET) [/] ->

并且/ greet有错误。该页面显示:

  

错误请求   对于请求'GET / greet'[缺少参数:名称]

最后,我无法理解routes文件的语法。这是什么类型的文件?当我们写:

GET /greet controllers.HomeController.greet(name)

它是带有两个参数的GET方法吗?到底是怎么回事?这是如何解释的?

修改

所以我让这个工作:

GET     /greet                      controllers.HomeController.greet(name)

然后转到此处:http://localhost:9000/greet?name=jeff

1 个答案:

答案 0 :(得分:1)

您在路线文件中的语法错误,您需要执行以下操作:

GET     /greet/:name                      controllers.HomeController.greet(name)

您可以在路线中指定变量,以及如何将它们传递给控制器​​功能。我不知道具体细节,但该文件会被编译成Scala文件。