PRESENTATION NAME

Download Report

Transcript PRESENTATION NAME

Introduction to Grails
by Jason McDonald
Java Users Group
Charleston, SC
June 25, 2008
Getting Started
Grails Basics
• Open Source
• Fully integrated with Java
• Groovy based
– Uses ANTLR to compile Groovy down to JVM
compatible bytecode
• Predicated on DRY principle
Underlying Technologies
•
•
•
•
•
•
Spring
Hibernate
Log4J
Junit
Quartz
Ant
Native Support
• HSQL
• MySQL
• Servlet container servers
– Jetty
– Tomcat
• AJAX and DHTML
– Dojo
– Prototype
– Yahoo!
Installation
•
•
•
•
Visit http://www.grails.org
Download and extract files
Create GRAILS_HOME environment variable
Add %GRAILS_HOME% to PATH environment
variable
• That’s it!
Grails Structure
Goovy Roots
•
•
•
•
•
•
•
Built on top of Java
Very similar syntax to java
Supports closures
Method returns can be slightly different
Case sensitive
No semi-colons needed
All classes end in .groovy
Conditional Environments
• Environment conditionals allow for variations
for a specific environment
– Database
– Initialization options
– More
• Three environment choices
– Development
– Testing
– Production
Script Based Code Generation
•
•
•
•
•
•
•
•
grails create-app [app name]
grails create-controller [controller name]
grails create-domain-class [class name]
grails create-service [service name]
grails create-unit-test [test name]
grails create-tag-lib [taglib name]
grails generate-all [class name]
grails generate-views [class name]
Building, Deploying, and Managing
•
•
•
•
•
•
•
grails clean
grails compile
grails console
grails doc
grails install-plugin
grails run-app
grails war
Important Files
• conf/DataSource.groovy
– Database connections
• conf/UrlMapping.groovy
– Routing
• conf/BootStrap.groovy
– Bootstrap file
• conf/Config.groovy
– Configurations (MIME mappings, more…)
Routing
• Route rules found in conf/UrlMapping.groovy
• Default route:
– application/controller/action/id[?params]
• Additional rules and restrictions can be
applied here
static mappings = {
"/product/$id?"(controller:"product"){
action = [GET:"show", PUT:"update",
DELETE:"delete", POST:"save"]
}
}
Databases
•
•
•
•
db configuration is in conf/DataSource.groovy
Can define at environment level or global level
Defaults to HSQL
Change to MySQL by:
– Dropping MySQL connector in the lib
– Changing DataSource.groovy to point at MySQL
Database Create Scheme
• dbCreate
– create-drop: creates tables on startup and drops
them on shutdown (DEV)
– create: creates tables on startup, deletes data on
shutdown (DEV, TEST)
– update – creates tables on startup, saves data
between restarts (TEST, PROD)
Grails MVC
MVC Framework
• Standard MVC implementation
• Sits on top of Spring MVC
– Reduces repetition of XML developers must
maintain
– Gives access to Spring DSL
Views
• Groovy Server Pages
– GSP extension
– Based on JSP pages
– Use
• Tag libraries
• Expressions
– similar to JSP EL but allows any expression within ${…}
Tag Libraries
•
Ordering and sorting
<g:sortableColumn property="releaseDate"
defaultOrder="desc"
title="Release Date"
titleKey="book.releaseDate" />
•
Form display
<g:form name="myForm"
action="myaction" id="1">
<g:passwordField name="myPasswordField“
value="${myPassword}" />
...
</g:form>
•
Formatting
<g:formatDate format="yyyy-MM-dd" date="${date}"/>
Custom Tag Libraries
•
•
•
Custom tag libraries are just groovy classes
that end with TagLib
Defaults to ‘g’ namespaces unless declared
Closure defines actual tag:
class FormattingTagLib {
static namespace = ‘fmt’
def dateFormat = { attrs ->
out << new java.text.SimpleDateFormat(
‘dd-MM-yyyy’).format(attrs.date)
}
}
<fmt:dateFormat date=‘${plan.effDate}’ />
Internationalization Support
• Based on Java i18n specifications
• Define properties files with language specific
entries
• Views can read i18n entries with a tag:
<g:message code=‘my.message’ args=‘${[‘One’, ‘Two’]}’/>
• Tag libraries can read entries with code:
g.message(code: ‘my.message’, args: [‘One’, ‘Two’])
Models
• POGOs
– Fields default to private
– Getters and setters provided automatically
– Must use wrapper objects – no primitives (1.5?)
– Field validation defined within:
static constraints = { date(nullable: false) }
• Can define custom messages using convention:
– className.propertyName.constraint = ‘’Err msg’’
– Automatic parameter mapping from view
book.properties = params
GORM
• Grails Object Relational Mapping
• Uses Hibernate3
• Dynamic methods for finding
Book.findByTitle(“The Dark Tower“)
Book.findByTitleAndAuthor(“The Dark Tower”, “Stephen King”
Book.findByTitle(“Christine”, [sort: ‘edition’, order: ‘asc’] )
• Relational mapping defined within
– One to many:
static hasMany = [ attendances:Attendance ]
– One to one:
Attendance attendance
GORM Caching
• Provides the same caching mechanisms that
can be found with Hibernate3
• Updates to DataSource.groovy can toggle
caching:
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = true
cache.provider_class =
‘org.hibernate.cache.EhCacheProvider’
}
Controllers
• House actions (methods) that respond to a
request
• Actions should map to GSP of same name
• index is the default action
• Can define the method each action is allowed:
def allowedMethods = [save:'POST', update:'POST']
– GET is the default
• Auto scaffolding sets up CRUD without files
def scaffold = true // In Controller class
Action Responses
• All actions respond in one of three ways:
– redirect
• Equivalent ot response.sendRedirect
• Can specify actions, controller, params, and more
– return
• Returns a value and calls a GSP of the same name
(action method ‘go’ will forward to go.gsp)
– render
• Calls a GSP by name
• Has the ability to pass arguments
Grails in Action
Web Services
• REST
– Provide RESTful mappings in UrlMappings.groovy
– Implement controller to accept and return
marshalled data
• SOAP
– Supported through XFire plug-in
– Simply expose a service:
static expose = [‘xfire’]
Testing
• Test framework based on JUnit
• Unit tests
– By convention uses mock objects
• Integration tests
– By convention use real objects
• Functional tests
– Supports Canoo WebTest integration
Running the Application
• Bootstrapping data
– Allows for initialization and test data
• Jetty Server
– Specify port and environment on command line
grails dev –Dserver.port=9999 run-app
• Tomcat
– As war
– Exploded
The Example
Requirements
• Application needs to:
– Store meetings, people, and which meetings each
person attends
• People should store first and last name
• Meetings should store date and subject of meeting
– Must have full CRUD capability
– Must be web based
– Must be able to integrate with Java environments
(to meet future integration needs)
Open Discussion