Book Image

Play Framework Cookbook - Second Edition

By : Alexander Reelsen, Giancarlo Inductivo
Book Image

Play Framework Cookbook - Second Edition

By: Alexander Reelsen, Giancarlo Inductivo

Overview of this book

<p>As web and mobile systems become more sophisticated, anchoring systems in a mature, solid framework has become increasingly important. Play 2 provides developers with the necessary tools to build robust web applications.</p> <p>This book is a compilation of useful recipes aimed at helping developers discover the power of Play 2. The introductory section serves as a primer to Play Framework, wherein all the fundamentals of the framework are covered extensively. It then explains the usage of controllers and how modules can be leveraged for optimal performance. Next, the book walks you through creating and using APIs, followed by extensive real-world applications. Finally, you will learn to manage applications post production.</p>
Table of Contents (15 chapters)
Play Framework Cookbook Second Edition
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Working with controllers and routes


Play applications use controllers to handle HTTP requests and responses. Play controllers are composed of actions that have specific functionality. Play applications use a router to map HTTP requests to controller actions.

How to do it...

To create a new page, which prints out "Hello World" for a Play Java project, we need to take the following steps:

  1. Run the foo_java application with Hot-Reloading enabled:

        $ activator "~run"
    
  2. Edit foo_java/app/controllers/Application.java by adding the following action:

        public static Result hello() {
          return ok("Hello World");
        }
  3. Edit foo_java/conf/routes by adding the following line:

        GET    /hello    controllers.Application.hello()
  4. View your new hello page using a web browser:

    http://localhost:9000/hello
    

For Scala, we need to take the following steps:

  1. Run the foo_scala application with Hot-Reloading enabled:

        $ activator "~run"
    
  2. Edit foo_scala/app/controllers/Application.scala by adding the following action:

        def hello = Action {
          Ok("Hello World")
        }
  3. Edit foo_scala/conf/routes by adding the following line:

        GET    /hello    controllers.Application.hello
  4. View your new hello page using a web browser:

    http://localhost:9000/hello
    

How it works…

In this recipe, we enumerated the steps necessary to create a new accessible page by creating a new web action in a controller and defined this new page's URL route by adding a new entry to the conf/routes file. We should now have a "Hello World" page, and all without having to reload the application server.