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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.237.79