Table Of ContentThe Definitive Guide to
Grails 2
■ ■ ■
Jeff Scott Brown
Graeme Rocher
Apress
The Definitive Guide to Grails 2
Copyright © 2013 by Jeff Scott Brown and Graeme Rocher
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is
concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction
on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic
adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Exempted
from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied
specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser
of the work. Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright
Law of the Publisher’s location, in its current version, and permission for use must always be obtained from Springer.
Permissions for use may be obtained through RightsLink at the Copyright Clearance Center. Violations are liable to
prosecution under the respective Copyright Law.
ISBN 978-1-4302-4377-9
ISBN 978-1-4302-4378-6(eBook)
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every
occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and
to the benefit of the trademark owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified
as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication, neither
the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be
made. The publisher makes no warranty, express or implied, with respect to the material contained herein.
President and Publisher: Paul Manning
Lead Editor: Douglas Pundick
Technical Reviewer: Graeme Rocher
Editorial Board: Steve Anglin, Ewan Buckingham, Gary Cornell, Louise Corrigan, Morgan Ertel, Jonathan Gennick,
Jonathan Hassell, Robert Hutchinson, Michelle Lowman, James Markham, Matthew Moodie, Jeff Olson, Jeffrey
Pepper, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Gwenan Spearing, Matt Wade, Tom Welsh
Coordinating Editor: Katie Sullivan
Copy Editor: Thomas McCarthy
Compositor: Bytheway Publishing Services
Indexer: SPi Global
Artist: SPi Global
Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor,
New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.
springeronline.com.
For information on translations, please e-mail rights@apress.com, or visit www.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions
and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing
web page at www.apress.com/bulk-sales.
Any source code or other supplementary materials referenced by the author in this text is available to readers at www.
apress.com. For detailed information about how to locate your book’s source code, go to www.apress.com/source-code.
To Mom.
Thanks for everything.
—Jeff Scott Brown
To Birjinia.
Thanks for being you. Maite zaitut.
—Graeme Rocher
Contents at a Glance
■ About the Author ................................................................................................................xiii
■ About the Technical Reviewer ...........................................................................................xiv
■ Acknowledgments ...............................................................................................................xv
■ Chapter 1: The Essence of Grails ..........................................................................................1
■ Chapter 2: Getting Started with Grails ................................................................................15
■ Chapter 3: Understanding Domain Classes ........................................................................41
■ Chapter 4: Understanding Controllers ................................................................................63
■ Chapter 5: Understanding Views ......................................................................................105
■ Chapter 6: Mapping URLs ..................................................................................................139
■ Chapter 7: Internationalization .........................................................................................155
■ Chapter 8: Ajax ..................................................................................................................169
■ Chapter 9: GORM ...............................................................................................................191
■ Chapter 10: Services .........................................................................................................233
■ Chapter 11: Integration and Dependency Management ..................................................249
■ Chapter 12: Plug-ins ..........................................................................................................293
■ Index ..................................................................................................................................335
iv
Contents
■ About the Author ................................................................................................................xiii
■ About the Technical Reviewer ...........................................................................................xiv
■ Acknowledgments ...............................................................................................................xv
■ Chapter 1: The Essence of Grails ..........................................................................................1
Simplicity and Power ..............................................................................................................1
Grails, the Platform .................................................................................................................2
Living in the Java Ecosystem .................................................................................................3
Installing and Configuring Grails ............................................................................................4
Creating Your First Application ...............................................................................................5
Step 1: Creating the Application .....................................................................................................................5
Step 2: Creating a Controller...........................................................................................................................6
Step 3: Printing a Message .............................................................................................................................8
Step 4: Testing the Code .................................................................................................................................8
Step 5: Running the Tests ...............................................................................................................................9
Step 6: Running the Application....................................................................................................................10
Grails Interactive Mode .........................................................................................................12
Summary ..............................................................................................................................13
■ Chapter 2: Getting Started with Grails ................................................................................15
What Is Scaffolding?.............................................................................................................15
Creating a Domain ................................................................................................................15
Introducing Dynamic Scaffolding .........................................................................................17
The Create Operation ....................................................................................................................................19
The Read Operation ......................................................................................................................................21
v
■ CONTENTS
The Update Operation ...................................................................................................................................23
The Delete Operation ....................................................................................................................................24
Static Scaffolding .................................................................................................................25
Generating a Controller .................................................................................................................................25
Generating the Views ....................................................................................................................................29
Being Environmentally Friendly ............................................................................................31
Configuring Data Sources .....................................................................................................32
The DataSource.groovy File ..........................................................................................................................32
Configuring a MySQL Database ....................................................................................................................34
Configuring a JNDI Data Source ...................................................................................................................37
Supported Databases ...................................................................................................................................37
Deploying the Application .....................................................................................................38
Deployment with run-war .............................................................................................................................38
Deployment with a WAR file .........................................................................................................................39
Summary ..............................................................................................................................40
■ Chapter 3: Understanding Domain Classes ........................................................................41
Persisting Fields to the Database .........................................................................................41
Validating Domain Classes ...................................................................................................42
Using Custom Validators .......................................................................................................45
Understanding Transient Properties .....................................................................................45
Customizing Your Database Mapping ...................................................................................47
Building Relationships ..........................................................................................................49
Extending Classes with Inheritance .....................................................................................52
Embedding Objects ..............................................................................................................56
Testing Domain Classes .......................................................................................................58
Summary ..............................................................................................................................61
■ Chapter 4: Understanding Controllers ................................................................................63
Defining Controllers ..............................................................................................................63
Setting the Default Action .............................................................................................................................64
Logging .........................................................................................................................................................65
Logging Exceptions ......................................................................................................................................66
Accessing Request Attributes .......................................................................................................................66
Using Controller Scopes ...............................................................................................................................67
Understanding Flash Scope ..........................................................................................................................68
Accessing Request Parameters ....................................................................................................................70
vi
■ CONTENTS
Request Parameter Type Conversions ..........................................................................................................70
Rendering Text ..............................................................................................................................................72
Redirecting a Request ..................................................................................................................................73
Creating a Model ..................................................................................................................74
Rendering a View..................................................................................................................74
Finding the Default View ...............................................................................................................................75
Selecting a Custom View ..............................................................................................................................75
Rendering Templates ....................................................................................................................................75
Performing Data Binding ......................................................................................................76
Validating Incoming Data ..............................................................................................................................77
The Errors API and Controllers ......................................................................................................................77
Data Binding to Multiple Domain Objects .....................................................................................................78
Data Binding with the bindData Method .......................................................................................................79
Data Binding and Associations .....................................................................................................................79
The Bindable Constraint ...............................................................................................................................80
Working with Command Objects ..........................................................................................81
Defining Command Objects ..........................................................................................................................81
Using Command Objects ..............................................................................................................................82
Imposing HTTP Method Restrictions ....................................................................................83
Implementing an Imperative Solution ...........................................................................................................83
Taking Advantage of a Declarative Syntax ....................................................................................................84
Controller IO ..........................................................................................................................84
Handling File Uploads ...................................................................................................................................85
Reading the Request InputStream ................................................................................................................87
Writing a Binary Response ...........................................................................................................................87
Using Simple Interceptors ....................................................................................................88
Before Advice ................................................................................................................................................88
After Advice ..................................................................................................................................................89
Testing Controllers ................................................................................................................89
Controllers in Action .............................................................................................................92
Creating the gTunes Home Page...................................................................................................................92
Adding the User Domain Class .....................................................................................................................93
Adding a Login Form ....................................................................................................................................94
Implementing Registration ...........................................................................................................................96
Testing the Registration Code .......................................................................................................................99
Allowing Users to Log In .............................................................................................................................100
vii
■ CONTENTS
Testing the Login Process ...........................................................................................................................102
Summary ............................................................................................................................103
■ Chapter 5: Understanding Views ......................................................................................105
The Basics ..........................................................................................................................105
Understanding the Model ...........................................................................................................................106
Page Directives ...........................................................................................................................................107
Groovy Scriptlets ........................................................................................................................................107
GSP As GStrings ..........................................................................................................................................108
Built-in Grails Tags .............................................................................................................109
Setting Variables with Tags .........................................................................................................................109
Logical Tags ................................................................................................................................................109
Iterative Tags ..............................................................................................................................................110
Filtering and Iteration .................................................................................................................................111
Grails Dynamic Tags ...........................................................................................................113
Linking Tags ................................................................................................................................................114
The createLink and resource Tags .............................................................................................................................................115
Creating Forms and Fields ..........................................................................................................................116
Validation and Error Handling .....................................................................................................................121
Paginating Views ........................................................................................................................................122
Rendering GSP Templates...........................................................................................................................129
Creating Custom Tags .................................................................................................................................133
Creating a Tag Library .................................................................................................................................133
Custom Tag Basics......................................................................................................................................134
Testing a Custom Tag ..................................................................................................................................135
Summary ............................................................................................................................137
■ Chapter 6: Mapping URLs ..................................................................................................139
Understanding the Default URL Mapping ...........................................................................139
Including Static Text in a URL Mapping ..............................................................................140
Removing the Controller and Action Names from the URL .................................................140
Embedding Parameters in a Mapping ................................................................................141
Specifying Additional Parameters ......................................................................................143
Mapping to a View ..............................................................................................................143
Applying Constraints to URL Mappings ..............................................................................144
Including Wildcards in a Mapping...............................................................................................................145
Mapping to HTTP Request Methods ...................................................................................146
viii
■ CONTENTS
Mapping HTTP Response Codes .........................................................................................147
Taking Advantage of Reverse URL Mapping .......................................................................149
Named URL Mappings ........................................................................................................150
Defining Multiple URL Mappings Classes ...........................................................................151
Testing URL Mappings ........................................................................................................151
Summary ............................................................................................................................153
■ Chapter 7: Internationalization .........................................................................................155
Localizing Messages ..........................................................................................................155
Defining User Messages .............................................................................................................................155
Retrieving Message Values .........................................................................................................................157
Using URL Mappings for Internationalization .............................................................................................159
Using Parameterized Messages .........................................................................................160
Using java.text.MessageFormat .................................................................................................................160
Using the message Tag for Parameterized Messages ................................................................................161
Using Parameterized Messages for Validation ...................................................................162
Using messageSource ........................................................................................................165
Summary ............................................................................................................................167
■ Chapter 8: Ajax ..................................................................................................................169
Writing Ajax Code ...............................................................................................................169
Ajax in Action ......................................................................................................................169
Changing Your Ajax Provider ...............................................................................................171
Asynchronous Form Submission ........................................................................................172
Fun with Ajax Remote Linking ............................................................................................176
Adding Effects and Animation ............................................................................................184
Ajax-Enabled Form Fields...................................................................................................184
A Note on Ajax and Performance ........................................................................................188
Summary ............................................................................................................................188
■ Chapter 9: GORM ...............................................................................................................191
Persistence Basics .............................................................................................................191
Reading Objects ..........................................................................................................................................191
Listing, Sorting, and Counting .....................................................................................................................192
Saving, Updating, and Deleting ...................................................................................................................193
Associations .......................................................................................................................193
Relationship Management Methods ...........................................................................................................195
ix
■ CONTENTS
Transitive Persistence.................................................................................................................................195
Querying .............................................................................................................................196
Dynamic Finders .........................................................................................................................................196
Criteria Queries ...........................................................................................................................................198
Detached Criteria Queries ...........................................................................................................................202
Where Queries ............................................................................................................................................204
Query by Example .......................................................................................................................................209
HQL and SQL ...............................................................................................................................................209
Pagination ...................................................................................................................................................210
Configuring GORM ..............................................................................................................211
SQL Logging ...............................................................................................................................................211
Specifying a Custom Dialect .......................................................................................................................211
Other Hibernate Properties .........................................................................................................................212
The Semantics of GORM .....................................................................................................213
The Hibernate Session ................................................................................................................................213
Session Management and Flushing ............................................................................................................214
Obtaining the Session .................................................................................................................................215
Automatic Session Flushing .......................................................................................................................217
Transactions in GORM ........................................................................................................218
Detached Objects ...............................................................................................................220
The Persistence Life Cycle..........................................................................................................................221
Reattaching Detached Objects ...................................................................................................................221
Merging Changes ........................................................................................................................................223
Performance Tuning GORM .................................................................................................223
Eager vs. Lazy Associations ........................................................................................................................223
Batch Fetching ............................................................................................................................................226
Caching .......................................................................................................................................................227
Inheritance Strategies ................................................................................................................................229
Locking Strategies ..............................................................................................................229
Events Auto Time Stamping ................................................................................................231
Summary ............................................................................................................................232
■ Chapter 10: Services .........................................................................................................233
Understanding Service Basics ............................................................................................233
Services and Dependency Injection ...................................................................................234
Services in Action ...............................................................................................................235
x