Tuesday, April 28, 2009

Creating home and admin page

[From the series - creating software books reviews grails web application]

In the previous post I have explained some basic aspects of grails front-end. Having this knowledge it is a time to create home page of sbr application. For the list of steps how I got up to this point you may want to have a look at this post pointing to all posts related to sbr series.

If you start sbr application (grails run-app) default home page generated by grails is displayed. This is not very useful page as a home page but will be very useful as admin page. It can be very useful as a admin page because it displays all controllers in your application. For each controller you can generate default list/show/create/edit pages.

So let create home page. To create home page I usually create HomeController. So the first step is to generate home controller. To create home controller type the following command:

grails create-controller Home

This command will generate HomeController.groovy file in the grails-app/controllers folder and home folder in the grails-app/views folder. In this folder we should put our new home page.

So to create home page in the home folder create file home.gsp that should look like this one:

<html>
<head>
<title>SBR</title>
<meta name="layout" content="main" />
</head>
<body>
Welcome to the SBR
</body>
</html>

We want to display this page when ever the HomeController is accessed. This is very easy to achieve. Update the code of the HomeController to look like this:

class HomeController {
def index = {
render (view:'home')
}
}

index closure is default closure of the controller and is executed when controller is accessed without specifying action to be executed. So if you type in your browser http://localhost:8080/sbr/home, index action will be executed. And this action is telling that the view 'home' should be displayed. As you are in the HomeController it will look for the file home.gsp in the grails-app/views/home folder. But if you want in the render closure you can specify the full path to the page to be displayed relative to the views folder. So render (view:'home/home') would be valid too.

Now it is time to create admin page. For admin page we will need AdminController. To create AdminController execute following command:

grails create-controller admin

Same as for the HomeController this command will create file AdminController.groovy and folder admin. To create admin page in the admin folder create admin.gsp file. Copy the content of the web-app/index.gsp file into the admin.gsp file. At the end admin.gsp should look like this:

<html>
<head>
<title>SBR admin</title>
<meta name="layout" content="main" />
</head>
<body>
<div class="dialog" style="margin-left:20px;width:60%;">
<ul>
<g:each var="c" in="${grailsApplication.controllerClasses}">
<li class="controller"><g:link controller="${c.logicalPropertyName}">${c.fullName}</g:link></li>
</g:each>
</ul>
</div>
</body>
</html>

We still need ability to display admin page. To process is the same as for the HomeController. Change the AdminController so it looks like this:

class AdminController {
def index = {
render (view:'admin')
}
}

But still, when you start application and access the link http://localhost:8080/sbr you are getting old index page. To change this change the web-app/index.gsp file to this:

<html>
<body>
<%response.sendRedirect(request.getContextPath()+"/home/");%>
</body>
</html>

This will redirect you to the HomeController and home page will be displayed after accessing sbr application.

We are almost done. But what is still remaining is to update template that we use for our pages. So go the the grails-app/views/layouts/main.gsp file and change it to look like this:

<html>
<head>
<title><g:layoutTitle default="Grails" /></title>
<link rel="stylesheet" href="${createLinkTo(dir:'css',file:'main.css')}" />
<g:layoutHead />
<g:javascript library="application" />
</head>
<body>
<g:layoutBody />
</body>
</html>

What I did are just simple changes to this file. Actually I have only removed some code from file generated by default.

As it turned out that this post is longer than I have expected let me summarize steps I have done. So after your grails application is generated you are ready to create home and future admin page. I am usually doing these steps:

  • Create HomeController and home.gps page
  • Create AdminController and admin.gsp page
  • Change index.gsp file so it redirects to the HomeController
  • Make main.gsp layout file simple.

After those steps basic skeleton of the grails application is prepared.

What remains is to prepare layout of the home.page and this can be achieved by changing main.gsp file. If you remember from the previous post, main.gsp is actually template that we can reuse for all the pages in the grails application. Actually we already did it for the home and admin page.

In the next post I will describe layouting of the main.gsp file or to be more precise I will integrate blueprint css framework into sbr application.

P.S. Don't forget to write some review or post summary on the software books reviews.

Tuesday, April 21, 2009

Starting with front-end in grails application

[From the series - creating software books reviews grails web application]

In the previous post I have explained how to create grails application and some general aspects of the grails application. If you are expert for the web front-end you can probably jump into domain logic but if you are like me, front-end is probably harder part of the web application development. As it is generally advised to start with the more complex parts of the application I am usually setting up at least general aspects of the user interface. So let us see how is solved front-end of the grails application.

View technology of the grails application is groovy server pages or shorter gsp while sitemesh is used as main templating mechanism. To gain knowledge of the existing gsp tags visit grails documentation. There is description and short example for each tag. If you don't know site mesh don't worry because I don't know it either. The main usage is very easy and does not require knowledge of the sitemesh.

First interesting file to notice is main.gsp that is located in the grails-app/views/layouts. This file is template for other pages of the application. Just to notice, you can have any number of "main.gsp" files in your grails application. One for each different situation you need. E.g. one for pages with three columns, one for pages with two columns and so on.

The most important part of the main.gsp file is:

<g:layoutBody />

When some page as template uses main.gsp, the whole content of the main.gsp page will be displayed and the <g:layoutBody /> will be replaced with the body element of the mentioned page. To specify which template should be used for the gsp page, put following construct in the <head> element of the page.

<meta name="layout" content="NAME_OF_TEMPLATE_FILE" />

and replace the NAME_OF_TEMPLATE_FILE with the name of template without gsp extension.

So if you have page like this one:

<html>
<head>
<meta name="layout" content="main" />
</head>
<body>
<p>Hello World</p>
</body>
</html>

the main.gsp will be displayed an the element <g:layoutBody /> will be replaced with <p>Hello World</p>. I am not sure that this is 100% correct but this is generally how it behaves.

If this is still confusing let try to make some simple example. Assume that we have two template files: main1.gsp and main2.gsp that are of course placed in the grails-app/views/layouts directory.

// main1.gsp
<html>
<head>
<title><g:layoutTitle default="Grails" /></title>
<g:layoutHead />
</head>
<body>
<h1>Hello World</h1>
<g:layoutBody />
</body>
</html>



//main2.gsp
<html>
<head>
<title><g:layoutTitle default="Grails" /></title>
<g:layoutHead />
</head>
<body>
<g:layoutBody />
<h1>Hello World</h1>
</body>
</html>

And if we create following two gsp pages

// test1.gsp that uses main1.gsp as a template
<html>
<head>
<meta name="layout" content="main1" />
</head>
<body>
<p>Page 1</p>
</body>
</html>



// test2.gsp that uses main2.gsp as a template
<html>
<head>
<meta name="layout" content="main2" />
</head>
<body>
<p>Page 2</p>
</body>
</html>

test1.gsp will be displayed as:

Hello World
Page 1

while test2.gsp will be displayed as:

Page 2
Hello World

This way you have very powerful tool to create set of pages that look the same and you are just changing the business content of the page. The "same" part should be located in the template file while the "business content" should be located in the page. If for some set of pages you need different layout just create new common template for them. All this magic is possible because grails in the background uses sitemesh for this.

Now when there is basic understanding how front-end works in the grails application we are ready to create our home page. And this will be topic of my next post. I will create dummy home page, admin page from the index.gsp and redirect application to the home page.

P.S. Don't forget to write some review or post summary on the software books reviews.

Friday, April 17, 2009

General Aspects of the Grails Application

[From the series - creating software books reviews grails web application]

In the previous post I have created empty "sbr" grails application. Before changing it to the real grails application it would be good to cover some basic aspects and communication flows of the more or less each grails application. This way it will be more clear what is happening. On the picture below I tried to write main aspects and communication flows of the grails application at least as I see them. I don't claim it is correct. If you need completely correct picture and definitions please refer to the Grails documentation.

general_aspects_of_grails_application

Lets start from the top of the picture.

Probably as a first thing you want to display something to the end-user.

GSP stands for groovy server pages and is the view technology used in the grails. This means that front-end of the grails application is written in the GSP. To make GSP pages more readable and more scalable you can use TagLibs and Templates. As I like to write easily readable code, taglibs and templates are features of the grails that enables you to write readable GSP pages.

As the input into the GSP page you send a model. Just not to be confused, model is actually map of [key,value] pairs where key is the string and the value can be instance of any groovy or java class available on the classpath. Important part to remember is that value can be instance of any class - not only domain objects. I am making this clear because for the "long" time I was limiting data in the model to the instances of domain objects.

So when you are displaying GSP page, you are using gsp tags, custom taglibs, and templates. Data to be displayed on the page is contained in the model. Example of the map representing model can [bookToDisplay:book]. The bookToDisplay is the key (can be any string) while the book is instance of the groovy class. To e.g. display title of the book in the GSP page you would write ${bookToDisplay.title}.

Now when information is displayed there is big chance we want to send some data back to server and process it.

Controllers are groovy classes stored in the controllers folder. Each closure defined in the controller is considered as action and can be called from the GSP pages. So for example if you click the button on the GSP pages that is wired to some action in the controller, action in that controller will be called. Important thing to remember is that controllers are stateless. Controllers have access to the domain objects and to the services. This means, no business logic should be contained in the controller. Controller should use business logic available in the domain objects and services.

Data sent from the GSP page to the controller is available to the controller via params. params is actually variable containing all the request parameters. Thanks to the groovy it is injected into each controller so you have easy access to all request parameters.

So for example, if you have input field with the name bookTitle, content of the field is available to the controller via construct params.bookTitle.

Now when we got down from the GSP to the controller and we have all necessary data available via params variable the rest is easy.

From the controller class it is very easy to use domain objects and/or services. And when you are on the level of the domain object or service you are working with normal groovy and/or java.

Services are groovy classes stored within services folder. Services provide transactional context for database operations and can by dynamically injected into controller and domain classes. Business logic that is not directly connected with concrete domain object should be put into service. Additionally you can use service to surround transactional behavior around multiple calls on the domain objects.

Domain Objects represents domain of the problem you are solving. They are stored in the domain folder. They are famous because they represent GORM classes, grails solution for persistence. Domain classes are mapped to the databases and the database is automatically generated or updated for you according to relationships between domain objects.

And of course the whole grails framework is built on the top of the hibernate and spring. This ensures stability and scalability of the grails applications.

Summary

When you click on some button or link in the GSP page you are forwarded to the corresponding action in the controller. After performing basic validation in the controller you can use domain objects and services to perform application logic. After all necessary actions are performed you are creating model that is sent and displayed on the GSP page.

In the next post I will return back to the "sbr" project. I will create home page and explain basic layouting options.

P.S. Don't forget to write some review or post summary on the software books reviews.

Tuesday, April 7, 2009

Eager fetching and searchable plugin in Grails

What came as surprise to me is that eager fetching even when specified on the level of the domain class does not work with the searchable plugin. I hit this problem while working on the software books reviews and statement and description why I found on one blog post. Unfortunately I cannot find the mentioned post again so I am not able to give a credit to the original author by linking to his/her post.

So for example lets have Book domain class that among other properties has publisher property specified like this:

class Book {
static searchable = true
Publisher publisher

static fetchMode = [publisher:"eager"]
}

Using searchable plugin you can search for the books like this:

 Map<String,String> options = new HashMap<String, String>()
if (params.offset) {
options.put('offset',new Long(params.offset))
}
options.put('escape', true)
options.put('max',10)
def searchResult = Book.search(params.searchTerm, options)

After executing given query searchResult.result will be populated with the list of found Book instances. And in this moment you hope that everything is fine. You send the found list of books to the view but to your surprise you see that publisher is not displayed for each of the book. You check if the book has publisher and it is in the database. The reason for the missing publisher is that the domain classes are created differently when loaded from the lucene index file.

To resolve this problem I have actually reloaded all the found books from the database. This way all the books are of course loaded as specified in the domain object. So code for searching looks like this:

Map<String,String> options = new HashMap<String, String>()
if (params.offset) {
options.put('offset',new Long(params.offset))
}
options.put('escape', true)
options.put('max',10)
def searchResult = Book.search(params.searchTerm, options)

// create new results because those current one are actually not loaded eagery
def newResults = new ArrayList()
searchResult.results.each {book ->
def bookToAdd = Book.get(book.id)
newResults.add(bookToAdd)
}

searchResult.results = newResults

So if you have integrated searching into your grails application and expects that some parts of the domain object are loaded eagerly you should probably use approach similar to this one.

P.S. Don't forget to write some review or post summary on the software books reviews.

Monday, April 6, 2009

Creating Grails Application

[From the series - creating software books reviews grails web application]

In this post just for the sake of completeness I will shortly describe how to create grails application. As in the series of the post I will more or less explain some aspects of programming in the Grails and partially recreate software books reviews site the project to create I will call sbr (short for software books reviews).

Note: I am currently using Grails 1.0.3 version.

Creating Grails application is very easy. Open some command line tool and execute the command:

grails create-app sbr

Now the folder named sbr is create and in this folder is new grails application.

Actually you are already able to start this web application by executing following command from the sbr folder:

grails run-app

To access the application in the browser enter: http://localhost:8080/sbr.

In the case you want to start application on another port you can do that using following command:

grails -Dserver.port=[port_number] run-app

And of course instead of the [port_number] you should enter number of the port on which you want to start web application.

When Grails application is started this way without any changes it is run using embedded Jetty web container and in-memory HSQLDB that is default Grails configuration. Later on I will explain how to change database and how to deploy to Tomcat.

Let me shortly explain folders of the grails application. The top level folders are displayed on the following screen shot:


grails_folder

Short explanation of generated folders is:

  • grails-app actually contains the main part of the grails application and will be explained separately
  • lib - contains all external dependencies to other java libraries and is by default empty
  • scripts - contains scripts and is by default empty
  • src - contains java and groovy source files and is by default empty
  • test - contains unit and integration tests and is by default empty
  • web-app - contains web application

The content of the grails-app folder is much more interesting because it contains the heart of your web application.


grails_app_folder

Names of the folders should be self descriptive enough but shortly:

  • conf - contains configuration of the application. From this folder you are able to configure different aspects of the grails application like: datasources, hibernate, spring, bootstrap and so on. In the later post I will explain at least some of those files.
  • controllers - contains controllers of the web application. Controllers are accessed from the views and of course represents C of the MVC pattern
  • domain - is folder that will contain all application domain objects. All application domain objects are persisted while the database schema is automatically generated using hibernate. All domain objects are thanks to Groovy by default enriched with number of useful methods.
  • i18n - is folder used to localized application
  • services - are different services that can be used by controllers or domain objects. They are automatically initialized and inserted using spring. They also provide transactional behavior.
  • taglib - folder that will contain custom tag libraries. Tag libraries are excellent feature of the grails that enables you to modularize front-end of the grails application. I am using them heavily.
  • views - is the folder that contains html and gsp files of the application. In the one word it contains "pages" of the web application.

And although not directly visible in the folder list, another important part for modularizing front-end of the grails application are templates. I will explain how templates can be used in the later posts.

In the next post I will shortly explain general aspects of the grails application, or namely all folders of the grails-app folder. So stay tuned :)

P.S. Don't forget to write some review or post summary on the software books reviews.

Series from the Developing Software Books Reviews

As I have already promised few days ago, I will write a number of posts explaining my experience gained during development of the software books reviews and partially grails tutorials site. Actually during the series of the posts I will more or less recreate software books reviews grails application. Just for the convenience, I will regularly update this post so it points to all posts from this series. So if you will like those posts come and visit this post from time to time.

So the list of the posts so far is:

Friday, April 3, 2009

Developing Web Applications with Grails

As I have recently released software books reviews I believe I have finally improved my skills also when working with pure front end (html, css) of web application. As I also mentioned in the previous post, I plan to write series of posts explaining development work on the 'software books reviews' site. I hope my experience will be useful for additional developers. As I am coming from back-end Java development, while developing my first Grails applications the hardest part for me was HTML, css, layout... I believe posts I will write will also help other back-end developers to write web sites using Grails.

I plan to write at least one post per week (till there is enough to write). I do not plan to cover basics like how to install grails or how to generate applications. There are already lot of articles covering these topics. But I hope posts will be clear enough so even beginners will be able to understand them.

Lets go to the first topic :)

So if you are reading this probably you want to write web applications using Grails. Let us see what topics one needs to cover to write web application:

  • It is necessary to create nice front-end (HTML, css styles, layouts)  (disclaimer: I don't claim that I am making nice front-ends :) )
  • It is necessary to implement business logic - behavior of the application
  • Probably it is necessary to include security into application
  • It is necessary to store data into database
  • And very often it is necessary to provide some additional features that are not directly connected with business logic but in these days are more or less "must have". Obvious feature are RSS feeds.

Grails can help us with most of these requirements while hiding most of the complexity from us. Thanks to grails the most complex things are hidden from us but we still have access to them.

Domain objects - domain objects of course describe domain of our business logic. They are automatically persisted and loaded from the database. This means that database schema generation is something we don't need to think about most of the time.

Services - provide functionality that is not part of the domain objects. In services you include functions that are not naturally fitting into domain objects. Further on services handle transactional behavior for you. You can configure them with simple flag.

Plugins - Grails has excellent system of plugins. As we don't want to reinvent wheel we can reuse what is already implemented for us. Plugins will provide us with security, nice front-end components, RSS generation....

Sitemesh - is decorator engine supported by Grails to support view layouts. I am using it only on the basic level but even in such scenario it is very useful.

So these are some basics that will help us to make developing web application fun and fast.  Using those features we will go through example implementation of the software books reviews.

In the next post I will describe how I start project, and at least what are my basic first steps. I don't claim that it is the correct way but for me it turned out to be good.

Some advertisement: if you are reading software related books please be so kind to post review or link to review on the software books reviews.