Book Image

Play Framework Cookbook

By : Alexander Reelsen
Book Image

Play Framework Cookbook

By: Alexander Reelsen

Overview of this book

<p>The Play framework is the new kid on the block of Java frameworks. By breaking with existing standards the play framework tries not to abstract away from HTTP as most web frameworks do, but tightly integrates with it. This means quite a shift for Java programmers. Understanding these concepts behind the play framework and its impact on web development with Java are crucial for fast development of applications.<br /><br />The Play Framework Cookbook starts where the beginner documentation ends. It shows you how to utilize advanced features of the Play framework &ndash; piece by piece and completely outlined with working applications!<br /><br />The reader will be taken through all layers of the Play Framework and provided with in-depth knowledge from as many examples and applications as possible. Leveraging the most from the Play framework means to think simple again in a java environment. Implement your own renderers, integrate tightly with HTTP, use existing code, improve site performance with caching and integrate with other web services and interfaces. Learn about non-functional issues like modularity or integration into production and testing environments. In order to provide the best learning experience during reading Play Framework Cookbook, almost every example is provided with source code, so you can start immediately to integrate recipes into your own play applications.</p>
Table of Contents (16 chapters)
Play Framework Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Further Information About the Play Framework
Index

Defining your own controllers


Controllers represent the thin layer between HTTP and business logic. They are called by the router, once the requested resource is mapped successfully to a controller method specified in the conf/routes file.

Getting ready

In order to follow this recipe, you should use the conf/routes file defined in the recipe Defining routes as the entry point to your application in this chapter.

How to do it...

Fire up your favorite editor, open app/controllers/Application.java, and put the following into the file:

package controllers;

import play.*;
import play.mvc.*;
public class Application extends Controller {

    public static void index() {
        render();
    }

    public static void showUser(String id) {
         render();
    }   

    public static void deleteUser(String id) {
        render();
    }

    public static void createUser(User user) {
        render();     
    }   
}

How it works...

Absolutely no business logic happens here. All that is done here is to create a possibility to execute business logic. When looking back at the conf/routes file you see the use of the id parameter, which is again used here as a parameter for the static method inside the Application class. Due to the name of the parameter it is automatically filled with the corresponding part of the URL in the request; for example, calling GET /user/1234 will result in putting "1234" in the ID parameter of the showUser method. The most important fact to make a Java class work as controller is to have it extend from play.mvc.Controller. Furthermore, all your actions have to be static in order to be executed as controller methods.

As no business logic is executed here (such as creating or deleting a user from some database) the render() method is called. This method is again defined in the controller class and tells the controller to start the rendering phase. A template is looked up and rendered. As Play also follows the convention over configuration pattern, a default template location is assumed, which follows an easy naming scheme:

./app/views/${controller}/{method}.html

In the case of showing a user it would be:

./app/views/Application/showUser.html

There's more...

This not only looks pretty simple, it actually is. As Play framework follows the MVC principle, you should be aware that the controller layer should be as thin as possible. This means that this layer is not for business logic but merely for validation in order to ensure the model layer will only get valid data.

Using POJOs for HTTP mapping

As it is not convenient for any web developer to construct the objects by hand from the HTTP parameters, Play can easily do this task for you like this:

    public static void createUser(User user) {

        // Do something with the user object
        // ...
        render();
    }

This requires a certain naming convention of your form elements in the HTML source, which will be shown later.

Using HTTP redirects

Instead of just rendering HTML pages there is another great feature. You can trigger a HTTP redirect by just calling the Java method. Imagine the following code for creating a new user:

   public static void createUser(User user) {

        // store user here..., then call showUser()showUser(user.id);
    }

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

Now the last line of code will not call the static showUser method directly, but instead issue a HTTP 304 redirect response to the client, which includes a Location: /show/1234 response header. This allows easy implementation of the common redirect-after-post pattern, without cluttering your application logic. You only need to be aware that it is not possible to directly call methods marked as public in your controller classes, as the framework intercepts them.

Thread safety

Some Java developers might want to scream in pain and agony now that "Static methods in a controller are not threadsafe!". However, the Controller is bytecode enhanced in order to make certain calls threadsafe, so the developer has not to worry about such issues. If you are interested in knowing more, you might want to check the class play.classloading.enhancers.ControllerEnhancer.

See also

Many recipes will change controller logic. Consider dealing with controllers which is absolute and essential core knowledge.