1 / 33

Java Users Group

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.

fauve
Download Presentation

Java Users Group

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Grails by Jason McDonald Java Users Group Charleston, SC June 25, 2008

  2. Getting Started

  3. Grails Basics • Open Source • Fully integrated with Java • Groovy based • Uses ANTLR to compile Groovy down to JVM compatible bytecode • Predicated on DRY principle

  4. Underlying Technologies Spring Hibernate Log4J Junit Quartz Ant

  5. Native Support • HSQL • MySQL • Servlet container servers • Jetty • Tomcat • AJAX and DHTML • Dojo • Prototype • Yahoo!

  6. 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!

  7. Grails Structure

  8. 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

  9. Conditional Environments • Environment conditionals allow for variations for a specific environment • Database • Initialization options • More • Three environment choices • Development • Testing • Production

  10. 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]

  11. Building, Deploying, and Managing grails clean grails compile grails console grails doc grails install-plugin grails run-app grails war

  12. Important Files • conf/DataSource.groovy • Database connections • conf/UrlMapping.groovy • Routing • conf/BootStrap.groovy • Bootstrap file • conf/Config.groovy • Configurations (MIME mappings, more…)

  13. Routing • Route rules found in conf/UrlMapping.groovy • Default route: • application/controller/action/id[?params] • Additional rules and restrictions can be applied herestatic mappings = { "/product/$id?"(controller:"product"){ action = [GET:"show", PUT:"update", DELETE:"delete", POST:"save"] } }

  14. 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

  15. 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)

  16. Grails MVC

  17. MVC Framework • Standard MVC implementation • Sits on top of Spring MVC • Reduces repetition of XML developers must maintain • Gives access to Spring DSL

  18. Views • Groovy Server Pages • GSP extension • Based on JSP pages • Use • Tag libraries • Expressions • similar to JSP EL but allows any expression within ${…}

  19. 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}"/>

  20. 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}’ />

  21. 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’])

  22. 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 viewbook.properties = params

  23. GORM • Grails Object Relational Mapping • Uses Hibernate3 • Dynamic methods for findingBook.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

  24. 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’}

  25. 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 filesdef scaffold = true // In Controller class

  26. 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

  27. Grails in Action

  28. 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’]

  29. 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

  30. Running the Application • Bootstrapping data • Allows for initialization and test data • Jetty Server • Specify port and environment on command linegrails dev –Dserver.port=9999 run-app • Tomcat • As war • Exploded

  31. The Example

  32. 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)

  33. Open Discussion

More Related