I am new to Play Framework and was trying to understand SimpleRouter
class. In the Play documentation, I see a simple example as:
val router = Router.from {
case GET(p"/hello/$to") =>
Action {
Results.Ok(s"Hello $to")
}
}
But I am not sure what is Action
and what is its significance? I see it heavily used in all other routing methods as well. Here's the link to the documentation:
My reference code:
import play.api.mvc._
import play.api.routing.Router._
import play.api.routing._
import play.api.routing.sird._
class CacheRouter extends SimpleRouter {
override def routes: Routes = {
case GET(p"/") =>
Action {
Results.Ok(s"Hello")
}
// case POST(p"/") =>
// controller.process
//
// case GET(p"/$id") =>
// controller.show(id)
}
}
CodePudding user response:
An Action according to the Play documentation here is
basically a (play.api.mvc.Request => play.api.mvc.Result) function that handles a request and generates a result to be sent to the client.
In other words, an Action a full implementation of the server side of the http request that is able to take a play.api.mvc.Request
and do some work and return a play.api.mvc.Result
In your example the Action is one that does not use anything from the request and returns a static HTTP 200 response with the content hello
Edit: From the comment here it looks like you are having an issue with the Action
in the code sample not being resolved.
The reason for this is that that is not actually a reference to the play.api.mvc.Action
but a helper method to construct Actions.
This helper method is defined in play.api.mbc.AbstractController
which you can extend to make use of it.
An example of this would be something like:
class CacheRouter @Inject()(cc: ControllerComponents) extends AbstractController(cc) with SimpleRouter {
override def routes: Routes = {
case GET(p"/") =>
Action {
Results.Ok(s"Hello")
}
}
}
}
Bear in mind the above is using Plays guice
integration for dependency injection but that is just one of many options available.