Skip to content

Step 1 my first controller

opensas edited this page Nov 3, 2011 · 10 revisions

Step 1 - my first controller

Purpose: show live editing capabilities of play -just fix the bug and reload- and developer friendly error reports.

Note: you can get the sources of this step with the following commands

cd ~/devel/apps
git clone git://github.com/opensas/play-demo.git
cd play-demo
git checkout origin/01-my_first_controller

Edit Application.index.html template

Go to app root folder, and, if it's not already started, start your app.

cd ~/devel/apps/play-demo
play run

Open a browser and navigate to localhost:9000, you should see play's welcome page.

Now open the template page with your favorite editor, for example gedit.

gedit app/views/Application/index.html

This is a fine opportunity to also show main.html and briefly explain template inheritance.

Get rid of the welcome tag and replace it with your own salutation, like the following

#{extends 'main.html' /}
#{set title:'Home' /}

Hello!

Save the file, go back to your browser and refresh the page. No need to compile, deploy or anything like that, just modify the source code and hit refresh.

Now we will let the user indicate it's name using the url. Open the controller file at app/controllers/Application.java

public class Application extends Controller {
    public static void index(String name) {
        render(name);
    }
}

And modify the template

#{extends 'main.html' /}
#{set title:'Home' /}

Hello ${name}!

And then navigate to http://localhost:9000?name=stranger

Now we will provide a default value for the name variable, so go back to the controller an type:

public class Application extends Controller {
    public static void index(String name) {
	if (name==null) name = "unknown visitor"
        render(name);
    }
}

And then navigate to http://localhost:9000

Oops, you forgot the ";", and you'll see how play tells you so

Compilation error
The file /app/controllers/Application.java could not be compiled. Error raised is : Syntax error, insert ";" to complete Statement

In /app/controllers/Application.java (around line 12)

8:  import models.*;
9: 
10: public class Application extends Controller {
11: public static void index(String name) {
12:   if (name==null) name = "unknown"
13:     render(name);
14:   }
15: }

Just fix the typo, add the semicolon, and hit reload.


Now you can move on to Step 2 - working with models