Learn Java for Web Development

(Tina Meador) #1
CHAPTER 7: Rapid Web Development with Grails 303

This will create a new directory called helloworld inside the current one that contains the project, in
other words, your workspace. Navigate to this directory in your console:


cd helloworld


Change into the helloworld directory you just created and start the Grails interactive console by
typing the grails command.


\grails2-workspace\helloworld>grails


This will download several resources, and then you should see a prompt, as illustrated in Figure 7-2.


Figure 7-2. Grails interactive console


What we want is a simple page that just prints the message “Hello World” to the browser. In Grails,
whenever you want a new page, you create a new controller action for it. Since we don’t yet have a
controller, let’s create one now with the create-controller command.


grails> create-controller hello


The previous command will create a new controller called HelloController.groovy as illustrated in
Listing 7-1, in the grails-app/controllers/helloworld directory.


Listing 7-1. HelloController.groovy


package helloworld


class HelloController {


def index() { }
}


We now have a controller, so let’s add an action to generate the “Hello World” page. The code looks
like Listing 7-2.


Listing 7-2. Modifying the Index Action


def index() { render "Hello World" } }


The action is simply a method. In this particular case, it calls a special method provided by Grails to
render the page.


To see your application in action, you need to start up a server with another command called
run-app.


grails> run-app

Free download pdf