Page 1

Agile Web Development with Groovy and Grails

Lee Chuk Munn Staff Engineer

1


Groovy Overview

2


What is Groovy? •A dynamic language build on top of the JVM •Java like syntax >Easier learning curve for Java developers •Seamless integration with Java >Groovy applications can instantiate Java objects >Java applications can instantiate Groovy objects >Java applications can control Groovy environment via JSR223 and vice versa

3


A Valid Java Program import java.util.*; public class Erase { private List<String> filterLongerThan(List<String> strings, int length) { List<String> result = new ArrayList<String>(); for (String n: strings) if (n.length() <= length) result.add(n); return (result); } public static void main(String[] args) { List<String> names = new ArrayList<String>(); names.add("Ted"); names.add("Fred"); names.add("Ned"); System.out.println(names); Erase e = new Erase(); List shortNames = e.filterLongerThan(names, 3); System.out.println(shortNames); }

} 4


A Valid Groovy Program import java.util.*; public class Erase { private List<String> filterLongerThan(List<String> strings, int length) { List<String> result = new ArrayList<String>(); for (String n: strings) if (n.length() <= length) result.add(n); return (result); } public static void main(String[] args) { List<String> names = new ArrayList<String>(); names.add("Ted"); names.add("Fred"); names.add("Ned"); System.out.println(names); Erase e = new Erase(); List shortNames = e.filterLongerThan(names, 3); System.out.println(shortNames); }

} 5


A Valid Groovy Program import java.util.*; public class Erase { private List<String> filterLongerThan(List<String> strings, int length) { List<String> result = new ArrayList<String>(); for (String n: strings) if (n.length() <= length) result.add(n); return (result); } public static void main(String[] args) { List<String> names = new ArrayList<String>(); names.add("Ted"); names.add("Fred"); names.add("Ned"); System.out.println(names); Erase e = new Erase(); List shortNames = e.filterLongerThan(names, 3); System.out.println(shortNames); }

} 6


The Groovy Way def names = ["Ted", "Fred", "Jed", "Ned"] println names def shortNames = names.findAll { it.size() <= 3 } print shortNames

7


Grails Overview

8


What is Grails? • An open source Groovy MVC framework for web

applications • Design principles

>CoC – Convention over configuration >DRY – Don't repeat yourself

• Similar to RoR but with tighter integration to the

Java platform

>Courtesy of Groovy >Protect your investment

9


Why Grails? • ORM layer can be overly difficult to master and

get right

>JPA is a step in the right direction by using annotations and

POJO

• Numerous layers and configuration files can lead

to chaos

>Adoption of frameworks a good thing, but too often lead to

configuration file hell

• Ugly JSPs with scriplets and complex JSP

custom tags • Grails addresses all these problems without compromising their benefits • Lots of plugins

10


Grails Technology Stack

11


How To Get Started • Download Groovy >http://groovy.codehaus.org • Download Grails >http://grails.org • Set GROOVY_HOME, GRAILS_HOME • Add their bins to PATH >$GROOVY_HOME/bin:$GRAILS_HOME/bin:$PATH • Now you are ready to go

12


Using Grails

13


grails create-app â&#x20AC;˘ Will be prompted for the name of the application â&#x20AC;˘ Will generate a directory structure for >Grails source >Additional libraries >Configurations >web-app

14


Grails Directory Structure Application name

Grail source

Additional JARs Web application

15


grails run-app â&#x20AC;˘ Will start the embedded web server and run the

application â&#x20AC;˘ Defaults to

> http://localhost:8080/<app_name>

16


grails create-domain-class PurchaseOrder

Customer String name String email PurchaseOrder po

1

M

Customer cust Date orderDate String items int quantity

• Classes are tables • Members are table fields • Define relationships between objects with

specific field names

>hasMany, belongsTo 17


Grail use URI for Object Identification

http://<server>/orderentry/customer/12345 Application

Controller

Id

http://<server>/orderentry/customer/list Application

Controller

Action

18


grails create-controller • Generate a controller class • Controller contains a series of actions >Default action is index Controller class
CustomerController
{



 def
index
=
{
} def
list
=
{ if(!params.max)
params.max
=
10 [
customerList:
Customer.list(
params
)
] } def
show
=
{...

Actions 19


Sequence of Actions http://server:8080/orderentry/customer

'customer' controller

'index' action

'index' view

If action did not specify view, then the default view will be the same as action's name 20


Scaffolding • Generates a set of default actions and views for

the corresponding domain class

>Actions are CRUD >Create, Read, Update, Delete

• Enable scaffolding by setting the scaffold

property to true in controller class def
scaffold
=
true

21


grails generate-all â&#x20AC;˘ Nobody uses scaffold's view without customizing

it â&#x20AC;˘ Get Grails to generate scaffold's dynamically generated view >Now customize the view

22


Object Constraints • Can specify constraints on domain objects

static
constraints
=
{
…
} • Many predefined constraint type >Blank, email, inList, matches, max, min, etc.

static
constraints
=
{ email(email:
true,
nullable:
true) } • Create your constrain validator easily

customer(validator:{it.length()>0}) 23


Persistence Methods • GROM automatically provides persistence

methods for your object

>save(), get(), delete()

• Automatically generates addToXXXX() for object

relationships

>Where XXXX is the property's name >Automatically configures the relationship

def
customer
=
new
Customer(name:'Fred') def
po
=
new
PurchaseOrder (orderDate:
new
Date(),
item:
'Apple',
quantity:
5) customer.addToPo(order) customer.save() 24


Queries • Dynamically generated queries >list(), findBy(), findAllBy(),
findWhere() • Manual queries (not discusses here) >Criteria, Hibernate QL

PurchaseOrder.list() Customer.findByName('Chuk') PurchaseORder.findByOrderDateGreaterThan( new
Date()
-
7) Customer.findByNameAndEmail('chuk', 'cmlee@gmail.com') 25


grails console â&#x20AC;˘ Test your domain object interactively â&#x20AC;˘ Compiles all GROM classes automatically

26


Task – Create a Search Function • Create a search function to list all orders from a

particular customer • Use the following format

>http://<server>/orderentry/search/<customer_name>

• Write as little code as possible >Reuse what we have • What we have to do >Write a search action >Define a custom URL format

27


URL Mappings • Default URL format http://server:8080/orderentry/customer/list Application

Controller

Action

• Defined in grails-app/conf/UrlMappings.groovy static
mappings
=
{ “/$controller/$action?/$id?”

• Custom URL mappings with constraints ”/customer/$id”(controller:”product”,
action:”show”)
{ constraints
{ id(validate:
{
Customer.exists(it)
}) }

28


General Approach http://server.com/orderlist/search/fred Request UrlMappings Forwards PurchaseOrderController search

Render to models

list.gsp 29


Summary â&#x20AC;˘ Groovy is a powerful dynamic language for the

JVM

>Provides agile development on the Java platform without

the impedance mismatch of other languages

â&#x20AC;˘ Grails is a full featured web platform >Lots of plugins for Grails >Based on and build on proven technology

30


n. co m

Lee Chuk Munn Staff Engineer chuk-munn.lee@sun.com

31


Taglibs • Encapsulate logic in a markup tag

Attribute name

Tag name

<g:loop
times=”3”> Hello
number
${it} </g:loop>

Tag body

• Taglibs separate view and logic >Difficult to implement custom taglib in Servlet/JSP 32


grails create-tag-lib • Adds email to product list >If the product list page is from a search

http://<server>/orderentry/search/fred <g:customer
email=”${email}”
/>

<a
href=”mailto:fred@mail.com”> Send
email </a> 33


Acknowledgement â&#x20AC;˘ Thanks to Guilaume Laforge of G2One for

allowing me to use and adapt some of his slides

34


Lee Chuk Munn Staff Engineer chuk-munn.lee@sun.com

35

agile groovy grails  

agile groovy grails

Read more
Read more
Similar to
Popular now
Just for you