Learn Java for Web Development

(Tina Meador) #1
CHAPTER 8: Play with Java and Scala 365






  1. import views.html.*;



  2. public class Application extends Controller {



  3. public static Result index() {

  4. return ok(index.render("Your new application is ready."));

  5. }



  6. }


   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



  1. @(message: String)



  2. @main("Welcome to Play") {



  3. @play20.welcome(message, style = "Java")



  4. }


   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.
Free download pdf