CHAPTER 8: Play with Java and Scala 357
Browser Router Controller
View
Model
Request Invoke
Invoke
Update
Retrieve
Response
Figure 8-1. MVC in Play 2
The request flow in the MVC architecture illustrated in Figure 8-1 is as follows:
- An HTTP request is received by the router.
- The router finds the action defined in the controller to process this request.
- The controller listens for HTTP requests, extracts relevant data from the
requests, and applies changes to the model. - The controller renders a template file to generate the view.
- The result of the action method is then written as an HTTP response.
Router
The main entry point of the web application is the conf/routes file that defines the routes needed by
the application. Each route consists of an HTTP method and a URI pattern associated with a call to
an action method. Conf/routes is the configuration file used by the built-in component called Router
that translates each incoming HTTP request to an action call.
Note The HTTP method can be any of the valid methods supported by HTTP (GET, POST, PUT, DELETE,
and HEAD).
Controller
In a Java EE–based web application, a controller is a Java class that extends the servlet type. Since
Play is not Java EE–centric, a controller in Play 2 is a class in Java or an object in Scala that extends
the controller type (both in Java and Scala). This controller type is provided in the play.api.mvc
package. A controller in Play 2 comprises a public, static method called an action. An action is
basically a method that processes the request parameters and produces a result to be sent to the
client. The controller responds to requests, processes them, and invokes changes on the model.
Controllers are, by default, defined in the controllers package under the source root—the app folder.