CHAPTER 8: Play with Java and Scala 365
- import views.html.*;
- public class Application extends Controller {
- public static Result index() {
- return ok(index.render("Your new application is ready."));
- }
- }
Line 8: The Application controller class extends play.mvc.Controller.
Line 10: The public static index() action returns a Result. All action methods
return a Result. The Result represents the HTTP response to be sent back to
the browser.
Line 11: Here, the action returns a 200 OK response with an HTML response
body. The HTML content is provided by a template. An action always returns an
HTTP response, which is represented in Play 2 by the Result type. The Result
type must be a valid HTTP response, so it must include a valid HTTP status code.
OK sets it to 200.The render() method references a template file in Play 2.
The template is defined in the app/views/index.scala.html source file. This file is illustrated in
Listing 8-2.
Listing 8-2. index.scala.html
- @(message: String)
- @main("Welcome to Play") {
- @play20.welcome(message, style = "Java")
- }
Line 1: The Scala statement starts with the special @ character. The first line
defines the function signature. Here it takes a single String parameter.
A template is like a function, and thus it needs parameters, which are declared
at the top of the template file.
Line 3: This line invokes a function named main with one string argument.
Lines 3 to 7: These lines comprise the main function block.
Line 5: Line 5 uses a function called welcome, provided by Play 2. This function
renders the default welcome HTML page, which is in the file named main.scala.
html also located in apps/views folder.
Line 5: The welcome function has an extra parameter style that informs the
template that this is a Java-based application, and then this style parameter is
used by the welcome template to show links to documentation.