| <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" |
| "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> |
| <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> |
| <head> |
| <!-- Matomo --> |
| <script> |
| var _paq = window._paq = window._paq || []; |
| /* tracker methods like "setCustomDimension" should be called before "trackPageView" */ |
| _paq.push(["setDoNotTrack", true]); |
| _paq.push(["disableCookies"]); |
| _paq.push(['trackPageView']); |
| _paq.push(['enableLinkTracking']); |
| (function() { |
| var u="https://analytics.apache.org/"; |
| _paq.push(['setTrackerUrl', u+'matomo.php']); |
| _paq.push(['setSiteId', '79']); |
| var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; |
| g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s); |
| })(); |
| </script> |
| <!-- End Matomo Code --> |
| <title>The Grails Framework 3.0.0.RC2</title> |
| <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> |
| <link rel="stylesheet" href="../css/main.css" type="text/css" media="screen, print" title="Style" charset="utf-8" /> |
| <link rel="stylesheet" href="../css/pdf.css" type="text/css" media="print" title="PDF" charset="utf-8" /> |
| <script type="text/javascript"> |
| function addJsClass(el) { |
| var classes = document.body.className.split(" "); |
| classes.push("js"); |
| document.body.className = classes.join(" "); |
| } |
| </script> |
| </head> |
| |
| <body class="body" onload="addJsClass();"> |
| <div id="navigation"> |
| <ul> |
| <li> |
| <div id="nav-summary" onmouseover="toggleNavSummary(false)" onmouseout="toggleNavSummary(true)"> |
| <a href="../guide/index.html" class="button">Table of contents</a> |
| <div id="nav-summary-childs" style="display:none;"> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#introduction"><strong>1</strong><span>Introduction</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#gettingStarted"><strong>2</strong><span>Getting Started</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#upgrading"><strong>3</strong><span>Upgrading from Grails 2.x</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#conf"><strong>4</strong><span>Configuration</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#commandLine"><strong>5</strong><span>The Command Line</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#GORM"><strong>6</strong><span>Object Relational Mapping (GORM)</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#theWebLayer"><strong>7</strong><span>The Web Layer</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#traits"><strong>8</strong><span>Traits</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#webServices"><strong>9</strong><span>Web Services</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#async"><strong>10</strong><span>Asynchronous Programming</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#validation"><strong>11</strong><span>Validation</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#services"><strong>12</strong><span>The Service Layer</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#staticTypeCheckingAndCompilation"><strong>13</strong><span>Static Type Checking And Compilation</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#testing"><strong>14</strong><span>Testing</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#i18n"><strong>15</strong><span>Internationalization</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#security"><strong>16</strong><span>Security</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#plugins"><strong>17</strong><span>Plugins</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#spring"><strong>18</strong><span>Grails and Spring</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#hibernate"><strong>19</strong><span>Grails and Hibernate</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#scaffolding"><strong>20</strong><span>Scaffolding</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#deployment"><strong>21</strong><span>Deployment</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0"><a href="#contributing"><strong>22</strong><span>Contributing to Grails</span></a></div> |
| |
| </div> |
| </div> |
| </li> |
| <li class="separator selected"> |
| <a id="ref-button" onclick="localToggle(); return false;" href="#">Quick Reference</a> |
| </li> |
| </ul> |
| </div> |
| <div id="header"> |
| <div class="images clearfix"> |
| |
| <span id="logo"><a href="http://grails.org" target="_blank"><img alt="Grails Logo" title="The Grails Framework" src="../img/grails.png" border="0"/></a></span> |
| |
| |
| </div> |
| <p>See the light - agile, industrial strength, rapid web application development made easy</p> |
| </div> |
| |
| |
| <table id="colset" border="0" cellpadding="0" cellspacing="0"> |
| <tr> |
| <td id="col1"> |
| <div id="main" class="corner-all"> |
| |
| <span id='toggle-col1' class="toggle">(<a href="#" onclick="localToggle(); return false;">Quick Reference</a>)</span> |
| |
| <div class="project"> |
| <h1>The Grails Framework - Reference Documentation</h1> |
| <p><strong>Authors:</strong> Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari</p> |
| <p><strong>Version:</strong> 3.0.0.RC2</p> |
| |
| </div> |
| |
| |
| <div id="table-of-content"> |
| <h2>Table of Contents</h2> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#introduction"><strong>1</strong><span>Introduction</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#whatsNew"><strong>1.1</strong><span>What's new in Grails 3.0?</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#coreFeatures"><strong>1.1.1</strong><span>Core Features</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#webFeatures"><strong>1.1.2</strong><span>Web Features</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#developmentEnvironmentFeatures"><strong>1.1.3</strong><span>Development Environment Features</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#testingFeatures"><strong>1.1.4</strong><span>Testing Features</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#gettingStarted"><strong>2</strong><span>Getting Started</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#requirements"><strong>2.1</strong><span>Installation Requirements</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#downloadingAndInstalling"><strong>2.2</strong><span>Downloading and Installing</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#creatingAnApplication"><strong>2.3</strong><span>Creating an Application</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#aHelloWorldExample"><strong>2.4</strong><span>A Hello World Example</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#usingInteractiveMode"><strong>2.5</strong><span>Using Interactive Mode</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#ide"><strong>2.6</strong><span>Getting Set Up in an IDE</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#conventionOverConfiguration"><strong>2.7</strong><span>Convention over Configuration</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#runningAnApplication"><strong>2.8</strong><span>Running an Application</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#testingAnApplication"><strong>2.9</strong><span>Testing an Application</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#deployingAnApplication"><strong>2.10</strong><span>Deploying an Application</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#supportedJavaEEContainers"><strong>2.11</strong><span>Supported Java EE Containers</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#creatingArtefacts"><strong>2.12</strong><span>Creating Artefacts</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#generatingAnApplication"><strong>2.13</strong><span>Generating an Application</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#upgrading"><strong>3</strong><span>Upgrading from Grails 2.x</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#upgradingPlugins"><strong>3.1</strong><span>Upgrading Plugins</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#upgradingApps"><strong>3.2</strong><span>Upgrading Applications</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#conf"><strong>4</strong><span>Configuration</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#config"><strong>4.1</strong><span>Basic Configuration</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#builtInOptions"><strong>4.1.1</strong><span>Built in options</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#logging"><strong>4.1.2</strong><span>Logging</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#configGORM"><strong>4.1.3</strong><span>GORM</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#applicationClass"><strong>4.2</strong><span>The Application Class</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#executing"><strong>4.2.1</strong><span>Executing the Application Class</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#customizing"><strong>4.2.2</strong><span>Customizing the Application Class</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#applicationLifeCycle"><strong>4.2.3</strong><span>The Application LifeCycle</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#environments"><strong>4.3</strong><span>Environments</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#dataSource"><strong>4.4</strong><span>The DataSource</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#dataSourcesAndEnvironments"><strong>4.4.1</strong><span>DataSources and Environments</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#automaticDatabaseMigration"><strong>4.4.2</strong><span>Automatic Database Migration</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#transactionAwareDataSourceProxy"><strong>4.4.3</strong><span>Transaction-aware DataSource Proxy</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#databaseConsole"><strong>4.4.4</strong><span>Database Console</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#multipleDatasources"><strong>4.4.5</strong><span>Multiple Datasources</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#versioning"><strong>4.5</strong><span>Versioning</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#docengine"><strong>4.6</strong><span>Project Documentation</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#dependencyResolution"><strong>4.7</strong><span>Dependency Resolution</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#commandLine"><strong>5</strong><span>The Command Line</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#interactiveMode"><strong>5.1</strong><span>Interactive Mode</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#profiles"><strong>5.2</strong><span>The Command Line and Profiles</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#creatingCustomScripts"><strong>5.3</strong><span>Creating Custom Scripts</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#reusingGrailsScripts"><strong>5.4</strong><span>Re-using Grails scripts</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#gradleBuild"><strong>5.5</strong><span>Building with Gradle</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#gradleDependencies"><strong>5.5.1</strong><span>Defining Dependencies with Gradle</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#gradleTasks"><strong>5.5.2</strong><span>Working with Gradle Tasks</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#gradlePlugins"><strong>5.5.3</strong><span>Grails plugins for Gradle</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#GORM"><strong>6</strong><span>Object Relational Mapping (GORM)</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#quickStartGuide"><strong>6.1</strong><span>Quick Start Guide</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#basicCRUD"><strong>6.1.1</strong><span>Basic CRUD</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#domainClasses"><strong>6.2</strong><span>Domain Modelling in GORM</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#gormAssociation"><strong>6.2.1</strong><span>Association in GORM</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#manyToOneAndOneToOne"><strong>6.2.1.1</strong><span>Many-to-one and one-to-one</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#oneToMany"><strong>6.2.1.2</strong><span>One-to-many</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#manyToMany"><strong>6.2.1.3</strong><span>Many-to-many</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#basicCollectionTypes"><strong>6.2.1.4</strong><span>Basic Collection Types</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#gormComposition"><strong>6.2.2</strong><span>Composition in GORM</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#inheritanceInGORM"><strong>6.2.3</strong><span>Inheritance in GORM</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#sets,ListsAndMaps"><strong>6.2.4</strong><span>Sets, Lists and Maps</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#persistenceBasics"><strong>6.3</strong><span>Persistence Basics</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#savingAndUpdating"><strong>6.3.1</strong><span>Saving and Updating</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#deletingObjects"><strong>6.3.2</strong><span>Deleting Objects</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#cascades"><strong>6.3.3</strong><span>Understanding Cascading Updates and Deletes</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#fetching"><strong>6.3.4</strong><span>Eager and Lazy Fetching</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#locking"><strong>6.3.5</strong><span>Pessimistic and Optimistic Locking</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#modificationChecking"><strong>6.3.6</strong><span>Modification Checking</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#querying"><strong>6.4</strong><span>Querying with GORM</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#finders"><strong>6.4.1</strong><span>Dynamic Finders</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#whereQueries"><strong>6.4.2</strong><span>Where Queries</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#criteria"><strong>6.4.3</strong><span>Criteria</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#detachedCriteria"><strong>6.4.4</strong><span>Detached Criteria</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#hql"><strong>6.4.5</strong><span>Hibernate Query Language (HQL)</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#advancedGORMFeatures"><strong>6.5</strong><span>Advanced GORM Features</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#eventsAutoTimestamping"><strong>6.5.1</strong><span>Events and Auto Timestamping</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#ormdsl"><strong>6.5.2</strong><span>Custom ORM Mapping</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#tableAndColumnNames"><strong>6.5.2.1</strong><span>Table and Column Names</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#caching"><strong>6.5.2.2</strong><span>Caching Strategy</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#inheritanceStrategies"><strong>6.5.2.3</strong><span>Inheritance Strategies</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#identity"><strong>6.5.2.4</strong><span>Custom Database Identity</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#compositePrimaryKeys"><strong>6.5.2.5</strong><span>Composite Primary Keys</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#databaseIndices"><strong>6.5.2.6</strong><span>Database Indices</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#optimisticLockingAndVersioning"><strong>6.5.2.7</strong><span>Optimistic Locking and Versioning</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#fetchingDSL"><strong>6.5.2.8</strong><span>Eager and Lazy Fetching</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#customCascadeBehaviour"><strong>6.5.2.9</strong><span>Custom Cascade Behaviour</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#customHibernateTypes"><strong>6.5.2.10</strong><span>Custom Hibernate Types</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#derivedProperties"><strong>6.5.2.11</strong><span>Derived Properties</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#customNamingStrategy"><strong>6.5.2.12</strong><span>Custom Naming Strategy</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#defaultSortOrder"><strong>6.5.3</strong><span>Default Sort Order</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#programmaticTransactions"><strong>6.6</strong><span>Programmatic Transactions</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#gormConstraints"><strong>6.7</strong><span>GORM and Constraints</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#theWebLayer"><strong>7</strong><span>The Web Layer</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#controllers"><strong>7.1</strong><span>Controllers</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#understandingControllersAndActions"><strong>7.1.1</strong><span>Understanding Controllers and Actions</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#controllersAndScopes"><strong>7.1.2</strong><span>Controllers and Scopes</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#modelsAndViews"><strong>7.1.3</strong><span>Models and Views</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#redirectsAndChaining"><strong>7.1.4</strong><span>Redirects and Chaining</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#controllerInterceptors"><strong>7.1.5</strong><span>Controller Interceptors</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#dataBinding"><strong>7.1.6</strong><span>Data Binding</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#xmlAndJSON"><strong>7.1.7</strong><span>XML and JSON Responses</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#moreOnJSONBuilder"><strong>7.1.8</strong><span>More on JSONBuilder</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#uploadingFiles"><strong>7.1.9</strong><span>Uploading Files</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#commandObjects"><strong>7.1.10</strong><span>Command Objects</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#formtokens"><strong>7.1.11</strong><span>Handling Duplicate Form Submissions</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#typeConverters"><strong>7.1.12</strong><span>Simple Type Converters</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#controllerExceptionHandling"><strong>7.1.13</strong><span>Declarative Controller Exception Handling</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#gsp"><strong>7.2</strong><span>Groovy Server Pages</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#GSPBasics"><strong>7.2.1</strong><span>GSP Basics</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#variablesAndScopes"><strong>7.2.1.1</strong><span>Variables and Scopes</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#logicAndIteration"><strong>7.2.1.2</strong><span>Logic and Iteration</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#pageDirectives"><strong>7.2.1.3</strong><span>Page Directives</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#expressions"><strong>7.2.1.4</strong><span>Expressions</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#tags"><strong>7.2.2</strong><span>GSP Tags</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#tagVariablesAndScopes"><strong>7.2.2.1</strong><span>Variables and Scopes</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#tagLogicAndIteration"><strong>7.2.2.2</strong><span>Logic and Iteration</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#searchAndFiltering"><strong>7.2.2.3</strong><span>Search and Filtering</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#linksAndResources"><strong>7.2.2.4</strong><span>Links and Resources</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#formsAndFields"><strong>7.2.2.5</strong><span>Forms and Fields</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#tagsAsMethodCalls"><strong>7.2.2.6</strong><span>Tags as Method Calls</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#viewsAndTemplates"><strong>7.2.3</strong><span>Views and Templates</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#layouts"><strong>7.2.4</strong><span>Layouts with Sitemesh</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#resources"><strong>7.2.5</strong><span>Static Resources</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#sitemeshContentBlocks"><strong>7.2.6</strong><span>Sitemesh Content Blocks</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#makingChangesToADeployedApplication"><strong>7.2.7</strong><span>Making Changes to a Deployed Application</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#GSPDebugging"><strong>7.2.8</strong><span>GSP Debugging</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#taglibs"><strong>7.3</strong><span>Tag Libraries</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#taglibVariablesAndScopes"><strong>7.3.1</strong><span>Variables and Scopes</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#simpleTags"><strong>7.3.2</strong><span>Simple Tags</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#logicalTags"><strong>7.3.3</strong><span>Logical Tags</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#iterativeTags"><strong>7.3.4</strong><span>Iterative Tags</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#namespaces"><strong>7.3.5</strong><span>Tag Namespaces</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#usingJSPTagLibraries"><strong>7.3.6</strong><span>Using JSP Tag Libraries</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#tagReturnValue"><strong>7.3.7</strong><span>Tag return value</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#urlmappings"><strong>7.4</strong><span>URL Mappings</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#mappingToControllersAndActions"><strong>7.4.1</strong><span>Mapping to Controllers and Actions</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#restfulMappings"><strong>7.4.2</strong><span>Mapping to REST resources</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#redirectMappings"><strong>7.4.3</strong><span>Redirects In URL Mappings</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#embeddedVariables"><strong>7.4.4</strong><span>Embedded Variables</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#mappingToViews"><strong>7.4.5</strong><span>Mapping to Views</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#mappingToResponseCodes"><strong>7.4.6</strong><span>Mapping to Response Codes</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#mappingHTTP"><strong>7.4.7</strong><span>Mapping to HTTP methods</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#mappingWildcards"><strong>7.4.8</strong><span>Mapping Wildcards</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#automaticLinkRewriting"><strong>7.4.9</strong><span>Automatic Link Re-Writing</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#applyingConstraints"><strong>7.4.10</strong><span>Applying Constraints</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#namedMappings"><strong>7.4.11</strong><span>Named URL Mappings</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#customizingUrlFormat"><strong>7.4.12</strong><span>Customizing URL Formats</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#namespacedControllers"><strong>7.4.13</strong><span>Namespaced Controllers</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#interceptors"><strong>7.5</strong><span>Interceptors</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#definingInterceptors"><strong>7.5.1</strong><span>Defining Interceptors</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#interceptorMatching"><strong>7.5.2</strong><span>Matching Requests with Inteceptors</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#interceptorOrdering"><strong>7.5.3</strong><span>Ordering Interceptor Execution</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#contentNegotiation"><strong>7.6</strong><span>Content Negotiation</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#traits"><strong>8</strong><span>Traits</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#traitsprovided"><strong>8.1</strong><span>Traits Provided</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#example"><strong>8.1.1</strong><span>WebAttributes Trait Example</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#webServices"><strong>9</strong><span>Web Services</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#REST"><strong>9.1</strong><span>REST</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#domainResources"><strong>9.1.1</strong><span>Domain classes as REST resources</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#urlMappings"><strong>9.1.2</strong><span>Mapping to REST resources</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#linkingToResources"><strong>9.1.3</strong><span>Linking to REST resources</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#versioningResources"><strong>9.1.4</strong><span>Versioning REST resources</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#restfulControllers"><strong>9.1.5</strong><span>Implementing REST controllers</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#extendingRestfulController"><strong>9.1.5.1</strong><span>Extending the RestfulController super class</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#restControllersStepByStep"><strong>9.1.5.2</strong><span>Implementing REST Controllers Step by Step</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#generatingRestControllers"><strong>9.1.5.3</strong><span>Generating a REST controller using scaffolding</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#renderers"><strong>9.1.6</strong><span>Customizing Response Rendering</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#defaultRenderers"><strong>9.1.6.1</strong><span>Customizing the Default Renderers</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#objectMarshallers"><strong>9.1.6.2</strong><span>Registering Custom Objects Marshallers</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#namedObjectMarshallers"><strong>9.1.6.3</strong><span>Using Named Configurations for Object Marshallers</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#objectMarshallerInterface"><strong>9.1.6.4</strong><span>Implementing the ObjectMarshaller Interface</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#customRenderers"><strong>9.1.6.5</strong><span>Implementing a Custom Renderer</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#gspRenderers"><strong>9.1.6.6</strong><span>Using GSP to Customize Rendering</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#hypermedia"><strong>9.1.7</strong><span>Hypermedia as the Engine of Application State</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#hal"><strong>9.1.7.1</strong><span>HAL Support</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#atom"><strong>9.1.7.2</strong><span>Atom Support</span></a></div> |
| |
| <div class="toc-item" style="margin-left:30px"><a href="#vndError"><strong>9.1.7.3</strong><span>Vnd.Error Support</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#binding"><strong>9.1.8</strong><span>Customizing Binding of Resources</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#SOAP"><strong>9.2</strong><span>SOAP</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#RSSAndAtom"><strong>9.3</strong><span>RSS and Atom</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#async"><strong>10</strong><span>Asynchronous Programming</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#promises"><strong>10.1</strong><span>Promises</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#events"><strong>10.2</strong><span>Events</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#consuming"><strong>10.2.1</strong><span>Consuming Events</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#notifying"><strong>10.2.2</strong><span>Event Notification</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#asyncGorm"><strong>10.3</strong><span>Asynchronous GORM</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#asyncRequests"><strong>10.4</strong><span>Asynchronous Request Handling</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#asyncServletApi"><strong>10.5</strong><span>Servlet 3.0 Async</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#validation"><strong>11</strong><span>Validation</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#constraints"><strong>11.1</strong><span>Declaring Constraints</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#validatingConstraints"><strong>11.2</strong><span>Validating Constraints</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#sharingConstraints"><strong>11.3</strong><span>Sharing Constraints Between Classes</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#validationOnTheClient"><strong>11.4</strong><span>Validation on the Client</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#validationAndInternationalization"><strong>11.5</strong><span>Validation and Internationalization</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#validationNonDomainAndCommandObjectClasses"><strong>11.6</strong><span>Applying Validation to Other Classes</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#services"><strong>12</strong><span>The Service Layer</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#declarativeTransactions"><strong>12.1</strong><span>Declarative Transactions</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#transactionsRollbackAndTheSession"><strong>12.1.1</strong><span>Transactions Rollback and the Session</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#scopedServices"><strong>12.2</strong><span>Scoped Services</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#dependencyInjectionServices"><strong>12.3</strong><span>Dependency Injection and Services</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#usingServicesFromJava"><strong>12.4</strong><span>Using Services from Java</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#staticTypeCheckingAndCompilation"><strong>13</strong><span>Static Type Checking And Compilation</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#grailsCompileStatic"><strong>13.1</strong><span>The GrailsCompileStatic Annotation</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#grailsTypeChecked"><strong>13.2</strong><span>The GrailsTypeChecked Annotation</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#testing"><strong>14</strong><span>Testing</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#unitTesting"><strong>14.1</strong><span>Unit Testing</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#unitTestingControllers"><strong>14.1.1</strong><span>Unit Testing Controllers</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#unitTestingTagLibraries"><strong>14.1.2</strong><span>Unit Testing Tag Libraries</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#unitTestingDomains"><strong>14.1.3</strong><span>Unit Testing Domains</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#unitTestingFilters"><strong>14.1.4</strong><span>Unit Testing Filters</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#unitTestingURLMappings"><strong>14.1.5</strong><span>Unit Testing URL Mappings</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#mockingCollaborators"><strong>14.1.6</strong><span>Mocking Collaborators</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#mockingCodecs"><strong>14.1.7</strong><span>Mocking Codecs</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#unitTestMetaprogramming"><strong>14.1.8</strong><span>Unit Test Metaprogramming</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#integrationTesting"><strong>14.2</strong><span>Integration Testing</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#functionalTesting"><strong>14.3</strong><span>Functional Testing</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#i18n"><strong>15</strong><span>Internationalization</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#understandingMessageBundles"><strong>15.1</strong><span>Understanding Message Bundles</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#changingLocales"><strong>15.2</strong><span>Changing Locales</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#readingMessages"><strong>15.3</strong><span>Reading Messages</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#scaffoldingAndI18n"><strong>15.4</strong><span>Scaffolding and i18n</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#security"><strong>16</strong><span>Security</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#securingAgainstAttacks"><strong>16.1</strong><span>Securing Against Attacks</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#xssPrevention"><strong>16.2</strong><span>Cross Site Scripting (XSS) Prevention</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#codecs"><strong>16.3</strong><span>Encoding and Decoding Objects</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#authentication"><strong>16.4</strong><span>Authentication</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#securityPlugins"><strong>16.5</strong><span>Security Plugins</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#springSecurity"><strong>16.5.1</strong><span>Spring Security</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#shiro"><strong>16.5.2</strong><span>Shiro</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#plugins"><strong>17</strong><span>Plugins</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#creatingAndInstallingPlugins"><strong>17.1</strong><span>Creating and Installing Plugins</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#repositories"><strong>17.2</strong><span>Plugin Repositories</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#providingBasicArtefacts"><strong>17.3</strong><span>Providing Basic Artefacts</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#evaluatingConventions"><strong>17.4</strong><span>Evaluating Conventions</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#hookingIntoRuntimeConfiguration"><strong>17.5</strong><span>Hooking into Runtime Configuration</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#addingMethodsAtCompileTime"><strong>17.6</strong><span>Adding Methods at Compile Time</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#addingDynamicMethodsAtRuntime"><strong>17.7</strong><span>Adding Dynamic Methods at Runtime</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#participatingInAutoReloadEvents"><strong>17.8</strong><span>Participating in Auto Reload Events</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#understandingPluginLoadOrder"><strong>17.9</strong><span>Understanding Plugin Load Order</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#artefactApi"><strong>17.10</strong><span>The Artefact API</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#queryingArtefacts"><strong>17.10.1</strong><span>Asking About Available Artefacts</span></a></div> |
| |
| <div class="toc-item" style="margin-left:20px"><a href="#customArtefacts"><strong>17.10.2</strong><span>Adding Your Own Artefact Types</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#spring"><strong>18</strong><span>Grails and Spring</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#theUnderpinningsOfGrails"><strong>18.1</strong><span>The Underpinnings of Grails</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#springdslAdditional"><strong>18.2</strong><span>Configuring Additional Beans</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#springdsl"><strong>18.3</strong><span>Runtime Spring with the Beans DSL</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#theBeanBuilderDSLExplained"><strong>18.4</strong><span>The BeanBuilder DSL Explained</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#propertyPlaceholderConfiguration"><strong>18.5</strong><span>Property Placeholder Configuration</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#propertyOverrideConfiguration"><strong>18.6</strong><span>Property Override Configuration</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#hibernate"><strong>19</strong><span>Grails and Hibernate</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#usingHibernateXMLMappingFiles"><strong>19.1</strong><span>Using Hibernate XML Mapping Files</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#mappingWithHibernateAnnotations"><strong>19.2</strong><span>Mapping with Hibernate Annotations</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#addingConstraints"><strong>19.3</strong><span>Adding Constraints</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#scaffolding"><strong>20</strong><span>Scaffolding</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#deployment"><strong>21</strong><span>Deployment</span></a></div> |
| |
| <div class="toc-item" style="margin-left:0px"><a href="#contributing"><strong>22</strong><span>Contributing to Grails</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#issues"><strong>22.1</strong><span>Report Issues in JIRA</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#build"><strong>22.2</strong><span>Build From Source and Run Tests</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#patchesCore"><strong>22.3</strong><span>Submit Patches to Grails Core</span></a></div> |
| |
| <div class="toc-item" style="margin-left:10px"><a href="#patchesDoc"><strong>22.4</strong><span>Submit Patches to Grails Documentation</span></a></div> |
| |
| <div style="clear:both" ></div> |
| </div> |
| |
| |
| <a name="1. Introduction"><!-- Legacy link --></a> |
| <h1 id="introduction">1 Introduction</h1> |
| Java web development as it stands today is dramatically more complicated than it needs to be. Most modern web frameworks in the Java space are over complicated and don't embrace the Don't Repeat Yourself (DRY) principles.<p class="paragraph"/>Dynamic frameworks like Rails, Django and TurboGears helped pave the way to a more modern way of thinking about web applications. Grails builds on these concepts and dramatically reduces the complexity of building web applications on the Java platform. What makes it different, however, is that it does so by building on already established Java technologies like Spring and Hibernate.<p class="paragraph"/>Grails is a full stack framework and attempts to solve as many pieces of the web development puzzle through the core technology and its associated plugins. Included out the box are things like: |
| <ul class="star"> |
| <li>An easy to use Object Relational Mapping (ORM) layer built on <a href="http://www.hibernate.org" target="blank">Hibernate</a></li> |
| <li>An expressive view technology called Groovy Server Pages (GSP)</li> |
| <li>A controller layer built on <a href="http://www.spring.io" target="blank">Spring</a> MVC</li> |
| <li>An interactive command line environment and build system based on <a href="http://gradle.org" target="blank">Gradle</a></li> |
| <li>An embedded <a href="http://tomcat.apache.org" target="blank">Tomcat</a> container which is configured for on the fly reloading</li> |
| <li>Dependency injection with the inbuilt Spring container</li> |
| <li>Support for internationalization (i18n) built on Spring's core MessageSource concept</li> |
| <li>A transactional service layer built on Spring's transaction abstraction</li> |
| </ul><p class="paragraph"/>All of these are made easy to use through the power of the <a href="http://groovy-lang.org" target="blank">Groovy</a> language and the extensive use of Domain Specific Languages (DSLs)<p class="paragraph"/>This documentation will take you through getting started with Grails and building web applications with the Grails framework. |
| |
| <a name="1.1 What's new in Grails 2.0?"><!-- Legacy link --></a> |
| <h2 id="whatsNew">1.1 What's new in Grails 3.0?</h2> |
| This section covers the new features that are present in 3.0 and is broken down into sections covering the build system, core APIs, the web tier, persistence enhancements and improvements in testing. Note there are many more small enhancements and improvements, these sections just cover some of the highlights.<p class="paragraph"/> |
| |
| <a name="1.1.2 Core Features"><!-- Legacy link --></a> |
| <h2 id="coreFeatures">1.1.1 Core Features</h2> |
| <h4>Groovy 2.4</h4><p class="paragraph"/>Grails 3.0 comes with Groovy 2.4 which includes many new features and enhancements.<p class="paragraph"/>For more information on Groovy 2.4, see the (TBD).<p class="paragraph"/><h4>Spring 4.1 and Spring Boot 1.2</h4><p class="paragraph"/>Grails 3.0 comes with Spring 4.1 which includes many new features and enhancements. See the (TBD).<p class="paragraph"/>In addition, Grails 3.0 is built on <a href="http://projects.spring.io/spring-boot/" target="blank">Spring Boot 1.2</a> which provides the ability to produce runnable JAR files that can embed Tomcat, Jetty or Undertow containers.<p class="paragraph"/><h4>Gradle Build System</h4><p class="paragraph"/>Grails 3.0 deprecates the older Gant-based build system in favour of a new <a href="http://gradle.org" target="blank">Gradle-based</a> build that integrates closely with the <a href="http://plugins.gradle.org" target="blank">Gradle plugin ecosystem</a>.<p class="paragraph"/>See the new section on the new <a href="../guide/single.html#gradleBuild" class="guide">Gradle build</a> for more information.<p class="paragraph"/><h4>Application Profiles</h4><p class="paragraph"/>Grails 3.0 supports the notion of application profiles via a new <a href="https://github.com/grails/grails-profile-repository" target="blank">profile repository</a>. A profile encapsulates an application structure, set of commands, plugins and capabilities. For example the "web" profile allows construction on web applications deployable to a Servlet container. In the future more profiles will be developed targeting different environments.<p class="paragraph"/>See the new section on <a href="../guide/single.html#profiles" class="guide">Profiles</a> for more information.<p class="paragraph"/><h4>Redesigned API based on Traits</h4><p class="paragraph"/>The Grails API has been redesigned so that public API is correctly populated under the <code>grails.</code> package whilst private / internal API that is subject to change can be found in the <code>org.grails.</code> package. The core API has also been rewritten and based around the <a href="http://groovy-lang.org/objectorientation.html#_traits" target="blank">Groovy Traits</a>.<p class="paragraph"/>See the new documentation on Grails 3.0's <a href="../guide/single.html#traits" class="guide">core traits</a> for more information. |
| |
| |
| <a name="1.1.3 Web Features"><!-- Legacy link --></a> |
| <h2 id="webFeatures">1.1.2 Web Features</h2> |
| <h4>New Interceptors API</h4><p class="paragraph"/>In previous versions of Grails, filters were used to define logic that intercepts controller action execution.<p class="paragraph"/>As of Grails 3.0, this API is deprecated and has been replaced by the new <a href="../guide/single.html#interceptors" class="guide">Interceptor API</a>. An example interceptor can be seen below:<p class="paragraph"/><div class="code"><pre>class MyInterceptor {<p class="paragraph"/> <span class="java-object">boolean</span> before() { <span class="java-keyword">true</span> }<p class="paragraph"/> <span class="java-object">boolean</span> after() { <span class="java-keyword">true</span> }<p class="paragraph"/> void afterView() { |
| // no-op |
| }<p class="paragraph"/>}</pre></div> |
| |
| |
| <a name="1.1.1 Development Environment Features"><!-- Legacy link --></a> |
| <h2 id="developmentEnvironmentFeatures">1.1.3 Development Environment Features</h2> |
| <h4>New Shell and Code Generation API</h4><p class="paragraph"/>Replacing Gant, Grails 3.0 features a new interactive command line shell that integrates closely with Gradle and provides APIs for writing scripts that interact with Gradle and perform code generation.<p class="paragraph"/>The new shell integrates closely with the concept of application profiles with each profile capable defining <a href="https://github.com/grails/grails-profile-repository/tree/master/profiles/web/commands" target="blank">profile specific commands</a>. As with previous versions of Grails, plugins can define new shell commands that can invoke Gradle or perform code generation and project automation tasks.<p class="paragraph"/>See the new guide on <a href="../guide/single.html#creatingCustomScripts" class="guide">Creating Custom Scripts</a> for more information.<p class="paragraph"/><h4>Enhanced IDE Integration</h4><p class="paragraph"/>Since Grails 3.0 is built on Gradle, you can now import a Grails project using IntelliJ community edition or GGTS's Gradle tooling support without the need for Grails specific tooling. Grails 3.0 plugins are published as simple JAR files greatly reducing the need for additional IDE support specific to Grails.<p class="paragraph"/><h4>Application Main Class</h4><p class="paragraph"/>Each new Grails 3.0 project features an <code>Application</code> class that has a traditional <code>static void main</code> signature, meaning to run or debug a Grails 3.0 application from an IDE like IntelliJ or GGTS you can simply right-click on the <code>Application</code> class and execute to start your Grails application. All Grails 3.0 tests can also just be run from the IDE directly without needing to resort to the command line (even integration / functional tests!). |
| |
| |
| <a name="1.1.5 Testing Features"><!-- Legacy link --></a> |
| <h2 id="testingFeatures">1.1.4 Testing Features</h2> |
| <h4>Integration and Geb Functional Tests</h4><p class="paragraph"/>Grails 3.0 supports built in support for Spock/Geb functional tests using the <a href="../ref/Command Line/create-functional-test.html" class="commandLine">create-functional-test</a> command. Functional tests are based on Spring Boot's test running mechanism and load the application just once for an entire suite of tests. The tests can be run from and IDE and don't require the command line.<p class="paragraph"/><h4>Gradle Test Running</h4><p class="paragraph"/>Since Grails 3.0 is built on Gradle the test execution configuration is much more flexible and can easily configured to execute in parallel. |
| |
| <a name="2. Getting Started"><!-- Legacy link --></a> |
| <h1 id="gettingStarted">2 Getting Started</h1> |
| |
| |
| |
| <h2 id="requirements">2.1 Installation Requirements</h2> |
| Before installing Grails 3.0 you will need as a minimum a Java Development Kit (JDK) installed version 1.7 or above. Download the appropriate JDK for your operating system, run the installer, and then set up an environment variable called <code>JAVA_HOME</code> pointing to the location of this installation.<p class="paragraph"/>To automate the installation of Grails we recommend the <a href="http://gvmtool.net" target="blank">GVM tool</a> which greatly simplifies installing and managing multiple Grails versions.<p class="paragraph"/>For manual installation, we recommend the video installation guides from <a href="http://www.grailsexample.net/" target="blank">grailsexample.net</a>: |
| <ul class="star"> |
| <li><a href="http://www.grailsexample.net/installing-a-grails-development-environment-on-windows/" target="blank">Windows</a></li> |
| <li><a href="http://www.grailsexample.net/installing-a-grails-development-environment-on-linux/" target="blank">Linux</a></li> |
| <li><a href="http://www.grailsexample.net/installing-a-grails-development-environment-on-os-x/" target="blank">Mac OS X</a></li> |
| </ul><p class="paragraph"/>These will show you how to install Grails too, not just the JDK.<p class="paragraph"/><blockquote class="note"> |
| A JDK is required in your Grails development environment. A JRE is not sufficient. |
| </blockquote><p class="paragraph"/>On some platforms (for example OS X) the Java installation is automatically detected. However in many cases you will want to manually configure the location of Java. For example:<p class="paragraph"/><div class="code"><pre>export JAVA_HOME=/Library/Java/Home |
| export PATH=<span class="java-quote">"$PATH:$JAVA_HOME/bin"</span></pre></div><p class="paragraph"/>if you're using bash or another variant of the Bourne Shell. |
| |
| |
| <a name="2.1 Downloading and Installing"><!-- Legacy link --></a> |
| <h2 id="downloadingAndInstalling">2.2 Downloading and Installing</h2> |
| The first step to getting up and running with Grails is to install the distribution.<p class="paragraph"/>The best way to install Grails on *nix systems is with the <a href="http://gvmtool.net" target="blank">GVM tool</a> which greatly simplifies installing and managing multiple Grails versions.<p class="paragraph"/>For manual installation follow these steps: |
| <ul class="star"> |
| <li><a href="http://grails.org/Download" target="blank">Download</a> a binary distribution of Grails and extract the resulting zip file to a location of your choice</li> |
| <li>Set the GRAILS_HOME environment variable to the location where you extracted the zip</li> |
| <ul class="star"> |
| <li>On Unix/Linux based systems this is typically a matter of adding something like the following <code>export GRAILS_HOME=/path/to/grails</code> to your profile</li> |
| <li>On Windows this is typically a matter of setting an environment variable under <code>My Computer/Advanced/Environment Variables</code></li> |
| </ul> |
| <li>Then add the <code>bin</code> directory to your <code>PATH</code> variable:</li> |
| <ul class="star"> |
| <li>On Unix/Linux based systems this can be done by adding <code>export PATH="$PATH:$GRAILS_HOME/bin"</code> to your profile</li> |
| <li>On Windows this is done by modifying the <code>Path</code> environment variable under <code>My Computer/Advanced/Environment Variables</code></li> |
| </ul></ul><p class="paragraph"/>If Grails is working correctly you should now be able to type <code>grails -version</code> in the terminal window and see output similar to this:<p class="paragraph"/><pre class="bq"><code> |
| Grails version: 3.0.0</code></pre><p class="paragraph"/> |
| |
| <a name="2.4 Creating an Application"><!-- Legacy link --></a> |
| <h2 id="creatingAnApplication">2.3 Creating an Application</h2> |
| To create a Grails application you first need to familiarize yourself with the usage of the <code>grails</code> command which is used in the following manner:<p class="paragraph"/><div class="code"><pre>grails [command name]</pre></div><p class="paragraph"/>Run <a href="../ref/Command Line/create-app.html" class="commandLine">create-app</a> to create an application:<p class="paragraph"/><pre class="bq"><code> |
| grails create-app helloworld</code></pre><p class="paragraph"/>This will create a new directory inside the current one that contains the project. Navigate to this directory in your console:<p class="paragraph"/><div class="code"><pre>cd helloworld</pre></div><p class="paragraph"/> |
| |
| <a name="2.5 A Hello World Example"><!-- Legacy link --></a> |
| <h2 id="aHelloWorldExample">2.4 A Hello World Example</h2> |
| Let's now take the new project and turn it into the classic "Hello world!" example. First, change into the "helloworld" directory you just created and start the Grails interactive console:<p class="paragraph"/><pre class="bq"><code> |
| $ cd helloworld |
| $ grails</code></pre><p class="paragraph"/>You should see a prompt that looks like this:<p class="paragraph"/><img border="0" class="center" src="../img/interactive-helloworld.png"></img><p class="paragraph"/>What we want is a simple page that just prints the message "Hello World!" to the browser. In Grails, whenever you want a new page you just create a new controller action for it. Since we don't yet have a controller, let's create one now with the <a href="../ref/Command Line/create-controller.html" class="commandLine">create-controller</a> command:<p class="paragraph"/><pre class="bq"><code> |
| grails> create-controller hello</code></pre><p class="paragraph"/>Don't forget that in the interactive console, we have auto-completion on command names. So you can type "cre" and then press <tab> to get a list of all <code>create-*</code> commands. Type a few more letters of the command name and then <tab> again to finish.<p class="paragraph"/>The above command will create a new <a href="../guide/single.html#controllers" class="guide">controller</a> in the <code>grails-app/controllers/helloworld</code> directory called <code>HelloController.groovy</code>. Why the extra <code>helloworld</code> directory? Because in Java land, it's strongly recommended that all classes are placed into packages, so Grails defaults to the application name if you don't provide one. The reference page for <a href="../ref/Command Line/create-controller.html" class="commandLine">create-controller</a> provides more detail on this.<p class="paragraph"/>We now have a controller so let's add an action to generate the "Hello World!" page. The code looks like this:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> helloworld<p class="paragraph"/>class HelloController {<p class="paragraph"/> def index() { |
| render <span class="java-quote">"Hello World!"</span> |
| } |
| }</pre></div><p class="paragraph"/>The action is simply a method. In this particular case, it calls a special method provided by Grails to <a href="../ref/Tags/render.html" class="tags">render</a> the page.<p class="paragraph"/>Job done. To see your application in action, you just need to start up a server with another command called <a href="../ref/Command Line/run-app.html" class="commandLine">run-app</a>:<p class="paragraph"/><pre class="bq"><code> |
| grails> run-app</code></pre><p class="paragraph"/>This will start an embedded server on port 8080 that hosts your application. You should now be able to access your application at the URL <a href="http://localhost:8080/helloworld/" target="blank">http://localhost:8080/helloworld/</a> - try it!<p class="paragraph"/><blockquote class="note"> |
| If you see the error "Server failed to start for port 8080: Address already in use", then it means another server is running on that port. You can easily work around this by running your server on a different port using <code>-Dserver.port=9090 run-app</code>. '9090' is just an example: you can pretty much choose anything within the range 1024 to 49151. |
| </blockquote><p class="paragraph"/>The result will look something like this:<p class="paragraph"/><img border="0" class="center" src="../img/intropage.png"></img><p class="paragraph"/>This is the Grails intro page which is rendered by the <code>grails-app/view/index.gsp</code> file. It detects the presence of your controllers and provides links to them. You can click on the "HelloController" link to see our custom page containing the text "Hello World!". Voila! You have your first working Grails application.<p class="paragraph"/>One final thing: a controller can contain many actions, each of which corresponds to a different page (ignoring AJAX at this point). Each page is accessible via a unique URL that is composed from the controller name and the action name: /<appname>/<controller>/<action>. This means you can access the Hello World page via <a href="http://localhost:8080/helloworld/hello/index" target="blank">/helloworld/hello/index</a>, where 'hello' is the controller name (remove the 'Controller' suffix from the class name and lower-case the first letter) and 'index' is the action name. But you can also access the page via the same URL without the action name: this is because 'index' is the <em class="italic">default action</em> . See the end of the <a href="../guide/single.html#understandingControllersAndActions" class="guide">controllers and actions</a> section of the user guide to find out more on default actions.<p class="paragraph"/> |
| |
| |
| <h2 id="usingInteractiveMode">2.5 Using Interactive Mode</h2> |
| Grails 3.0 features an interactive mode which makes command execution faster since the JVM doesn't have to be restarted for each command. To use interactive mode simple type 'grails' from the root of any projects and use TAB completion to get a list of available commands. See the screenshot below for an example:<p class="paragraph"/><img border="0" class="center" src="../img/interactive-output.png"></img><p class="paragraph"/>For more information on the capabilities of interactive mode refer to the section on <a href="../guide/single.html#interactiveMode" class="guide">Interactive Mode</a> in the user guide. |
| |
| <a name="2.6 Getting Set-up in an IDE"><!-- Legacy link --></a> |
| <h2 id="ide">2.6 Getting Set Up in an IDE</h2> |
| <h4>IntelliJ IDEA</h4><p class="paragraph"/><a href="http://www.jetbrains.com/idea" target="blank">IntelliJ IDEA</a> is an excellent IDE for Grails 3.0 development. It comes in 2 editions, the free community edition and the paid-for ultimate edition.<p class="paragraph"/>The community edition can be used for most things, although GSP syntax higlighting is only part of the ultimate edition. To get started with Intellij IDEA and Grails 3.0 simply go to <code>File / Import Project</code> and point IDEA at your <code>build.gradle</code> file to import and configure the project.<p class="paragraph"/><h4>Eclipse</h4><p class="paragraph"/>We recommend that users of <a href="http://www.eclipse.org/" target="blank">Eclipse</a> looking to develop Grails application take a look at <a href="https://spring.io/tools/ggts" target="blank">Groovy/Grails Tool Suite</a>, which offers built in support for Grails including automatic classpath management, a GSP editor and quick access to Grails commands.<p class="paragraph"/>Like Intellij you can import a Grails 3.0 project using the Gradle project integration.<p class="paragraph"/><h4>NetBeans</h4><p class="paragraph"/>NetBeans provides a Groovy/Grails plugin that automatically recognizes Grails projects and provides the ability to run Grails applications in the IDE, code completion and integration with the Glassfish server. For an overview of features see the <a href="http://www.grails.org/NetBeans+Integration" target="blank">NetBeans Integration</a> guide on the Grails website which was written by the NetBeans team.<p class="paragraph"/><h4>TextMate, Sublime, VIM etc.</h4><p class="paragraph"/>There are several excellent text editors that work nicely with Groovy and Grails. See below for references: |
| <ul class="star"> |
| <li>A <a href="https://github.com/textmate/groovy-grails.tmbundle" target="blank">TextMate bundle</a> exists Groovy / Grails support in <a href="http://macromates.com" target="blank">Textmate</a></li> |
| <li>A <a href="https://github.com/osoco/sublimetext-grails" target="blank">Sublime Text plugin</a> can be installed via Sublime Package Control for the <a href="http://www.sublimetext.com" target="blank">Sublime Text Editor</a>.</li> |
| <li>See <a href="http://www.objectpartners.com/2012/02/21/using-vim-as-your-grails-ide-part-1-navigating-your-project/" target="blank">this post</a> for some helpful tips on how to setup VIM as your Grails editor of choise.</li> |
| <li>An <a href="https://atom.io/packages/atom-grails" target="blank">Atom Package</a> is available for use with the <a href="https://atom.io" target="blank">Atom editor</a></li> |
| </ul><p class="paragraph"/> |
| |
| <a name="2.7 Convention over Configuration"><!-- Legacy link --></a> |
| <h2 id="conventionOverConfiguration">2.7 Convention over Configuration</h2> |
| Grails uses "convention over configuration" to configure itself. This typically means that the name and location of files is used instead of explicit configuration, hence you need to familiarize yourself with the directory structure provided by Grails.<p class="paragraph"/>Here is a breakdown and links to the relevant sections: |
| <ul class="star"> |
| <li><code>grails-app</code> - top level directory for Groovy sources</li> |
| <ul class="star"> |
| <li><code>conf</code> - <a href="../guide/single.html#conf" class="guide">Configuration sources</a>.</li> |
| <li><code>controllers</code> - <a href="../guide/single.html#controllers" class="guide">Web controllers</a> - The C in MVC.</li> |
| <li><code>domain</code> - The <a href="../guide/single.html#GORM" class="guide">application domain</a>.</li> |
| <li><code>i18n</code> - Support for <a href="../guide/single.html#i18n" class="guide">internationalization (i18n)</a>.</li> |
| <li><code>services</code> - The <a href="../guide/single.html#services" class="guide">service layer</a>.</li> |
| <li><code>taglib</code> - <a href="../guide/single.html#taglibs" class="guide">Tag libraries</a>.</li> |
| <li><code>utils</code> - Grails specific utilities.</li> |
| <li><code>views</code> - <a href="../guide/single.html#gsp" class="guide">Groovy Server Pages</a> - The V in MVC.</li> |
| </ul> |
| <li><code>scripts</code> - <a href="../guide/single.html#commandLine" class="guide">Code generation scripts</a>.</li> |
| <li><code>src/main/groovy</code> - Supporting sources</li> |
| <li><code>src/test/groovy</code> - <a href="../guide/single.html#testing" class="guide">Unit and integration tests</a>.</li> |
| </ul><p class="paragraph"/> |
| |
| <a name="2.8 Running an Application"><!-- Legacy link --></a> |
| <h2 id="runningAnApplication">2.8 Running an Application</h2> |
| Grails applications can be run with the built in Tomcat server using the <a href="../ref/Command Line/run-app.html" class="commandLine">run-app</a> command which will load a server on port 8080 by default:<p class="paragraph"/><div class="code"><pre>grails run-app</pre></div><p class="paragraph"/>You can specify a different port by using the <code>server.port</code> argument:<p class="paragraph"/><div class="code"><pre>grails -Dserver.port=8090 run-app</pre></div><p class="paragraph"/>Note that it is better to start up the application in interactive mode since a container restart is much quicker:<p class="paragraph"/><div class="code"><pre>$ grails |
| grails> run-app |
| | Server running. Browse to http://localhost:8080/helloworld |
| | Application loaded in interactive mode. Type 'stop-app' to shutdown. |
| | Downloading: plugins-list.xml |
| grails> stop-app |
| | Stopping Grails server |
| grails> run-app |
| | Server running. Browse to http://localhost:8080/helloworld |
| | Application loaded in interactive mode. Type 'stop-app' to shutdown. |
| | Downloading: plugins-list.xml</pre></div><p class="paragraph"/>More information on the <a href="../ref/Command Line/run-app.html" class="commandLine">run-app</a> command can be found in the reference guide. |
| |
| <a name="2.9 Testing an Application"><!-- Legacy link --></a> |
| <h2 id="testingAnApplication">2.9 Testing an Application</h2> |
| The <code>create-*</code> commands in Grails automatically create unit or integration tests for you within the <code>src/test/groovy</code> directory. It is of course up to you to populate these tests with valid test logic, information on which can be found in the section on <a href="../guide/single.html#testing" class="guide">Testing</a>.<p class="paragraph"/>To execute tests you run the <a href="../ref/Command Line/test-app.html" class="commandLine">test-app</a> command as follows:<p class="paragraph"/><div class="code"><pre>grails test-app</pre></div> |
| |
| |
| <a name="2.10 Deploying an Application"><!-- Legacy link --></a> |
| <h2 id="deployingAnApplication">2.10 Deploying an Application</h2> |
| Grails applications can be deployed in a number of different ways.<p class="paragraph"/>If you are deploying to a traditional container (Tomcat, Jetty etc.) you can create a Web Application Archive (WAR file), and Grails includes the <a href="../ref/Command Line/war.html" class="commandLine">war</a> command for performing this task:<p class="paragraph"/><div class="code"><pre>grails war</pre></div><p class="paragraph"/>This will produce a WAR file under the <code>build/libs</code> directory which can then be deployed as per your container's instructions.<p class="paragraph"/>Unlike most scripts which default to the <code>development</code> environment unless overridden, the <code>war</code> command runs in the <code>production</code> environment by default. You can override this like any script by specifying the environment name, for example:<p class="paragraph"/><div class="code"><pre>grails dev war</pre></div><p class="paragraph"/>If you prefer not to operate a separate Servlet container then you can simply run the Grails WAR file as a regular Java application. Example:<p class="paragraph"/><div class="code"><pre>grails war |
| java -Xmx768M -XX:MaxPermSize=256m -jar build/libs/mywar-0.1.war</pre></div><p class="paragraph"/> |
| When deploying Grails you should always run your containers JVM with the <code>-server</code> option and with sufficient memory allocation. A good set of VM flags would be:<p class="paragraph"/><div class="code"><pre>-server -Xmx768M -XX:MaxPermSize=256m</pre></div> |
| |
| |
| <a name="2.11 Supported Java EE Containers"><!-- Legacy link --></a> |
| <h2 id="supportedJavaEEContainers">2.11 Supported Java EE Containers</h2> |
| Grails runs on any container that supports Servlet 3.0 and above and is known to work on the following specific container products: |
| <ul class="star"> |
| <li>Tomcat 7</li> |
| <li>GlassFish 3 or above</li> |
| <li>Resin 4 or above</li> |
| <li>JBoss 6 or above</li> |
| <li>Jetty 8 or above</li> |
| <li>Oracle Weblogic 12c or above</li> |
| <li>IBM WebSphere 8.0 or above</li> |
| </ul><p class="paragraph"/><blockquote class="note"> |
| It's required to set "-Xverify:none" in "Application servers > server > Process Definition > Java Virtual Machine > Generic JVM arguments" for older versions of WebSphere. This is no longer needed for WebSphere version 8 or newer. |
| </blockquote><p class="paragraph"/>Some containers have bugs however, which in most cases can be worked around. A <a href="http://grails.org/Deployment" target="blank">list of known deployment issues</a> can be found on the Grails wiki. |
| |
| <a name="2.13 Creating Artefacts"><!-- Legacy link --></a> |
| <h2 id="creatingArtefacts">2.12 Creating Artefacts</h2> |
| Grails ships with a few convenience targets such as <a href="../ref/Command Line/create-controller.html" class="commandLine">create-controller</a>, <a href="../ref/Command Line/create-domain-class.html" class="commandLine">create-domain-class</a> and so on that will create <a href="../guide/single.html#controllers" class="guide">Controllers</a> and different artefact types for you. |
| <blockquote class="note"> |
| These are just for your convenience and you can just as easily use an IDE or your favourite text editor. |
| </blockquote> |
| For example to create the basis of an application you typically need a <a href="../guide/single.html#GORM" class="guide">domain model</a>:<p class="paragraph"/><div class="code"><pre>grails create-app helloworld |
| cd helloworld |
| grails create-domain-class book</pre></div><p class="paragraph"/>This will result in the creation of a domain class at <code>grails-app/domain/helloworld/Book.groovy</code> such as:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> helloworld<p class="paragraph"/>class Book { |
| }</pre></div><p class="paragraph"/>There are many such <code>create-*</code> commands that can be explored in the command line reference guide.<p class="paragraph"/><blockquote class="note"> |
| To decrease the amount of time it takes to run Grails scripts, use the interactive mode. |
| </blockquote> |
| |
| |
| <a name="2.12 Generating an Application"><!-- Legacy link --></a> |
| <h2 id="generatingAnApplication">2.13 Generating an Application</h2> |
| To get started quickly with Grails it is often useful to use a feature called <a href="../guide/single.html#scaffolding" class="guide">Scaffolding</a> to generate the skeleton of an application. To do this use one of the <code>generate-*</code> commands such as <a href="../ref/Command Line/generate-all.html" class="commandLine">generate-all</a>, which will generate a <a href="../guide/single.html#controllers" class="guide">controller</a> (and its unit test) and the associated <a href="../guide/single.html#gsp" class="guide">views</a>:<p class="paragraph"/><div class="code"><pre>grails generate-all helloworld.Book</pre></div> |
| |
| |
| |
| <h1 id="upgrading">3 Upgrading from Grails 2.x</h1> |
| Grails 3.0 is a complete ground up rewrite of Grails and introduces new concepts and components for many parts of the framework.<p class="paragraph"/>When upgrading an application or plugin from Grails 3.0 there are many areas to consider including: |
| <ul class="star"> |
| <li>Project structure differences</li> |
| <li>File location differences</li> |
| <li>Configuration differences</li> |
| <li>Package name differences</li> |
| <li>Legacy Gant Scripts</li> |
| <li>Gradle Build System</li> |
| <li>Changes to Plugins</li> |
| <li>Source vs Binary Plugins</li> |
| </ul><p class="paragraph"/>The best approach to take when upgrading a plugin or application (and if your application is using several plugins the plugins will need upgrading first) is to create a new Grails 3.0 application of the same name and copy the source files into the correct locations in the new application.<p class="paragraph"/><h3>Project Structure Changes</h3><p class="paragraph"/><h4>File Location Differences</h4><p class="paragraph"/>The location of certain files have changed or been replaced with other files in Grails 3.0. The following table lists old default locations and their respective new locations:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th><strong class="bold">Old Location</strong></th><th><strong class="bold">New Location</strong></th><th><strong class="bold">Description</strong></th></tr><tr class="table-odd"><td><code>grails-app/conf/BuildConfig.groovy</code></td><td><code>build.gradle</code></td><td>Build time configuration is now defined in a Gradle build file</td></tr><tr class="table-even"><td><code>grails-app/conf/Config.groovy</code></td><td><code>grails-app/conf/application.groovy</code></td><td>Renamed for consistency with Spring Boot</td></tr><tr class="table-odd"><td><code>grails-app/conf/UrlMappings.groovy</code></td><td><code>grails-app/controllers/UrlMappings.groovy</code></td><td>Moved since grails-app/conf is not a source directory anymore</td></tr><tr class="table-even"><td><code>grails-app/conf/BootStrap.groovy</code></td><td><code>grails-app/init/BootStrap.groovy</code></td><td>Moved since grails-app/conf is not a source directory anymore</td></tr><tr class="table-odd"><td><code>scripts</code></td><td><code>src/main/scripts</code></td><td>Moved for consistency with Gradle</td></tr><tr class="table-even"><td><code>src/groovy</code></td><td><code>src/main/groovy</code></td><td>Moved for consistency with Gradle</td></tr><tr class="table-odd"><td><code>src/java</code></td><td><code>src/main/groovy</code></td><td>Moved for consistency with Gradle</td></tr><tr class="table-even"><td><code>test/unit</code></td><td><code>src/test/groovy</code></td><td>Moved for consistency with Gradle</td></tr><tr class="table-odd"><td><code>test/integration</code></td><td><code>src/integration-test/groovy</code></td><td>Moved for consistency with Gradle</td></tr><tr class="table-even"><td><code>web-app</code></td><td><code>src/main/webapp</code></td><td>Moved for consistency with Gradle</td></tr><tr class="table-odd"><td><code>*GrailsPlugin.groovy</code></td><td><code>src/main/groovy</code></td><td>The plugin descriptor moved to a source directory</td></tr></table><p class="paragraph"/>For plugins the plugin descriptor (a Groovy file ending with "GrailsPlugin") which was previously located in the root of the plugin directory should be moved to the <code>src/main/groovy</code> directory under an appropriate package.<p class="paragraph"/><h4>New Files Not Present in Grails 2.x</h4><p class="paragraph"/>The reason it is best to create a new application and copy your original sources to it is because there are a number of new files that are not present in Grails 2.x by default. These include:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th><strong class="bold">File</strong></th><th><strong class="bold">Description</strong></th></tr><tr class="table-odd"><td><code>build.gradle</code></td><td>The Gradle build descriptor located in the root of the project</td></tr><tr class="table-even"><td><code>gradle.properties</code></td><td>Properties file defining the Grails and Gradle versions</td></tr><tr class="table-odd"><td><code>grails-app/conf/logback.groovy</code></td><td>Logging previously defined in <code>Config.groovy</code> is now defined using Logback</td></tr><tr class="table-even"><td><code>grails-app/conf/application.yml</code></td><td>Configuration can now also be defined using YAML</td></tr><tr class="table-odd"><td><code>grails-app/init/PACKAGE_PATH/Application.groovy</code></td><td>The <code>Application</code> class used By Spring Boot to start the application</td></tr></table><p class="paragraph"/><h4>Files Not Present in Grails 3.x</h4><p class="paragraph"/>Some files that were previously created by Grails 2.x are no longer created. These have either been removed or an appropriate replacement added. The following table lists files no longer in use:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th><strong class="bold">File</strong></th><th><strong class="bold">Description</strong></th></tr><tr class="table-odd"><td><code>application.properties</code></td><td>The application name and version is now defined in <code>build.gradle</code></td></tr><tr class="table-even"><td><code>grails-app/conf/DataSource.groovy</code></td><td>Merged together into <code>application.yml</code></td></tr><tr class="table-odd"><td><code>lib</code></td><td>Dependency resolution should be used to resolve JAR files</td></tr><tr class="table-even"><td><code>web-app/WEB-INF/applicationContext.xml</code></td><td>Removed, beans can be defined in <code>grails-app/conf/spring/resources.groovy</code></td></tr><tr class="table-odd"><td><code>src/templates/war/web.xml</code></td><td>Grails 3.0 no longer requires web.xml. Customizations can be done via Spring</td></tr><tr class="table-even"><td><code>web-app/WEB-INF/sitemesh.xml</code></td><td>Removed, sitemesh filter no longer present.</td></tr><tr class="table-odd"><td><code>web-app/WEB-INF/tld</code></td><td>Removed, can be restored in src/main/webapp</td></tr></table> |
| |
| |
| |
| <h2 id="upgradingPlugins">3.1 Upgrading Plugins</h2> |
| To upgrade a Grails 2.x plugin to Grails 3.x you need to make a number of different changes. This documentation will outline the steps that were taken to upgrade the Quartz plugin to Grails 3, each individual plugin may differ.<p class="paragraph"/><h4>Step 1 - Create a new Grails 3 plugin</h4><p class="paragraph"/>The first step is to create a new Grails 3 plugin using the command line:<p class="paragraph"/><div class="code"><pre>$ grails create-plugin quartz</pre></div><p class="paragraph"/>This will create a Grails 3 plugin in the <code>quartz</code> directory.<p class="paragraph"/><h4>Step 2 - Copy sources from the original Grails 2 plugin</h4><p class="paragraph"/>The next step is to copy the sources from the original Grails 2 plugin to the Grails 3 plugin:<p class="paragraph"/><div class="code"><pre># first the sources |
| cp -rf ../quartz-2.x/src/groovy src/main/groovy |
| cp -rf ../quartz-2.x/src/java src/main/groovy |
| cp -rf ../quartz-2.x/grails-app grails-app |
| cp -rf ../quartz-2.x/QuartzGrailsPlugin.groovy src/main/groovy/grails/plugins/quartz<p class="paragraph"/># then the tests |
| cp -rf ../quartz-2.x/test/unit src/test/groovy |
| mkdir -p src/integration-test/groovy |
| cp -rf ../quartz-2.x/test/integration src/integration-test/groovy<p class="paragraph"/># then templates / other resources |
| cp -rf ../quartz-2.x/src/templates src/main/templates</pre></div><p class="paragraph"/><h4>Step 3 - Alter the plugin descriptor</h4><p class="paragraph"/>You will need to add a package declaration to the plugin descriptor. In this case <code>QuartzGrailsPlugin</code> is modified as follows:<p class="paragraph"/><div class="code"><pre>// add <span class="java-keyword">package</span> declaration |
| <span class="java-keyword">package</span> grails.plugins.quartz |
| … |
| class QuartzGrailsPlugin { |
| … |
| }</pre></div><p class="paragraph"/>In addition you should remove the <code>version</code> property from the descriptor as this is now defined in <code>build.gradle</code>.<p class="paragraph"/><h4>Step 4 - Update the Gradle build with required dependencies</h4><p class="paragraph"/>The repositories and dependencies defined in <code>grails-app/conf/BuildConfig.groovy</code> of the original Grails 2.x plugin will need to be defined in <code>build.gradle</code> of the new Grails 3.x plugin:<p class="paragraph"/><div class="code"><pre>compile(<span class="java-quote">"org.quartz-scheduler:quartz:2.2.1"</span>) { |
| exclude group: 'slf4j-api', module: 'c3p0' |
| }</pre></div><p class="paragraph"/><h4>Step 5 - Modify Package Imports</h4><p class="paragraph"/>In Grails 3.x all internal APIs can be found in the <code>org.grails</code> package and public facing APIs in the <code>grails</code> package. The <code>org.codehaus.groovy.grails</code> package no longer exists.<p class="paragraph"/>All package declaration in sources should be modified for the new location of the respective classes. Example <code>org.codehaus.groovy.grails.commons.GrailsApplication</code> is now <code>grails.core.GrailsApplication</code>.<p class="paragraph"/><h4>Step 5 - Migrate Plugin Specific Config to application.yml</h4><p class="paragraph"/>Some plugins define a default configuration file. For example the Quartz plugin defines a file called <code>grails-app/conf/DefaultQuartzConfig.groovy</code>. In Grails 3.x this default configuration can be migrated to <code>grails-app/conf/application.yml</code> and it will automatically be loaded by Grails without requiring manual configuration merging.<p class="paragraph"/><h4>Step 6 - Register ArtefactHandler Definitions</h4><p class="paragraph"/>In Grails 3.x <a href="http://grails.org/doc/3.0.x/api/grails/core/ArtefactHandler.html" class="api">ArtefactHandler</a> definitions written in Java need to be declared in a file called <code>src/main/resources/META-INF/grails.factories</code> since these need to be known at compile time.<p class="paragraph"/><blockquote class="note"> |
| If the <code>ArtefactHandler</code> is written in Groovy this step can be skipped as Grails will automatically create the <code>grails.factories</code> file during compilation. |
| </blockquote><p class="paragraph"/>The Quartz plugin requires the following definition to register the <code>ArtrefactHandler</code>:<p class="paragraph"/><div class="code"><pre>grails.core.ArtefactHandler=grails.plugins.quartz.JobArtefactHandler</pre></div><p class="paragraph"/><h4>Step 7 - Migrate Code Generation Scripts</h4><p class="paragraph"/>Many plugins previously defined command line scripts in Gant. In Grails 3.x command line scripts have been replaced by two new features: Code generation scripts and Gradle tasks.<p class="paragraph"/>If your script is doing simple code generation then for many cases a code generation script can replace an old Gant script.<p class="paragraph"/>The <code>create-job</code> script provided by the Quartz plugin in Grails 2.x was defined in <code>scripts/CreateJob.groovy</code> as:<p class="paragraph"/><div class="code"><pre>includeTargets << grailsScript(<span class="java-quote">"_GrailsCreateArtifacts"</span>)<p class="paragraph"/>target(createJob: <span class="java-quote">"Creates a <span class="java-keyword">new</span> Quartz scheduled job"</span>) { |
| depends(checkVersion, parseArguments)<p class="paragraph"/> def type = <span class="java-quote">"Job"</span> |
| promptForName(type: type)<p class="paragraph"/> <span class="java-keyword">for</span> (name in argsMap.params) { |
| name = purgeRedundantArtifactSuffix(name, type) |
| createArtifact(name: name, suffix: type, type: type, path: <span class="java-quote">"grails-app/jobs"</span>) |
| createUnitTest(name: name, suffix: type) |
| } |
| }<p class="paragraph"/>setDefaultTarget 'createJob'</pre></div><p class="paragraph"/>A replacement Grails 3.x compatible script can be created using the <code>create-script</code> command:<p class="paragraph"/><div class="code"><pre>$ grails create-script create-job</pre></div><p class="paragraph"/>Which creates a new script called <code>src/main/scripts/create-job.groovy</code>. Using the new code generation API it is simple to implement:<p class="paragraph"/><div class="code"><pre>description(<span class="java-quote">"Creates a <span class="java-keyword">new</span> Quartz scheduled job"</span>) { |
| usage <span class="java-quote">"grails create-job [JOB NAME]"</span> |
| argument name:'Job Name', description:<span class="java-quote">"The name of the job"</span> |
| }<p class="paragraph"/>model = model( args[0] ) |
| render template:<span class="java-quote">"Job.groovy"</span>, |
| destination: file( <span class="java-quote">"grails-app/jobs/$model.packagePath/${model.simpleName}Job.groovy"</span>), |
| model: model</pre></div><p class="paragraph"/>Please refer to the documentation on <a href="../guide/single.html#creatingCustomScripts" class="guide">Creating Custom Scripts</a> for more information.<p class="paragraph"/><h4>Migrating More Complex Scripts Using Gradle Tasks</h4><p class="paragraph"/>Using the old Grails 2.x build system it was relatively common to spin up Grails inside the command line. In Grails 3.x it is not possible to load a Grails application within a code generation script created by the <a href="../ref/Command Line/create-script.html" class="commandLine">create-script</a> command.<p class="paragraph"/>Instead a new mechanism specific to plugins exists via the <a href="../ref/Command Line/create-command.html" class="commandLine">create-command</a> command. The <code>create-command</code> command will create a new <a href="http://grails.org/doc/3.0.x/api/grails/dev/commands/ApplicationCommand.html" class="api">ApplicationCommand</a>, for example the following command will execute a query:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.dev.commands.* |
| <span class="java-keyword">import</span> javax.sql.* |
| <span class="java-keyword">import</span> groovy.sql.* |
| <span class="java-keyword">import</span> org.springframework.beans.factory.annotation.*<p class="paragraph"/>class RunQueryCommand <span class="java-keyword">implements</span> ApplicationCommand {<p class="paragraph"/> @Autowired |
| DataSource dataSource<p class="paragraph"/> <span class="java-object">boolean</span> handle(ExecutionContext ctx) { |
| def sql = <span class="java-keyword">new</span> Sql(dataSource) |
| println sql.executeQuery(<span class="java-quote">"select * from foo"</span>) |
| <span class="java-keyword">return</span> <span class="java-keyword">true</span> |
| } |
| }</pre></div><p class="paragraph"/>With this command in place once the plugin is installed into your local Maven cache you can add the plugin to both the build classpath and the runtime classpath of the application's <code>build.gradle</code> file:<p class="paragraph"/><div class="code"><pre>buildscript { |
| … |
| dependencies { |
| classpath <span class="java-quote">"org.grails.plugins:myplugin:0.1-SNAPSHOT"</span> |
| } |
| } |
| … |
| dependencies { |
| runtime <span class="java-quote">"org.grails.plugins:myplugin:0.1-SNAPSHOT"</span> |
| }</pre></div><p class="paragraph"/>Grails will automatically create a Gradle task called <code>runQuery</code> and a command named <code>run-query</code> so both the following examples will execute the command:<p class="paragraph"/><div class="code"><pre>$ grails run-query |
| $ gradle runQuery</pre></div><p class="paragraph"/><h4>Step 8 - Delete Files that were migrated or no longer used</h4><p class="paragraph"/>You should now delete and cleanup the project of any files no longer required by Grails 3.x (<code>BuildConfig.groovy</code>, <code>Config.groovy</code>, <code>DataSource.groovy</code> etc.) |
| |
| |
| |
| <h2 id="upgradingApps">3.2 Upgrading Applications</h2> |
| Upgrading applications to Grails 3.x will require that you upgrade all plugins the application uses first, hence you should follow the steps in the previous section to first upgrade your plugins.<p class="paragraph"/><h4>Step 1 - Create a New Application</h4><p class="paragraph"/>Once the plugins are Grails 3.x compatible you can upgrade the application. To upgrade an application it is again best to create a new Grails 3 application using the "web" profile:<p class="paragraph"/><div class="code"><pre>$ grails create-app myapp |
| $ cd myapp</pre></div><p class="paragraph"/><h4>Step 2 - Migrate Sources</h4><p class="paragraph"/>The next step is to copy the sources from the original Grails 2 application to the Grails 3 application:<p class="paragraph"/><div class="code"><pre># first the sources |
| cp -rf ../old_app/src/groovy src/main/groovy |
| cp -rf ../old_app/src/java src/main/groovy |
| cp -rf ../old_app/grails-app grails-app<p class="paragraph"/># then the tests |
| cp -rf ../old_app/test/unit src/test/groovy |
| mkdir -p src/integration-test/groovy |
| cp -rf ../old_app/test/integration src/integration-test/groovy</pre></div><p class="paragraph"/><h4>Step 3 - Update the Gradle build with required dependencies</h4><p class="paragraph"/>The repositories and dependencies defined in <code>grails-app/conf/BuildConfig.groovy</code> of the original Grails 2.x application will need to be defined in <code>build.gradle</code> of the new Grails 3.x application.<p class="paragraph"/><h4>Step 4 - Modify Package Imports</h4><p class="paragraph"/>In Grails 3.x all internal APIs can be found in the <code>org.grails</code> package and public facing APIs in the <code>grails</code> package. The <code>org.codehaus.groovy.grails</code> package no longer exists.<p class="paragraph"/>All package declaration in sources should be modified for the new location of the respective classes. Example <code>org.codehaus.groovy.grails.commons.GrailsApplication</code> is now <code>grails.core.GrailsApplication</code>.<p class="paragraph"/><h4>Step 5 - Migrate Configuration</h4><p class="paragraph"/>The configuration of the application will need to be migrated, this can normally be done by simply renaming <code>grails-app/conf/Config.groovy</code> to <code>grails-app/conf/application.groovy</code> and merging the content of <code>grails-app/conf/DataSource.groovy</code> into <code>grails-app/conf/application.groovy</code>.<p class="paragraph"/>Note however that Log4j has been replaced by <code>grails-app/conf/logback.groovy</code> for logging, so any logging configuration in <code>grails-app/conf/Config.groovy</code> should be migrated to <a href="http://logback.qos.ch/manual/groovy.html" target="blank">logback format</a>.<p class="paragraph"/><h4>Step 6 - Migrate web.xml Modifications to Spring</h4><p class="paragraph"/>If you have a modified <code>web.xml</code> template then you will need to migrate this to Spring as Grails 3.x does not use a web.xml (although it is still possible to have on in <code>src/main/webapp/WEB-INF/web.xml</code>).<p class="paragraph"/>New servlets and filters can be registered as Spring beans or with <a href="http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/context/embedded/ServletRegistrationBean.html" class="api">ServletRegistrationBean</a> and <a href="http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/context/embedded/FilterRegistrationBean.html" class="api">FilterRegistrationBean</a> respectively.<p class="paragraph"/><h4>Step 7 - Migrate Tests</h4><p class="paragraph"/>Once the package names are corrected unit tests will continue to run, however any tests that extend the deprecated and removed JUnit 3 hierarchy will need to be migrated to Spock or JUnit 4.<p class="paragraph"/>Integration tests will need to be annotated with the <a href="http://grails.org/doc/3.0.x/api/grails/test/mixin/integration/Integration.html" class="api">Integration</a> annotation and should not extend GroovyTestCase or any JUnit 3 super class. |
| |
| |
| <a name="3. Configuration"><!-- Legacy link --></a> |
| <h1 id="conf">4 Configuration</h1> |
| It may seem odd that in a framework that embraces "convention-over-configuration" that we tackle this topic now. With Grails' default settings you can actually develop an application without doing any configuration whatsoever, as the quick start demonstrates, but it's important to learn where and how to override the conventions when you need to. Later sections of the user guide will mention what configuration settings you can use, but not how to set them. The assumption is that you have at least read the first section of this chapter! |
| |
| |
| <a name="3.1 Basic Configuration"><!-- Legacy link --></a> |
| <h2 id="config">4.1 Basic Configuration</h2> |
| Configuration in Grails is generally split across 2 areas: build configuration and runtime configuration.<p class="paragraph"/>Build configuration is generally done via Gradle and the <code>build.gradle</code> file. Runtime configuration is by default specified in YAML in the <code>grails-app/conf/application.yml</code> file.<p class="paragraph"/>If you prefer to use Grails 2.0-style Groovy configuration then you can create an additional <code>grails-app/conf/application.groovy</code> file to specify configuration using Groovy's <a href="http://groovy.codehaus.org/ConfigSlurper" target="blank">ConfigSlurper</a> syntax.<p class="paragraph"/>For Groovy configuration the following variables are available to the configuration script:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th><strong class="bold">Variable</strong></th><th><strong class="bold">Description</strong></th></tr><tr class="table-odd"><td>userHome</td><td>Location of the home directory for the account that is running the Grails application.</td></tr><tr class="table-even"><td>grailsHome</td><td>Location of the directory where you installed Grails. If the <code>GRAILS_HOME</code> environment variable is set, it is used.</td></tr><tr class="table-odd"><td>appName</td><td>The application name as it appears in application.properties.</td></tr><tr class="table-even"><td>appVersion</td><td>The application version as it appears in application.properties.</td></tr></table><p class="paragraph"/>For example:<p class="paragraph"/><div class="code"><pre>my.tmp.dir = <span class="java-quote">"${userHome}/.grails/tmp"</span></pre></div><p class="paragraph"/> |
| If you want to read runtime configuration settings, i.e. those defined in <code>application.yml</code>, use the <a href="http://grails.org/doc/3.0.x/api/grails/core/GrailsApplication.html" class="api"><code>grailsApplication</code></a> object, which is available as a variable in controllers and tag libraries:<p class="paragraph"/><div class="code"><pre>class MyController { |
| def hello() { |
| def recipient = grailsApplication.config.getProperty('foo.bar.hello')<p class="paragraph"/> render <span class="java-quote">"Hello ${recipient}"</span> |
| } |
| }</pre></div><p class="paragraph"/>The <code>config</code> property of the <code>grailsApplication</code> object is an instance of the <a href="http://grails.org/doc/3.0.x/api/grails/config/Config.html" class="api">Config</a> interface and provides a number of useful methods to read the configuration of the application.<p class="paragraph"/>Notice that the <code>Config</code> instance is a merged configuration based on Spring's <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/context/annotation/PropertySource.html" class="api">PropertySource</a> concept and reads configuration from the environment, system properties and the local application configuration merging them into a single object.<p class="paragraph"/> |
| and can be easily injected into services and other Grails artifacts:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.core.*<p class="paragraph"/>class MyService { |
| GrailsApplication grailsApplication<p class="paragraph"/> <span class="java-object">String</span> greeting() { |
| def recipient = grailsApplication.config.getProperty('foo.bar.hello') |
| <span class="java-keyword">return</span> <span class="java-quote">"Hello ${recipient}"</span> |
| } |
| }</pre></div><p class="paragraph"/>Finally, you can also use Spring's <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/beans/factory/annotation/Value.html" class="api">Value</a> annotation to dependency injection configuration values:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.springframework.beans.factory.annotation.*<p class="paragraph"/>class MyController { |
| @Value('${foo.bar.hello}') |
| <span class="java-object">String</span> recipient<p class="paragraph"/> def hello() { |
| render <span class="java-quote">"Hello ${recipient}"</span> |
| } |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| In Groovy code you must use single quotes around the string for the value of the <code>Value</code> annotation otherwise it is interpreted as a GString not a Spring expression. |
| </blockquote><p class="paragraph"/>As you can see, when accessing configuration settings you use the same dot notation as when you define them. |
| |
| |
| <a name="3.1.1 Built in options"><!-- Legacy link --></a> |
| <h2 id="builtInOptions">4.1.1 Built in options</h2> |
| Grails has a set of core settings that are worth knowing about. Their defaults are suitable for most projects, but it's important to understand what they do because you may need one or more of them later.<p class="paragraph"/> |
| <h3>Runtime settings</h3><p class="paragraph"/>On the runtime front, i.e. <code>grails-app/conf/application.yml</code>, there are quite a few more core settings: |
| <ul class="star"> |
| <li><code>grails.enable.native2ascii</code> - Set this to false if you do not require native2ascii conversion of Grails i18n properties files (default: true).</li> |
| <li><code>grails.views.default.codec</code> - Sets the default encoding regime for GSPs - can be one of 'none', 'html', or 'base64' (default: 'none'). To reduce risk of XSS attacks, set this to 'html'.</li> |
| <li><code>grails.views.gsp.encoding</code> - The file encoding used for GSP source files (default: 'utf-8').</li> |
| <li><code>grails.mime.file.extensions</code> - Whether to use the file extension to dictate the mime type in <a href="../guide/single.html#contentNegotiation" class="guide">Content Negotiation</a> (default: true).</li> |
| <li><code>grails.mime.types</code> - A map of supported mime types used for <a href="../guide/single.html#contentNegotiation" class="guide">Content Negotiation</a>.</li> |
| <li><code>grails.serverURL</code> - A string specifying the server URL portion of absolute links, including server name e.g. grails.serverURL="http://my.yourportal.com". See <a href="../ref/Tags/createLink.html" class="Tags">createLink</a>. Also used by redirects.</li> |
| <li><code>grails.views.gsp.sitemesh.preprocess</code> - Determines whether SiteMesh preprocessing happens. Disabling this slows down page rendering, but if you need SiteMesh to parse the generated HTML from a GSP view then disabling it is the right option. Don't worry if you don't understand this advanced property: leave it set to true.</li> |
| <li><code>grails.reload.excludes</code> and <code>grails.reload.includes</code> - Configuring these directives determines the reload behavior for project specific source files. Each directive takes a list of strings that are the class names for project source files that should be excluded from reloading behavior or included accordingly when running the application in development with the <code>run-app</code> command. If the <code>grails.reload.includes</code> directive is configured, then only the classes in that list will be reloaded.</li> |
| </ul><p class="paragraph"/> |
| |
| <a name="3.1.2 Logging"><!-- Legacy link --></a> |
| <h2 id="logging">4.1.2 Logging</h2> |
| By default logging in Grails 3.0 is handled by the <a href="http://logback.qos.ch" target="blank">Logback logging framework</a> and can be configured with the <code>grails-app/conf/logback.groovy</code> file.<p class="paragraph"/><blockquote class="note"> |
| If you prefer XML you can replace the <code>logback.groovy</code> file with a <code>logback.xml</code> file instead. |
| </blockquote><p class="paragraph"/>For more information on configuring logging refer to the <a href="http://logback.qos.ch/manual/groovy.html" target="blank">Logback documentation</a> on the subject. |
| |
| <a name="3.1.3 GORM"><!-- Legacy link --></a> |
| <h2 id="configGORM">4.1.3 GORM</h2> |
| Grails provides the following GORM configuration options: |
| <ul class="star"> |
| <li><code>grails.gorm.failOnError</code> - If set to <code>true</code>, causes the <code>save()</code> method on domain classes to throw a <code>grails.validation.ValidationException</code> if <a href="../guide/single.html#validation" class="guide">validation</a> fails during a save. This option may also be assigned a list of Strings representing package names. If the value is a list of Strings then the failOnError behavior will only be applied to domain classes in those packages (including sub-packages). See the <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> method docs for more information.</li> |
| </ul><p class="paragraph"/>For example, to enable failOnError for all domain classes: |
| <div class="code"><pre>grails: |
| gorm: |
| failOnError: <span class="java-keyword">true</span></pre></div><p class="paragraph"/>and to enable failOnError for domain classes by package:<p class="paragraph"/><div class="code"><pre>grails: |
| gorm: |
| failOnError: |
| - com.companyname.somepackage |
| - com.companyname.someotherpackage</pre></div> |
| <ul class="star"> |
| <li><code>grails.gorm.autoFlush</code> - If set to <code>true</code>, causes the <a href="../ref/Domain Classes/merge.html" class="domainClasses">merge</a>, <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> and <a href="../ref/Domain Classes/delete.html" class="domainClasses">delete</a> methods to flush the session, replacing the need to explicitly flush using <code>save(flush: true)</code>.</li> |
| </ul><p class="paragraph"/> |
| |
| |
| <h2 id="applicationClass">4.2 The Application Class</h2> |
| Every new Grails application features an <code>Application</code> class witin the the <code>grails-app/init</code> directory.<p class="paragraph"/>The <code>Application</code> class subclasses the <a href="http://grails.org/doc/3.0.x/api/grails/boot/config/GrailsAutoConfiguration.html" class="api">GrailsAutoConfiguration</a> class and features a <code>static void main</code> method, meaning it can be run as a regular application. |
| |
| |
| |
| <h2 id="executing">4.2.1 Executing the Application Class</h2> |
| There are several ways to execute the <code>Application</code> class, if you are using an IDE then you can simply right click on the class and run it directly from your IDE which will start your Grails application.<p class="paragraph"/>This is also useful for debugging since you can debug directly from the IDE without having to connect a remote debugger when using the <code>run-app --debug-jvm</code> command from the command line.<p class="paragraph"/>You can also package your application into a runnable WAR file, for example:<p class="paragraph"/><div class="code"><pre>$ grails <span class="java-keyword">package</span> |
| $ java -jar build/libs/myapp-0.1.war</pre></div><p class="paragraph"/>This is useful if you plan to deploy your application using a container-less approach. |
| |
| |
| |
| <h2 id="customizing">4.2.2 Customizing the Application Class</h2> |
| There are several ways in which you can customize the <code>Application</code> class.<p class="paragraph"/><h4>Customizing Scanning</h4><p class="paragraph"/>By default Grails will scan all known source directories for controllers, domain class etc., however if there are packages in other JAR files you wish to scan you can do so by overriding the <code>packageNames()</code> method of the <code>Application</code> class:<p class="paragraph"/><div class="code"><pre>class Application <span class="java-keyword">extends</span> GrailsAutoConfiguration { |
| @Override |
| Collection<<span class="java-object">String</span>> packageNames() { |
| <span class="java-keyword">super</span>.packageNames() + ['my.additional.<span class="java-keyword">package</span>'] |
| }<p class="paragraph"/> … |
| }</pre></div><p class="paragraph"/><h4>Registering Additional Beans</h4><p class="paragraph"/>The <code>Application</code> class can also be used as a source for Spring bean definitions, simply define a method annotated with the <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/context/annotation/Bean.html" class="api">Bean</a> and the returned object will become a Spring bean. The name of the method is used as the bean name:<p class="paragraph"/><div class="code"><pre>class Application <span class="java-keyword">extends</span> GrailsAutoConfiguration { |
| @Bean |
| MyType myBean() { |
| <span class="java-keyword">return</span> <span class="java-keyword">new</span> MyType() |
| }<p class="paragraph"/> … |
| }</pre></div> |
| |
| |
| |
| <h2 id="applicationLifeCycle">4.2.3 The Application LifeCycle</h2> |
| The <code>Application</code> class also implements the <a href="http://grails.org/doc/3.0.x/api/grails/core/GrailsApplicationLifeCycle.html" class="api">GrailsApplicationLifeCycle</a> interface which all plugins implement.<p class="paragraph"/>This means that the <code>Application</code> class can be used to perform the same functions as a plugin. You can override the <a href="../guide/single.html#hookingIntoRuntimeConfiguration" class="guide">regular plugins hooks</a> such as <code>doWithSpring</code>, <code>doWithApplicationContext</code> and so on by overriding the appropriate method:<p class="paragraph"/><div class="code"><pre>class Application <span class="java-keyword">extends</span> GrailsAutoConfiguration { |
| @Override |
| Closure doWithSpring() { |
| {-> |
| mySpringBean(MyType) |
| } |
| }<p class="paragraph"/> … |
| }</pre></div> |
| |
| |
| <a name="3.2 Environments"><!-- Legacy link --></a> |
| <h2 id="environments">4.3 Environments</h2> |
| <h4>Per Environment Configuration</h4><p class="paragraph"/>Grails supports the concept of per environment configuration. The <code>application.yml</code> and <code>application.groovy</code> files in the <code>grails-app/conf</code> directory can use per-environment configuration using either YAML or the syntax provided by <a href="http://groovy.codehaus.org/ConfigSlurper" target="blank">ConfigSlurper</a>. As an example consider the following default <code>application.yml</code> definition provided by Grails:<p class="paragraph"/><div class="code"><pre>environments: |
| development: |
| dataSource: |
| dbCreate: create-drop |
| url: jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE |
| test: |
| dataSource: |
| dbCreate: update |
| url: jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE |
| production: |
| dataSource: |
| dbCreate: update |
| url: jdbc:h2:prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE |
| properties: |
| jmxEnabled: <span class="java-keyword">true</span> |
| initialSize: 5 |
| ...</pre></div><p class="paragraph"/>The above can expression in Groovy syntax in <code>application.groovy</code> as follows:<p class="paragraph"/><div class="code"><pre>dataSource { |
| pooled = <span class="java-keyword">false</span> |
| driverClassName = <span class="java-quote">"org.h2.Driver"</span> |
| username = <span class="java-quote">"sa"</span> |
| password = <span class="java-quote">""</span> |
| } |
| environments { |
| development { |
| dataSource { |
| dbCreate = <span class="java-quote">"create-drop"</span> |
| url = <span class="java-quote">"jdbc:h2:mem:devDb"</span> |
| } |
| } |
| test { |
| dataSource { |
| dbCreate = <span class="java-quote">"update"</span> |
| url = <span class="java-quote">"jdbc:h2:mem:testDb"</span> |
| } |
| } |
| production { |
| dataSource { |
| dbCreate = <span class="java-quote">"update"</span> |
| url = <span class="java-quote">"jdbc:h2:prodDb"</span> |
| } |
| } |
| }</pre></div><p class="paragraph"/>Notice how the common configuration is provided at the top level and then an <code>environments</code> block specifies per environment settings for the <code>dbCreate</code> and <code>url</code> properties of the <code>DataSource</code>.<p class="paragraph"/><h4>Packaging and Running for Different Environments</h4><p class="paragraph"/>Grails' <a href="../guide/single.html#commandLine" class="guide">command line</a> has built in capabilities to execute any command within the context of a specific environment. The format is:<p class="paragraph"/><div class="code"><pre>grails [environment] [command name]</pre></div><p class="paragraph"/>In addition, there are 3 preset environments known to Grails: <code>dev</code>, <code>prod</code>, and <code>test</code> for <code>development</code>, <code>production</code> and <code>test</code>. For example to create a WAR for the <code>test</code> environment you wound run:<p class="paragraph"/><div class="code"><pre>grails test war</pre></div><p class="paragraph"/>To target other environments you can pass a <code>grails.env</code> variable to any command:<p class="paragraph"/><div class="code"><pre>grails -Dgrails.env=UAT run-app</pre></div><p class="paragraph"/><h4>Programmatic Environment Detection</h4><p class="paragraph"/>Within your code, such as in a Gant script or a bootstrap class you can detect the environment using the <a href="http://grails.org/doc/3.0.x/api/grails/util/Environment.html" class="api">Environment</a> class:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.util.Environment<p class="paragraph"/>...<p class="paragraph"/><span class="java-keyword">switch</span> (Environment.current) { |
| <span class="java-keyword">case</span> Environment.DEVELOPMENT: |
| configureForDevelopment() |
| <span class="java-keyword">break</span> |
| <span class="java-keyword">case</span> Environment.PRODUCTION: |
| configureForProduction() |
| <span class="java-keyword">break</span> |
| }</pre></div><p class="paragraph"/><h4>Per Environment Bootstrapping</h4><p class="paragraph"/>It's often desirable to run code when your application starts up on a per-environment basis. To do so you can use the <code>grails-app/conf/BootStrap.groovy</code> file's support for per-environment execution:<p class="paragraph"/><div class="code"><pre>def init = { ServletContext ctx -> |
| environments { |
| production { |
| ctx.setAttribute(<span class="java-quote">"env"</span>, <span class="java-quote">"prod"</span>) |
| } |
| development { |
| ctx.setAttribute(<span class="java-quote">"env"</span>, <span class="java-quote">"dev"</span>) |
| } |
| } |
| ctx.setAttribute(<span class="java-quote">"foo"</span>, <span class="java-quote">"bar"</span>) |
| }</pre></div><p class="paragraph"/><h4>Generic Per Environment Execution</h4><p class="paragraph"/>The previous <code>BootStrap</code> example uses the <code>grails.util.Environment</code> class internally to execute. You can also use this class yourself to execute your own environment specific logic:<p class="paragraph"/><div class="code"><pre>Environment.executeForCurrentEnvironment { |
| production { |
| // <span class="java-keyword">do</span> something in production |
| } |
| development { |
| // <span class="java-keyword">do</span> something only in development |
| } |
| }</pre></div> |
| |
| |
| <a name="3.3 The DataSource"><!-- Legacy link --></a> |
| <h2 id="dataSource">4.4 The DataSource</h2> |
| Since Grails is built on Java technology setting up a data source requires some knowledge of JDBC (the technology that doesn't stand for Java Database Connectivity).<p class="paragraph"/>If you use a database other than H2 you need a JDBC driver. For example for MySQL you would need <a href="http://www.mysql.com/downloads/connector/j/" target="blank">Connector/J</a><p class="paragraph"/>Drivers typically come in the form of a JAR archive. It's best to use the dependency resolution to resolve the jar if it's available in a Maven repository, for example you could add a dependency for the MySQL driver like this:<p class="paragraph"/><div class="code"><pre>dependencies { |
| runtime 'mysql:mysql-connector-java:5.1.29' |
| }</pre></div><p class="paragraph"/>If you can't use dependency resolution then just put the JAR in your project's <code>lib</code> directory.<p class="paragraph"/>Once you have the JAR resolved you need to get familiar Grails' DataSource descriptor file located at <code>grails-app/conf/DataSource.groovy</code>. This file contains the dataSource definition which includes the following settings: |
| <ul class="star"> |
| <li><code>driverClassName</code> - The class name of the JDBC driver</li> |
| <li><code>username</code> - The username used to establish a JDBC connection</li> |
| <li><code>password</code> - The password used to establish a JDBC connection</li> |
| <li><code>url</code> - The JDBC URL of the database</li> |
| <li><code>dbCreate</code> - Whether to auto-generate the database from the domain model - one of 'create-drop', 'create', 'update' or 'validate'</li> |
| <li><code>pooled</code> - Whether to use a pool of connections (defaults to true)</li> |
| <li><code>logSql</code> - Enable SQL logging to stdout</li> |
| <li><code>formatSql</code> - Format logged SQL</li> |
| <li><code>dialect</code> - A String or Class that represents the Hibernate dialect used to communicate with the database. See the <a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/dialect/package-summary.html" target="blank">org.hibernate.dialect</a> package for available dialects.</li> |
| <li><code>readOnly</code> - If <code>true</code> makes the DataSource read-only, which results in the connection pool calling <code>setReadOnly(true)</code> on each <code>Connection</code></li> |
| <li><code>transactional</code> - If <code>false</code> leaves the DataSource's transactionManager bean outside the chained BE1PC transaction manager implementation. This only applies to additional datasources.</li> |
| <li><code>persistenceInterceptor</code> - The default datasource is automatically wired up to the persistence interceptor, other datasources are not wired up automatically unless this is set to <code>true</code></li> |
| <li><code>properties</code> - Extra properties to set on the DataSource bean. See the <a href="http://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html#Common_Attributes" target="blank">Tomcat Pool</a> documentation. There is also a Javadoc format <a href="https://tomcat.apache.org/tomcat-7.0-doc/api/org/apache/tomcat/jdbc/pool/PoolConfiguration.html" target="blank">documentation of the properties</a>.</li> |
| <li><code>jmxExport</code> - If <code>false</code>, will disable registration of JMX MBeans for all DataSources. By default JMX MBeans are added for DataSources with <code>jmxEnabled = true</code> in properties.</li> |
| </ul><p class="paragraph"/>A typical configuration for MySQL may be something like:<p class="paragraph"/><div class="code"><pre>dataSource { |
| pooled = <span class="java-keyword">true</span> |
| dbCreate = <span class="java-quote">"update"</span> |
| url = <span class="java-quote">"jdbc:mysql://localhost:3306/my_database"</span> |
| driverClassName = <span class="java-quote">"com.mysql.jdbc.Driver"</span> |
| dialect = org.hibernate.dialect.MySQL5InnoDBDialect |
| username = <span class="java-quote">"username"</span> |
| password = <span class="java-quote">"password"</span> |
| properties { |
| jmxEnabled = <span class="java-keyword">true</span> |
| initialSize = 5 |
| maxActive = 50 |
| minIdle = 5 |
| maxIdle = 25 |
| maxWait = 10000 |
| maxAge = 10 * 60000 |
| timeBetweenEvictionRunsMillis = 5000 |
| minEvictableIdleTimeMillis = 60000 |
| validationQuery = <span class="java-quote">"SELECT 1"</span> |
| validationQueryTimeout = 3 |
| validationInterval = 15000 |
| testOnBorrow = <span class="java-keyword">true</span> |
| testWhileIdle = <span class="java-keyword">true</span> |
| testOnReturn = <span class="java-keyword">false</span> |
| jdbcInterceptors = <span class="java-quote">"ConnectionState;StatementCache(max=200)"</span> |
| defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED |
| } |
| }</pre></div><p class="paragraph"/><blockquote class="warning"> |
| When configuring the DataSource do not include the type or the def keyword before any of the configuration settings as Groovy will treat these as local variable definitions and they will not be processed. For example the following is invalid: |
| </blockquote><p class="paragraph"/><div class="code"><pre>dataSource { |
| <span class="java-object">boolean</span> pooled = <span class="java-keyword">true</span> // type declaration results in ignored local variable |
| … |
| }</pre></div><p class="paragraph"/>Example of advanced configuration using extra properties: |
| <div class="code"><pre>dataSource { |
| pooled = <span class="java-keyword">true</span> |
| dbCreate = <span class="java-quote">"update"</span> |
| url = <span class="java-quote">"jdbc:mysql://localhost:3306/my_database"</span> |
| driverClassName = <span class="java-quote">"com.mysql.jdbc.Driver"</span> |
| dialect = org.hibernate.dialect.MySQL5InnoDBDialect |
| username = <span class="java-quote">"username"</span> |
| password = <span class="java-quote">"password"</span> |
| properties { |
| // Documentation <span class="java-keyword">for</span> Tomcat JDBC Pool |
| // http://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html#Common_Attributes |
| // https://tomcat.apache.org/tomcat-7.0-doc/api/org/apache/tomcat/jdbc/pool/PoolConfiguration.html |
| jmxEnabled = <span class="java-keyword">true</span> |
| initialSize = 5 |
| maxActive = 50 |
| minIdle = 5 |
| maxIdle = 25 |
| maxWait = 10000 |
| maxAge = 10 * 60000 |
| timeBetweenEvictionRunsMillis = 5000 |
| minEvictableIdleTimeMillis = 60000 |
| validationQuery = <span class="java-quote">"SELECT 1"</span> |
| validationQueryTimeout = 3 |
| validationInterval = 15000 |
| testOnBorrow = <span class="java-keyword">true</span> |
| testWhileIdle = <span class="java-keyword">true</span> |
| testOnReturn = <span class="java-keyword">false</span> |
| ignoreExceptionOnPreLoad = <span class="java-keyword">true</span> |
| // http://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html#JDBC_interceptors |
| jdbcInterceptors = <span class="java-quote">"ConnectionState;StatementCache(max=200)"</span> |
| defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED // safe <span class="java-keyword">default</span> |
| // controls <span class="java-keyword">for</span> leaked connections |
| abandonWhenPercentageFull = 100 // settings are active only when pool is full |
| removeAbandonedTimeout = 120 |
| removeAbandoned = <span class="java-keyword">true</span> |
| // use JMX console to change <span class="java-keyword">this</span> setting at runtime |
| logAbandoned = <span class="java-keyword">false</span> // causes stacktrace recording overhead, use only <span class="java-keyword">for</span> debugging |
| // JDBC driver properties |
| // Mysql as example |
| dbProperties { |
| // Mysql specific driver properties |
| // http://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html |
| // let Tomcat JDBC Pool handle reconnecting |
| autoReconnect=<span class="java-keyword">false</span> |
| // truncation behaviour |
| jdbcCompliantTruncation=<span class="java-keyword">false</span> |
| // mysql 0-date conversion |
| zeroDateTimeBehavior='convertToNull' |
| // Tomcat JDBC Pool's StatementCache is used instead, so disable mysql driver's cache |
| cachePrepStmts=<span class="java-keyword">false</span> |
| cacheCallableStmts=<span class="java-keyword">false</span> |
| // Tomcat JDBC Pool's StatementFinalizer keeps track |
| dontTrackOpenResources=<span class="java-keyword">true</span> |
| // performance optimization: reduce number of SQLExceptions thrown in mysql driver code |
| holdResultsOpenOverStatementClose=<span class="java-keyword">true</span> |
| // enable MySQL query cache - using server prep stmts will disable query caching |
| useServerPrepStmts=<span class="java-keyword">false</span> |
| // metadata caching |
| cacheServerConfiguration=<span class="java-keyword">true</span> |
| cacheResultSetMetadata=<span class="java-keyword">true</span> |
| metadataCacheSize=100 |
| // timeouts <span class="java-keyword">for</span> TCP/IP |
| connectTimeout=15000 |
| socketTimeout=120000 |
| // timer tuning (disable) |
| maintainTimeStats=<span class="java-keyword">false</span> |
| enableQueryTimeouts=<span class="java-keyword">false</span> |
| // misc tuning |
| noDatetimeStringSync=<span class="java-keyword">true</span> |
| } |
| } |
| }</pre></div><p class="paragraph"/><h4>More on dbCreate</h4><p class="paragraph"/>Hibernate can automatically create the database tables required for your domain model. You have some control over when and how it does this through the <code>dbCreate</code> property, which can take these values: |
| <ul class="star"> |
| <li><strong class="bold">create</strong> - Drops the existing schema and creates the schema on startup, dropping existing tables, indexes, etc. first.</li> |
| <li><strong class="bold">create-drop</strong> - Same as <strong class="bold">create</strong>, but also drops the tables when the application shuts down cleanly.</li> |
| <li><strong class="bold">update</strong> - Creates missing tables and indexes, and updates the current schema without dropping any tables or data. Note that this can't properly handle many schema changes like column renames (you're left with the old column containing the existing data).</li> |
| <li><strong class="bold">validate</strong> - Makes no changes to your database. Compares the configuration with the existing database schema and reports warnings.</li> |
| <li>any other value - does nothing</li> |
| </ul><p class="paragraph"/>You can also remove the <code>dbCreate</code> setting completely, which is recommended once your schema is relatively stable and definitely when your application and database are deployed in production. Database changes are then managed through proper migrations, either with SQL scripts or a migration tool like <a href="http://www.liquibase.org/" target="blank">Liquibase</a> (the <a href="http://grails.org/plugin/database-migration" target="blank">Database Migration</a> plugin uses Liquibase and is tightly integrated with Grails and GORM). |
| |
| |
| <a name="3.3.1 DataSources and Environments"><!-- Legacy link --></a> |
| <h2 id="dataSourcesAndEnvironments">4.4.1 DataSources and Environments</h2> |
| The previous example configuration assumes you want the same config for all environments: production, test, development etc.<p class="paragraph"/>Grails' DataSource definition is "environment aware", however, so you can do:<p class="paragraph"/><div class="code"><pre>dataSource { |
| pooled = <span class="java-keyword">true</span> |
| driverClassName = <span class="java-quote">"com.mysql.jdbc.Driver"</span> |
| dialect = org.hibernate.dialect.MySQL5InnoDBDialect |
| // other common settings here |
| }<p class="paragraph"/>environments { |
| production { |
| dataSource { |
| url = <span class="java-quote">"jdbc:mysql://liveip.com/liveDb"</span> |
| // other environment-specific settings here |
| } |
| } |
| }</pre></div> |
| |
| |
| <a name="3.3.3 Automatic Database Migration"><!-- Legacy link --></a> |
| <h2 id="automaticDatabaseMigration">4.4.2 Automatic Database Migration</h2> |
| The <code>dbCreate</code> property of the <code>DataSource</code> definition is important as it dictates what Grails should do at runtime with regards to automatically generating the database tables from <a href="../guide/single.html#GORM" class="guide">GORM</a> classes. The options are described in the <a href="../guide/single.html#dataSource" class="guide">DataSource</a> section: |
| <ul class="star"> |
| <li><code>create</code></li> |
| <li><code>create-drop</code></li> |
| <li><code>update</code></li> |
| <li><code>validate</code></li> |
| <li>no value</li> |
| </ul><p class="paragraph"/>In <a href="../guide/single.html#environments" class="guide">development</a> mode <code>dbCreate</code> is by default set to "create-drop", but at some point in development (and certainly once you go to production) you'll need to stop dropping and re-creating the database every time you start up your server.<p class="paragraph"/>It's tempting to switch to <code>update</code> so you retain existing data and only update the schema when your code changes, but Hibernate's update support is very conservative. It won't make any changes that could result in data loss, and doesn't detect renamed columns or tables, so you'll be left with the old one and will also have the new one.<p class="paragraph"/>Grails supports migrations with Flyway or Liquibase using the <a href="http://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html" target="blank">same mechanism provided by Spring Boot</a>. |
| |
| |
| <a name="3.3.4 Transaction-aware DataSource Proxy"><!-- Legacy link --></a> |
| <h2 id="transactionAwareDataSourceProxy">4.4.3 Transaction-aware DataSource Proxy</h2> |
| The actual <code>dataSource</code> bean is wrapped in a transaction-aware proxy so you will be given the connection that's being used by the current transaction or Hibernate <code>Session</code> if one is active.<p class="paragraph"/>If this were not the case, then retrieving a connection from the <code>dataSource</code> would be a new connection, and you wouldn't be able to see changes that haven't been committed yet (assuming you have a sensible transaction isolation setting, e.g. <code>READ_COMMITTED</code> or better).<p class="paragraph"/>The "real" unproxied <code>dataSource</code> is still available to you if you need access to it; its bean name is <code>dataSourceUnproxied</code>.<p class="paragraph"/>You can access this bean like any other Spring bean, i.e. using dependency injection:<p class="paragraph"/><div class="code"><pre>class MyService {<p class="paragraph"/> def dataSourceUnproxied |
| … |
| }</pre></div><p class="paragraph"/>or by pulling it from the <code>ApplicationContext</code>:<p class="paragraph"/><div class="code"><pre>def dataSourceUnproxied = ctx.dataSourceUnproxied</pre></div> |
| |
| |
| <a name="3.3.5 Database Console"><!-- Legacy link --></a> |
| <h2 id="databaseConsole">4.4.4 Database Console</h2> |
| The <a href="http://h2database.com/html/quickstart.html#h2_console" target="blank">H2 database console</a> is a convenient feature of H2 that provides a web-based interface to any database that you have a JDBC driver for, and it's very useful to view the database you're developing against. It's especially useful when running against an in-memory database.<p class="paragraph"/>You can access the console by navigating to <strong class="bold">http://localhost:8080/appname/dbconsole</strong> in a browser. The URI can be configured using the <code>grails.dbconsole.urlRoot</code> attribute in Config.groovy and defaults to <code>'/dbconsole'</code>.<p class="paragraph"/>The console is enabled by default in development mode and can be disabled or enabled in other environments by using the <code>grails.dbconsole.enabled</code> attribute in Config.groovy. For example you could enable the console in production using<p class="paragraph"/><div class="code"><pre>environments { |
| production { |
| grails.serverURL = <span class="java-quote">"http://www.changeme.com"</span> |
| grails.dbconsole.enabled = <span class="java-keyword">true</span> |
| grails.dbconsole.urlRoot = '/admin/dbconsole' |
| } |
| development { |
| grails.serverURL = <span class="java-quote">"http://localhost:8080/${appName}"</span> |
| } |
| test { |
| grails.serverURL = <span class="java-quote">"http://localhost:8080/${appName}"</span> |
| } |
| }</pre></div><p class="paragraph"/><blockquote class="warning"> |
| If you enable the console in production be sure to guard access to it using a trusted security framework. |
| </blockquote><p class="paragraph"/><h4>Configuration</h4><p class="paragraph"/>By default the console is configured for an H2 database which will work with the default settings if you haven't configured an external database - you just need to change the JDBC URL to <code>jdbc:h2:mem:devDB</code>. If you've configured an external database (e.g. MySQL, Oracle, etc.) then you can use the Saved Settings dropdown to choose a settings template and fill in the url and username/password information from your DataSource.groovy. |
| |
| |
| <a name="3.3.6 Multiple Datasources"><!-- Legacy link --></a> |
| <h2 id="multipleDatasources">4.4.5 Multiple Datasources</h2> |
| By default all domain classes share a single <code>DataSource</code> and a single database, but you have the option to partition your domain classes into two or more <code>DataSource</code>s.<p class="paragraph"/><h4>Configuring Additional DataSources</h4><p class="paragraph"/>The default <code>DataSource</code> configuration in <code>grails-app/conf/DataSource.groovy</code> looks something like this:<p class="paragraph"/><div class="code"><pre>--- |
| dataSource: |
| pooled: <span class="java-keyword">true</span> |
| jmxExport: <span class="java-keyword">true</span> |
| driverClassName: org.h2.Driver |
| username: sa |
| password:<p class="paragraph"/>environments: |
| development: |
| dataSource: |
| dbCreate: create-drop |
| url: jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE |
| test: |
| dataSource: |
| dbCreate: update |
| url: jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE |
| production: |
| dataSource: |
| dbCreate: update |
| url: jdbc:h2:prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE |
| properties: |
| jmxEnabled: <span class="java-keyword">true</span> |
| initialSize: 5</pre></div><p class="paragraph"/>This configures a single <code>DataSource</code> with the Spring bean named <code>dataSource</code>. To configure extra <code>DataSource</code>s, add a <code>dataSources</code> block (at the top level, in an environment block, or both, just like the standard <code>DataSource</code> definition) with a custom name. For example, this configuration adds a second <code>DataSource</code>, using MySQL in the development environment and Oracle in production:<p class="paragraph"/><div class="code"><pre>--- |
| dataSources: |
| dataSource: |
| pooled: <span class="java-keyword">true</span> |
| jmxExport: <span class="java-keyword">true</span> |
| driverClassName: org.h2.Driver |
| username: sa |
| password: |
| lookup: |
| dialect: org.hibernate.dialect.MySQLInnoDBDialect |
| driverClassName: com.mysql.jdbc.Driver |
| username: lookup |
| password: secret |
| url: jdbc:mysql://localhost/lookup |
| dbCreate: update<p class="paragraph"/>environments: |
| development: |
| dataSources: |
| dataSource: |
| dbCreate: create-drop |
| url: jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE |
| test: |
| dataSources: |
| dataSource: |
| dbCreate: update |
| url: jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE |
| production: |
| dataSources: |
| dataSource: |
| dbCreate: update |
| url: jdbc:h2:prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE |
| properties: |
| jmxEnabled: <span class="java-keyword">true</span> |
| initialSize: 5 |
| … |
| lookup: |
| dialect: org.hibernate.dialect.Oracle10gDialect |
| driverClassName: oracle.jdbc.driver.OracleDriver |
| username: lookup |
| password: secret |
| url: jdbc:oracle:thin:@localhost:1521:lookup |
| dbCreate: update</pre></div><p class="paragraph"/>You can use the same or different databases as long as they're supported by Hibernate.<p class="paragraph"/><h4>Configuring Domain Classes</h4><p class="paragraph"/>If a domain class has no <code>DataSource</code> configuration, it defaults to the standard <code>'dataSource'</code>. Set the <code>datasource</code> property in the <code>mapping</code> block to configure a non-default <code>DataSource</code>. For example, if you want to use the <code>ZipCode</code> domain to use the <code>'lookup'</code> <code>DataSource</code>, configure it like this;<p class="paragraph"/><div class="code"><pre>class ZipCode {<p class="paragraph"/> <span class="java-object">String</span> code<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| datasource 'lookup' |
| } |
| }</pre></div><p class="paragraph"/>A domain class can also use two or more <code>DataSource</code>s. Use the <code>datasources</code> property with a list of names to configure more than one, for example:<p class="paragraph"/><div class="code"><pre>class ZipCode {<p class="paragraph"/> <span class="java-object">String</span> code<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| datasources(['lookup', 'auditing']) |
| } |
| }</pre></div><p class="paragraph"/>If a domain class uses the default <code>DataSource</code> and one or more others, use the special name <code>'DEFAULT'</code> to indicate the default <code>DataSource</code>:<p class="paragraph"/><div class="code"><pre>class ZipCode {<p class="paragraph"/> <span class="java-object">String</span> code<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| datasources(['lookup', 'DEFAULT']) |
| } |
| }</pre></div><p class="paragraph"/>If a domain class uses all configured <code>DataSource</code>s use the special value <code>'ALL'</code>:<p class="paragraph"/><div class="code"><pre>class ZipCode {<p class="paragraph"/> <span class="java-object">String</span> code<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| datasource 'ALL' |
| } |
| }</pre></div><p class="paragraph"/><h4>Namespaces and GORM Methods</h4><p class="paragraph"/>If a domain class uses more than one <code>DataSource</code> then you can use the namespace implied by each <code>DataSource</code> name to make GORM calls for a particular <code>DataSource</code>. For example, consider this class which uses two <code>DataSource</code>s:<p class="paragraph"/><div class="code"><pre>class ZipCode {<p class="paragraph"/> <span class="java-object">String</span> code<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| datasources(['lookup', 'auditing']) |
| } |
| }</pre></div><p class="paragraph"/>The first <code>DataSource</code> specified is the default when not using an explicit namespace, so in this case we default to 'lookup'. But you can call GORM methods on the 'auditing' <code>DataSource</code> with the <code>DataSource</code> name, for example:<p class="paragraph"/><div class="code"><pre>def zipCode = ZipCode.auditing.get(42) |
| … |
| zipCode.auditing.save()</pre></div><p class="paragraph"/>As you can see, you add the <code>DataSource</code> to the method call in both the static case and the instance case.<p class="paragraph"/><h4>Hibernate Mapped Domain Classes</h4><p class="paragraph"/>You can also partition annotated Java classes into separate datasources. Classes using the default datasource are registered in <code>grails-app/conf/hibernate/hibernate.cfg.xml</code>. To specify that an annotated class uses a non-default datasource, create a <code>hibernate.cfg.xml</code> file for that datasource with the file name prefixed with the datasource name.<p class="paragraph"/>For example if the <code>Book</code> class is in the default datasource, you would register that in <code>grails-app/conf/hibernate/hibernate.cfg.xml</code>:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><?xml version='1.0' encoding='UTF-8'?></span> |
| <!DOCTYPE hibernate-configuration PUBLIC |
| '-//Hibernate/Hibernate Configuration DTD 3.0//EN' |
| 'http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd'> |
| <span class="xml-tag"><hibernate-configuration></span> |
| <span class="xml-tag"><session-factory></span> |
| <span class="xml-tag"><mapping class='org.example.Book'/></span> |
| <span class="xml-tag"></session-factory></span> |
| <span class="xml-tag"></hibernate-configuration></span></pre></div><p class="paragraph"/>and if the <code>Library</code> class is in the "ds2" datasource, you would register that in <code>grails-app/conf/hibernate/ds2_hibernate.cfg.xml</code>:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><?xml version='1.0' encoding='UTF-8'?></span> |
| <!DOCTYPE hibernate-configuration PUBLIC |
| '-//Hibernate/Hibernate Configuration DTD 3.0//EN' |
| 'http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd'> |
| <span class="xml-tag"><hibernate-configuration></span> |
| <span class="xml-tag"><session-factory></span> |
| <span class="xml-tag"><mapping class='org.example.Library'/></span> |
| <span class="xml-tag"></session-factory></span> |
| <span class="xml-tag"></hibernate-configuration></span></pre></div><p class="paragraph"/>The process is the same for classes mapped with hbm.xml files - just list them in the appropriate hibernate.cfg.xml file.<p class="paragraph"/><h4>Services</h4><p class="paragraph"/>Like Domain classes, by default Services use the default <code>DataSource</code> and <code>PlatformTransactionManager</code>. To configure a Service to use a different <code>DataSource</code>, use the static <code>datasource</code> property, for example:<p class="paragraph"/><div class="code"><pre>class DataService {<p class="paragraph"/> <span class="java-keyword">static</span> datasource = 'lookup'<p class="paragraph"/> void someMethod(...) { |
| … |
| } |
| }</pre></div><p class="paragraph"/>A transactional service can only use a single <code>DataSource</code>, so be sure to only make changes for domain classes whose <code>DataSource</code> is the same as the Service.<p class="paragraph"/>Note that the datasource specified in a service has no bearing on which datasources are used for domain classes; that's determined by their declared datasources in the domain classes themselves. It's used to declare which transaction manager to use.<p class="paragraph"/>What you'll see is that if you have a Foo domain class in dataSource1 and a Bar domain class in dataSource2, and WahooService uses dataSource1, a service method that saves a new Foo and a new Bar will only be transactional for Foo since they share the datasource. The transaction won't affect the Bar instance. If you want both to be transactional you'd need to use two services and XA datasources for two-phase commit, e.g. with the Atomikos plugin.<p class="paragraph"/><h4>Transactions across multiple datasources </h4><p class="paragraph"/>Grails uses the Best Efforts 1PC pattern for handling transactions across multiple datasources.<p class="paragraph"/>The <a href="http://www.javaworld.com/article/2077963/open-source-tools/distributed-transactions-in-spring--with-and-without-xa.html?page=2" target="blank">Best Efforts 1PC pattern</a> is fairly general but can fail in some circumstances that the developer must be aware of. This is a non-XA pattern that involves a synchronized single-phase commit of a number of resources. Because the <a href="https://en.wikipedia.org/wiki/Two-phase_commit" target="blank">2PC</a> is not used, it can never be as safe as an <a href="https://en.wikipedia.org/wiki/X/Open_XA" target="blank">XA</a> transaction, but is often good enough if the participants are aware of the compromises.<p class="paragraph"/>The basic idea is to delay the commit of all resources as late as possible in a transaction so that the only thing that can go wrong is an infrastructure failure (not a business-processing error). Systems that rely on Best Efforts 1PC reason that infrastructure failures are rare enough that they can afford to take the risk in return for higher throughput. If business-processing services are also designed to be idempotent, then little can go wrong in practice.<p class="paragraph"/>The BE1PC implementation was added in Grails 2.3.6. . Before this change additional datasources didn't take part in transactions initiated in Grails. The transactions in additional datasources were basically in auto commit mode. In some cases this might be the wanted behavior. One reason might be performance: on the start of each new transaction, the BE1PC transaction manager creates a new transaction to each datasource. It's possible to leave an additional datasource out of the BE1PC transaction manager by setting <code>transactional = false</code> in the respective configuration block of the additional dataSource. Datasources with <code>readOnly = true</code> will also be left out of the chained transaction manager (since 2.3.7).<p class="paragraph"/>By default, the BE1PC implementation will add all beans implementing the Spring <code><a href="http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/transaction/PlatformTransactionManager.html" target="blank">PlatformTransactionManager</a></code> interface to the chained BE1PC transaction manager. For example, a possible <code><a href="http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/jms/connection/JmsTransactionManager.html" target="blank">JMSTransactionManager</a></code> bean in the Grails application context would be added to the Grails BE1PC transaction manager's chain of transaction managers.<p class="paragraph"/>You can exclude transaction manager beans from the BE1PC implementation with the this configuration option: |
| <div class="code"><pre>grails.transaction.chainedTransactionManagerPostProcessor.blacklistPattern = '.*'</pre></div> |
| The exclude matching is done on the name of the transaction manager bean. The transaction managers of datasources with <code>transactional = false</code> or <code>readOnly = true</code> will be skipped and using this configuration option is not required in that case.<p class="paragraph"/><h4>XA and Two-phase Commit</h4><p class="paragraph"/>When the Best Efforts 1PC pattern isn't suitable for handling transactions across multiple transactional resources (not only datasources), there are several options available for adding XA/2PC support to Grails applications.<p class="paragraph"/>The <a href="http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/transaction.html#transaction-application-server-integration" target="blank">Spring transactions documentation</a> contains information about integrating the JTA/XA transaction manager of different application servers. In this case, you can configure a bean with the name <code>transactionManager</code> manually in <code>resources.groovy</code> or <code>resources.xml</code> file.<p class="paragraph"/>There is also <a href="http://grails.org/plugin/atomikos" target="blank">Atomikos plugin</a> available for XA support in Grails applications. |
| |
| <a name="3.5 Versioning"><!-- Legacy link --></a> |
| <h2 id="versioning">4.5 Versioning</h2> |
| <h4>Detecting Versions at Runtime</h4><p class="paragraph"/>You can detect the application version using Grails' support for application metadata using the <a href="http://grails.org/doc/3.0.x/api/grails/core/GrailsApplication.html" class="api">GrailsApplication</a> class. For example within <a href="../guide/single.html#controllers" class="guide">controllers</a> there is an implicit <a href="../ref/Controllers/grailsApplication.html" class="controllers">grailsApplication</a> variable that can be used:<p class="paragraph"/><div class="code"><pre>def version = grailsApplication.metadata.getApplicationVersion()</pre></div><p class="paragraph"/>You can retrieve the version of Grails that is running with:<p class="paragraph"/><div class="code"><pre>def grailsVersion = grailsApplication.metadata.getGrailsVersion()</pre></div><p class="paragraph"/>or the <code>GrailsUtil</code> class:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.util.GrailsUtil |
| … |
| def grailsVersion = GrailsUtil.grailsVersion</pre></div> |
| |
| |
| <a name="3.6 Project Documentation"><!-- Legacy link --></a> |
| <h2 id="docengine">4.6 Project Documentation</h2> |
| Since Grails 1.2, the documentation engine that powers the creation of this documentation has been available for your own Grails projects.<p class="paragraph"/>The documentation engine uses a variation on the <a href="http://textile.sitemonks.com/" target="blank">Textile</a> syntax to automatically create project documentation with smart linking, formatting etc.<p class="paragraph"/><h4>Creating project documentation</h4><p class="paragraph"/>To use the engine you need to follow a few conventions. First, you need to create a <code>src/docs/guide</code> directory where your documentation source files will go. Then, you need to create the source docs themselves. Each chapter should have its own gdoc file as should all numbered sub-sections. You will end up with something like:<p class="paragraph"/><div class="code"><pre>+ src/docs/guide/introduction.gdoc |
| + src/docs/guide/introduction/changes.gdoc |
| + src/docs/guide/gettingStarted.gdoc |
| + src/docs/guide/configuration.gdoc |
| + src/docs/guide/configuration/build.gdoc |
| + src/docs/guide/configuration/build/controllers.gdoc</pre></div><p class="paragraph"/>Note that you can have all your gdoc files in the top-level directory if you want, but you can also put sub-sections in sub-directories named after the parent section - as the above example shows.<p class="paragraph"/>Once you have your source files, you still need to tell the documentation engine what the structure of your user guide is going to be. To do that, you add a <code>src/docs/guide/toc.yml</code> file that contains the structure and titles for each section. This file is in <a href="http://www.yaml.org/" target="blank">YAML</a> format and basically represents the structure of the user guide in tree form. For example, the above files could be represented as:<p class="paragraph"/><div class="code"><pre>introduction: |
| title: Introduction |
| changes: Change Log |
| gettingStarted: Getting Started |
| configuration: |
| title: Configuration |
| build: |
| title: Build Config |
| controllers: Specifying Controllers</pre></div><p class="paragraph"/>The format is pretty straightforward. Any section that has sub-sections is represented with the corresponding filename (minus the .gdoc extension) followed by a colon. The next line should contain <code>title:</code> plus the title of the section as seen by the end user. Every sub-section then has its own line after the title. Leaf nodes, i.e. those without any sub-sections, declare their title on the same line as the section name but after the colon.<p class="paragraph"/>That's it. You can easily add, remove, and move sections within the <code>toc.yml</code> to restructure the generated user guide. You should also make sure that all section names, i.e. the gdoc filenames, should be unique since they are used for creating internal links and for the HTML filenames. Don't worry though, the documentation engine will warn you of duplicate section names.<p class="paragraph"/><h4>Creating reference items</h4><p class="paragraph"/>Reference items appear in the Quick Reference section of the documentation. Each reference item belongs to a category and a category is a directory located in the <code>src/docs/ref</code> directory. For example, suppose you have defined a new controller method called <code>renderPDF</code>. That belongs to the <code>Controllers</code> category so you would create a gdoc text file at the following location:<p class="paragraph"/><div class="code"><pre>+ src/docs/ref/Controllers/renderPDF.gdoc</pre></div><p class="paragraph"/><h4>Configuring Output Properties</h4><p class="paragraph"/>There are various properties you can set within your <code>grails-app/conf/Config.groovy</code> file that customize the output of the documentation such as: |
| <ul class="star"> |
| <li><strong class="bold">grails.doc.title</strong> - The title of the documentation</li> |
| <li><strong class="bold">grails.doc.subtitle</strong> - The subtitle of the documentation</li> |
| <li><strong class="bold">grails.doc.authors</strong> - The authors of the documentation</li> |
| <li><strong class="bold">grails.doc.license</strong> - The license of the software</li> |
| <li><strong class="bold">grails.doc.copyright</strong> - The copyright message to display</li> |
| <li><strong class="bold">grails.doc.footer</strong> - The footer to use</li> |
| </ul><p class="paragraph"/>Other properties such as the version are pulled from your project itself. If a title is not specified, the application name is used.<p class="paragraph"/>You can also customise the look of the documentation and provide images by setting a few other options: |
| <ul class="star"> |
| <li><strong class="bold">grails.doc.css</strong> - The location of a directory containing custom CSS files (type <code>java.io.File</code>)</li> |
| <li><strong class="bold">grails.doc.js</strong> - The location of a directory containing custom JavaScript files (type <code>java.io.File</code>)</li> |
| <li><strong class="bold">grails.doc.style</strong> - The location of a directory containing custom HTML templates for the guide (type <code>java.io.File</code>)</li> |
| <li><strong class="bold">grails.doc.images</strong> - The location of a directory containing image files for use in the style templates and within the documentation pages themselves (type <code>java.io.File</code>)</li> |
| </ul><p class="paragraph"/>One of the simplest ways to customise the look of the generated guide is to provide a value for <code>grails.doc.css</code> and then put a custom.css file in the corresponding directory. Grails will automatically include this CSS file in the guide. You can also place a custom-pdf.css file in that directory. This allows you to override the styles for the PDF version of the guide.<p class="paragraph"/><h4>Generating Documentation</h4><p class="paragraph"/>Once you have created some documentation (refer to the syntax guide in the next chapter) you can generate an HTML version of the documentation using the command:<p class="paragraph"/><div class="code"><pre>grails doc</pre></div><p class="paragraph"/>This command will output an <code>docs/manual/index.html</code> which can be opened in a browser to view your documentation.<p class="paragraph"/><h4>Documentation Syntax</h4><p class="paragraph"/>As mentioned the syntax is largely similar to Textile or Confluence style wiki markup. The following sections walk you through the syntax basics.<p class="paragraph"/><h5>Basic Formatting</h5><p class="paragraph"/>Monospace: <code>monospace</code> |
| <div class="code"><pre>@monospace@</pre></div><p class="paragraph"/>Italic: <em class="italic">italic</em> |
| <div class="code"><pre>_italic_</pre></div><p class="paragraph"/>Bold: <strong class="bold">bold</strong> |
| <div class="code"><pre>*bold*</pre></div><p class="paragraph"/>Image: |
| <img border="0" class="center" src="http://grails.org/images/new/grailslogo_topNav.png"></img><p class="paragraph"/><div class="code"><pre>!http://grails.org/images/new/grailslogo_topNav.png!</pre></div><p class="paragraph"/>You can also link to internal images like so:<p class="paragraph"/><div class="code"><pre>!someFolder/my_diagram.png!</pre></div><p class="paragraph"/>This will link to an image stored locally within your project. There is currently no default location for doc images, but you can specify one with the <code>grails.doc.images</code> setting in Config.groovy like so:<p class="paragraph"/><div class="code"><pre>grails.doc.images = <span class="java-keyword">new</span> File(<span class="java-quote">"src/docs/images"</span>)</pre></div><p class="paragraph"/>In this example, you would put the my_diagram.png file in the directory 'src/docs/images/someFolder'.<p class="paragraph"/><h5>Linking</h5><p class="paragraph"/>There are several ways to create links with the documentation generator. A basic external link can either be defined using confluence or textile style markup:<p class="paragraph"/><div class="code"><pre>[Pivotal|http://www.pivotal.io/oss]</pre></div><p class="paragraph"/>or<p class="paragraph"/><div class="code"><pre><span class="java-quote">"Pivotal"</span>:http://www.pivotal.io/oss</pre></div><p class="paragraph"/>For links to other sections inside the user guide you can use the <code>guide:</code> prefix with the name of the section you want to link to:<p class="paragraph"/><div class="code"><pre>[Intro|guide:introduction]</pre></div><p class="paragraph"/>The section name comes from the corresponding gdoc filename. The documentation engine will warn you if any links to sections in your guide break.<p class="paragraph"/>To link to reference items you can use a special syntax:<p class="paragraph"/><div class="code"><pre>[renderPDF|controllers]</pre></div><p class="paragraph"/>In this case the category of the reference item is on the right hand side of the | and the name of the reference item on the left.<p class="paragraph"/>Finally, to link to external APIs you can use the <code>api:</code> prefix. For example:<p class="paragraph"/><div class="code"><pre>[<span class="java-object">String</span>|api:java.lang.<span class="java-object">String</span>]</pre></div><p class="paragraph"/>The documentation engine will automatically create the appropriate javadoc link in this case. To add additional APIs to the engine you can configure them in <code>grails-app/conf/Config.groovy</code>. For example:<p class="paragraph"/><div class="code"><pre>grails.doc.api.org.hibernate= |
| <span class="java-quote">"http://docs.jboss.org/hibernate/stable/core/javadocs"</span></pre></div><p class="paragraph"/>The above example configures classes within the <code>org.hibernate</code> package to link to the Hibernate website's API docs.<p class="paragraph"/><h5>Lists and Headings</h5><p class="paragraph"/>Headings can be created by specifying the letter 'h' followed by a number and then a dot:<p class="paragraph"/><div class="code"><pre>h3.<space>Heading3 |
| h4.<space>Heading4</pre></div><p class="paragraph"/>Unordered lists are defined with the use of the * character:<p class="paragraph"/><div class="code"><pre>* item 1 |
| ** subitem 1 |
| ** subitem 2 |
| * item 2</pre></div><p class="paragraph"/>Numbered lists can be defined with the # character:<p class="paragraph"/><div class="code"><pre># item 1</pre></div><p class="paragraph"/>Tables can be created using the <code>table</code> macro:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th><strong class="bold">Name</strong></th><th><strong class="bold">Number</strong></th></tr><tr class="table-odd"><td>Albert</td><td>46</td></tr><tr class="table-even"><td>Wilma</td><td>1348</td></tr><tr class="table-odd"><td>James</td><td>12</td></tr></table><p class="paragraph"/><div class="code"><pre>{table} |
| *Name* | *<span class="java-object">Number</span>* |
| Albert | 46 |
| Wilma | 1348 |
| James | 12 |
| {table}</pre></div><p class="paragraph"/><h5>Code and Notes</h5><p class="paragraph"/>You can define code blocks with the <code>code</code> macro:<p class="paragraph"/><div class="code"><pre>class Book { |
| <span class="java-object">String</span> title |
| }</pre></div><p class="paragraph"/><div class="code"><pre>{code} |
| class Book { |
| <span class="java-object">String</span> title |
| } |
| {code}</pre></div><p class="paragraph"/>The example above provides syntax highlighting for Java and Groovy code, but you can also highlight XML markup:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><hello></span>world<span class="xml-tag"></hello></span></pre></div><p class="paragraph"/><div class="code"><pre>{code:xml} |
| <hello>world</hello> |
| {code}</pre></div><p class="paragraph"/>There are also a couple of macros for displaying notes and warnings:<p class="paragraph"/>Note: |
| <blockquote class="note"> |
| This is a note! |
| </blockquote><p class="paragraph"/><div class="code"><pre>{note} |
| This is a note! |
| {note}</pre></div><p class="paragraph"/>Warning:<p class="paragraph"/><blockquote class="warning"> |
| This is a warning! |
| </blockquote><p class="paragraph"/><div class="code"><pre>{warning} |
| This is a warning! |
| {warning}</pre></div> |
| |
| |
| <a name="3.7 Dependency Resolution"><!-- Legacy link --></a> |
| <h2 id="dependencyResolution">4.7 Dependency Resolution</h2> |
| Dependency resolution is handled by the <a href="http://gradle.org" target="blank">Gradle build tool</a>, all dependencies are defined in the <code>build.gradle</code> file. Refer to the <a href="https://www.gradle.org/documentation" target="blank">Gradle user guide</a> for more information. |
| |
| <a name="4. The Command Line"><!-- Legacy link --></a> |
| <h1 id="commandLine">5 The Command Line</h1> |
| Grails 3.0's command line system differs greatly from previous versions of Grails and features APIs for invoking Gradle for build related tasks, as well as performing code generation.<p class="paragraph"/>When you type:<p class="paragraph"/><div class="code"><pre>grails [command name]</pre></div><p class="paragraph"/>Grails searches the <a href="https://github.com/grails/grails-profile-repository" target="blank">profile repository</a> based on the profile of the current application. If the profile is for a web application then commmands a read from the web profile and the base profile which it inherits from.<p class="paragraph"/>Since command behavior is profile specific the web profile my provide different behavior for the <code>run-app</code> command then say a profile for running batch applications.<p class="paragraph"/>When you type the following command:<p class="paragraph"/><div class="code"><pre>grails run-app</pre></div><p class="paragraph"/>It results in a search for the following files: |
| <ul class="star"> |
| <li><code>PROJECT_HOME/scripts/RunApp.groovy</code></li> |
| <li><code>PROFILE_REPOSITORY_PATH/profiles/web/commands/run-app.groovy</code> (if the web profile is active)</li> |
| <li><code>PROFILE_REPOSITORY_PATH/profiles/web/commands/run-app.yml</code> (for YAML defined commands)</li> |
| </ul><p class="paragraph"/>To get a list of all commands and some help about the available commands type:<p class="paragraph"/><div class="code"><pre>grails help</pre></div><p class="paragraph"/>which outputs usage instructions and the list of commands Grails is aware of:<p class="paragraph"/><div class="code"><pre>grails [environment]* [target] [arguments]*'<p class="paragraph"/>| Examples: |
| $ grails dev run-app |
| $ grails create-app books<p class="paragraph"/>| Available Commands (type grails help 'command-name' <span class="java-keyword">for</span> more info): |
| | Command Name Command Description |
| ---------------------------------------------------------------------------------------------------- |
| clean Cleans a Grails application's compiled sources |
| compile Compiles a Grails application |
| ...</pre></div><p class="paragraph"/><blockquote class="note"> |
| Refer to the Command Line reference in the Quick Reference menu of the reference guide for more information about individual commands |
| </blockquote><p class="paragraph"/><h4>non-interactive mode</h4><p class="paragraph"/>When you run a script manually and it prompts you for information, you can answer the questions and continue running the script. But when you run a script as part of an automated process, for example a continuous integration build server, there's no way to "answer" the questions. So you can pass the <code>--non-interactive</code> switch to the script command to tell Grails to accept the default answer for any questions, for example whether to install a missing plugin.<p class="paragraph"/>For example:<p class="paragraph"/><div class="code"><pre>grails war --non-interactive</pre></div> |
| |
| |
| |
| <h2 id="interactiveMode">5.1 Interactive Mode</h2> |
| Interactive mode is the a feature of the Grails command line which keeps the JVM running and allows for quicker execution of commands. To activate interactive mode type 'grails' at the command line and then use TAB completion to get a list of commands:<p class="paragraph"/><img border="0" class="center" src="../img/interactive-output.png"></img><p class="paragraph"/>If you need to open a file whilst within interactive mode you can use the <code>open</code> command which will TAB complete file paths:<p class="paragraph"/><img border="0" class="center" src="../img/interactive-open-cmd.png"></img><p class="paragraph"/>Even better, the <code>open</code> command understands the logical aliases 'test-report' and 'dep-report', which will open the most recent test and dependency reports respectively. In other words, to open the test report in a browser simply execute <code>open test-report</code>. You can even open multiple files at once: <code>open test-report test/unit/MyTests.groovy</code> will open the HTML test report in your browser and the <code>MyTests.groovy</code> source file in your text editor.<p class="paragraph"/>TAB completion also works for class names after the <code>create-*</code> commands:<p class="paragraph"/><img border="0" class="center" src="../img/interactive-complete-class.png"></img><p class="paragraph"/>If you need to run an external process whilst interactive mode is running you can do so by starting the command with a !:<p class="paragraph"/><img border="0" class="center" src="../img/interactive-run-external.png"></img><p class="paragraph"/>Note that with ! (bang) commands, you get file path auto completion - ideal for external commands that operate on the file system such as 'ls', 'cat', 'git', etc.<p class="paragraph"/>To exit interactive mode enter the <code>exit</code> command. Note that if the Grails application has been run with <code>run-app</code> normally it will terminate when the interactive mode console exits because the JVM will be terminated. An exception to this would be if the application were running in forked mode which means the application is running in a different JVM. In that case the application will be left running after the interactive mode console terminates. If you want to exit interactive mode and stop an application that is running in forked mode, use the <code>quit</code> command. The <code>quit</code> command will stop the running application and then close interactive mode. |
| |
| |
| |
| <h2 id="profiles">5.2 The Command Line and Profiles</h2> |
| When you create a Grails application with the <a href="../ref/Command Line/create-app.html" class="commandLine">create-app</a> command by default the "web" profile is used:<p class="paragraph"/><div class="code"><pre>grails create-app myapp</pre></div><p class="paragraph"/>You can specify a different profile with the profile argument:<p class="paragraph"/><div class="code"><pre>grails create-app myapp --profile=web-plugin</pre></div><p class="paragraph"/>Profiles encapsulate the project commands, templates and plugins that are designed to work for a given profile. They are stored in the <a href="https://github.com/grails/grails-profile-repository" target="blank">Grails Profile Repository</a> on Github.<p class="paragraph"/>This repository is checked out locally and stored in the <code>USER_HOME/.grails/repository</code> directory.<p class="paragraph"/><h4>Understanding a Profile's Structure</h4><p class="paragraph"/>A profile is a simple directory that contains a <code>profile.yml</code> file and directorys containing the "commands", "skeleton" and "templates" defined by the profile. Example:<p class="paragraph"/><div class="code"><pre>web |
| * commands |
| * create-controller.yml |
| * run-app.groovy |
| … |
| * skeleton |
| * grails-app |
| * controllers |
| … |
| * build.gradle |
| * templates |
| * artifacts |
| * Controller.groovy |
| * profile.yml</pre></div><p class="paragraph"/>The above example is a snippet of structure of the 'web' profile. The <code>profile.yml</code> file is defined as follows:<p class="paragraph"/><div class="code"><pre>description: Profile <span class="java-keyword">for</span> Web applications |
| <span class="java-keyword">extends</span>: base</pre></div><p class="paragraph"/>As you can see it contains the description of the profile and a definition of which profiles this profile extends, since one profile can extend from another.<p class="paragraph"/>When the <code>create-app</code> command runs it takes the skeleton of the parent profiles and copies the skeletons into a new project structure. Child profiles overwrite files from the parent profile so if the parent defines a <code>build.gradle</code> then the child profile will override the parent.<p class="paragraph"/><h4>Defining Profile Commands</h4><p class="paragraph"/>A profile can define new commands that apply only to that profile using YAML or Groovy scripts. Below is an example of the <a href="../ref/Command Line/create-controller.html" class="commandLine">create-controller</a> command defined in YAML:<p class="paragraph"/><div class="code"><pre>description: |
| - Creates a controller |
| - usage: 'create-controller [controller name]' |
| - completer: org.grails.cli.interactive.completers.DomainClassCompleter |
| - argument: <span class="java-quote">"Controller Name"</span> |
| description: <span class="java-quote">"The name of the controller"</span> |
| steps: |
| - command: render |
| template: templates/artifacts/Controller.groovy |
| destination: grails-app/controllers/<code>artifact.<span class="java-keyword">package</span>.path</code>/<code>artifact.name</code>Controller.groovy |
| - command: render |
| template: templates/testing/Controller.groovy |
| destination: src/test/groovy/<code>artifact.<span class="java-keyword">package</span>.path</code>/<code>artifact.name</code>ControllerSpec.groovy |
| - command: mkdir |
| location: grails-app/views/<code>artifact.propertyName</code></pre></div><p class="paragraph"/>Commands defined in YAML must define one or many steps. Each step is a command in itself. The available step types are: |
| <ul class="star"> |
| <li><code>render</code> - To render a template to a given destination (as seen in the previous example)</li> |
| <li><code>mkdir</code> - To make a directory specified by the <code>location</code> parameter</li> |
| <li><code>execute</code> - To execute a command specified by the <code>class</code> parameter. Must be a class that implements the <a href="http://grails.org/doc/3.0.x/api/org/grails/cli/profile/Command.html" class="api">Command</a> interface.</li> |
| <li><code>gradle</code> - To execute one or many Gradle tasks specified by the <code>tasks</code> parameter.</li> |
| </ul><p class="paragraph"/>For example to invoke a Gradle task, you can define the following YAML:<p class="paragraph"/><div class="code"><pre>description: Creates a WAR file <span class="java-keyword">for</span> deployment to a container (like Tomcat) |
| minArguments: 0 |
| usage: | |
| war |
| steps: |
| - command: gradle |
| tasks: |
| - war</pre></div><p class="paragraph"/>If you need more flexiblity than what the declarative YAML approach provides you can create Groovy script commands. Each Command script is extends from the <a href="http://grails.org/doc/3.0.x/api/org/grails/cli/profile/commands/script/GroovyScriptCommmand.html" class="api">GroovyScriptCommmand</a> class and hence has all of the methods of that class available to it.<p class="paragraph"/>The following is an example of the <a href="../ref/Command Line/create-script.html" class="commandLine">create-script</a> command written in Groovy:<p class="paragraph"/><div class="code"><pre>description( <span class="java-quote">"Creates a Grails script"</span> ) { |
| usage <span class="java-quote">"grails create-script [SCRIPT NAME]"</span> |
| argument name:'Script Name', description:<span class="java-quote">"The name of the script to create"</span> |
| flag name:'force', description:<span class="java-quote">"Whether to overwrite existing files"</span> |
| }<p class="paragraph"/>def scriptName = args[0] |
| def model = model(scriptName) |
| def overwrite = flag('force') ? <span class="java-keyword">true</span> : <span class="java-keyword">false</span><p class="paragraph"/>render template: template('artifacts/Script.groovy'), |
| destination: file(<span class="java-quote">"src/main/scripts/${model.lowerCaseName}.groovy"</span>), |
| model: model, |
| overwrite: overwrite</pre></div><p class="paragraph"/>For more information on creating Groovy commands see the following section on creating custom Grails scripts.<p class="paragraph"/> |
| |
| |
| <h2 id="creatingCustomScripts">5.3 Creating Custom Scripts</h2> |
| |
| You can create your own Command scripts by running the <a href="../ref/Command Line/create-script.html" class="commandLine">create-script</a> command from the root of your project. For example the following command:<p class="paragraph"/><div class="code"><pre>grails create-script hello-world</pre></div><p class="paragraph"/><p class="paragraph"/>Will create a script called <code>src/main/scripts/hello-world.groovy</code>. Each Command script is extends from the <a href="http://grails.org/doc/3.0.x/api/org/grails/cli/profile/commands/script/GroovyScriptCommmand.html" class="api">GroovyScriptCommmand</a> class and hence has all of the methods of that class available to it.<p class="paragraph"/><blockquote class="note"> |
| In general Grails scripts should be used for scripting the Gradle based build system and code generation. Scripts cannot load application classes and in fact should not since Gradle is required to construct the application classpath. |
| </blockquote><p class="paragraph"/>See below for an example script that prints 'Hello World':<p class="paragraph"/><div class="code"><pre>description <span class="java-quote">"Example description"</span>, <span class="java-quote">"grails hello-world"</span><p class="paragraph"/>println <span class="java-quote">"Hello World"</span></pre></div><p class="paragraph"/>The <code>description</code> method is used to define the output seen by <code>grails help</code> and to aid users of the script. The following is a more complete example of providing a description taken from the <code>generate-all</code> command:<p class="paragraph"/><div class="code"><pre>description( <span class="java-quote">"Generates a controller that performs CRUD operations and the associated views"</span> ) { |
| usage <span class="java-quote">"grails generate-all [DOMAIN CLASS]"</span> |
| flag name:'force', description:<span class="java-quote">"Whether to overwrite existing files"</span> |
| argument name:'Domain <span class="java-object">Class</span>', description:'The name of the domain class' |
| }</pre></div><p class="paragraph"/>As you can see this description profiles usage instructions, a flag and an argument. This allows the command to be used as follows:<p class="paragraph"/><div class="code"><pre>grails generate-all MyClass --force</pre></div><p class="paragraph"/><p class="paragraph"/> |
| |
| |
| <a name="4.2 Re-using Grails scripts"><!-- Legacy link --></a> |
| <h2 id="reusingGrailsScripts">5.4 Re-using Grails scripts</h2> |
| Grails ships with a lot of command line functionality out of the box that you may find useful in your own scripts (See the command line reference in the reference guide for info on all the commands).<p class="paragraph"/>Any script you create an invoke another Grails script simply by invoking a method:<p class="paragraph"/><div class="code"><pre>testApp()</pre></div><p class="paragraph"/>The above will invoke the <code>test-app</code> command. You can also pass arguments using the method arguments:<p class="paragraph"/><div class="code"><pre>testApp('--debug-jvm')</pre></div><p class="paragraph"/><h4>Invoking Gradle </h4><p class="paragraph"/>Instead of invoking another Grails CLI command you can invoke Gradle directory using the <code>gradle</code> property.<p class="paragraph"/><div class="code"><pre>gradle.compileGroovy()</pre></div><p class="paragraph"/><h4>Invoking Ant</h4><p class="paragraph"/>You can also invoke Ant tasks from scripts which can help if you need to writing code generation and automation tasks:<p class="paragraph"/><div class="code"><pre>ant.mkdir(dir:<span class="java-quote">"path"</span>)</pre></div><p class="paragraph"/><h4>Template Generation</h4><p class="paragraph"/>Plugins and applications that need to define template generation tasks can do so using scripts. A example of this is the Scaffolding plugin which defines the <code>generate-all</code> and <code>generate-controllers</code> commands.<p class="paragraph"/>Every Grails script implements the <a href="http://grails.org/doc/3.0.x/api/org/grails/cli/profile/commands/templates/TemplateRenderer.html" class="api">TemplateRenderer</a> interface which makes it trivial to render templates to the users project workspace.<p class="paragraph"/>The following is an example of the <a href="../ref/Command Line/create-script.html" class="commandLine">create-script</a> command written in Groovy:<p class="paragraph"/><div class="code"><pre>description( <span class="java-quote">"Creates a Grails script"</span> ) { |
| usage <span class="java-quote">"grails create-script [SCRIPT NAME]"</span> |
| argument name:'Script Name', description:<span class="java-quote">"The name of the script to create"</span> |
| flag name:'force', description:<span class="java-quote">"Whether to overwrite existing files"</span> |
| }<p class="paragraph"/>def scriptName = args[0] |
| def model = model(scriptName) |
| def overwrite = flag('force') ? <span class="java-keyword">true</span> : <span class="java-keyword">false</span><p class="paragraph"/>render template: template('artifacts/Script.groovy'), |
| destination: file(<span class="java-quote">"src/main/scripts/${model.lowerCaseName}.groovy"</span>), |
| model: model, |
| overwrite: overwrite</pre></div> |
| |
| |
| |
| <h2 id="gradleBuild">5.5 Building with Gradle</h2> |
| Grails 3.0 uses the <a href="http://gradle.org" target="blank">Gradle Build System</a> for build related tasks such as compilation, runnings tests and producing binary distrubutions of your project. It is recommended to use Gradle 2.2 or above with Grails 3.0.<p class="paragraph"/>The build is defined by the <code>build.gradle</code> file which specifies the version of your project, the dependencies of the project and the repositories where to find those dependencies (amongst other things).<p class="paragraph"/>When you invoke the <code>grails</code> command the version of Gradle that ships with Grails 3.0 (currently 2.3) is invoked by the <code>grails</code> process via the <a href="http://www.gradle.org/docs/current/userguide/embedding.html" target="blank">Gradle Tooling API</a>:<p class="paragraph"/><div class="code"><pre># Equivalent to 'gradle classes' |
| $ grails compile</pre></div><p class="paragraph"/>You can invoke Gradle directly using the <code>gradle</code> command and use your own local version of Gradle, however you will need Gradle 2.2 or above to work with Grails 3.0:<p class="paragraph"/><div class="code"><pre>$ gradle assemble</pre></div><p class="paragraph"/> |
| |
| |
| <h2 id="gradleDependencies">5.5.1 Defining Dependencies with Gradle</h2> |
| Dependencies for your project are defined in the <code>dependencies</code> block. In general you can follow the <a href="http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html" target="blank">Gradle documentation on dependency management</a> to understand how to configure additional dependencies.<p class="paragraph"/>The default dependencies for the "web" profile can be seen below:<p class="paragraph"/><div class="code"><pre>dependencies { |
| compile 'org.springframework.boot:spring-boot-starter-logging' |
| compile('org.springframework.boot:spring-boot-starter-actuator') |
| compile 'org.springframework.boot:spring-boot-autoconfigure' |
| compile 'org.springframework.boot:spring-boot-starter-tomcat' |
| compile 'org.grails:grails-dependencies' |
| compile 'org.grails:grails-web-boot'<p class="paragraph"/> compile 'org.grails.plugins:hibernate' |
| compile 'org.grails.plugins:cache' |
| compile 'org.hibernate:hibernate-ehcache'<p class="paragraph"/> runtime 'org.grails.plugins:asset-pipeline' |
| runtime 'org.grails.plugins:scaffolding'<p class="paragraph"/> testCompile <span class="java-quote">"org.grails:grails-plugin-testing' |
| testCompile "</span>org.grails.plugins:geb'<p class="paragraph"/> // Note: It is recommended to update to a more robust driver (Chrome, Firefox etc.) |
| testRuntime 'org.seleniumhq.selenium:selenium-htmlunit-driver:2.44.0'<p class="paragraph"/> console 'org.grails:grails-console' |
| }</pre></div><p class="paragraph"/>Note that version numbers are not present in the majority of the dependencies. This is thanks to the dependency management plugin which configures a Maven BOM that defines the default dependency versions for certain commonly used dependencies and plugins:<p class="paragraph"/><div class="code"><pre>dependencyManagement { |
| imports { |
| mavenBom 'org.grails:grails-bom:' + grailsVersion |
| } |
| applyMavenExclusions <span class="java-keyword">false</span> |
| }</pre></div> |
| |
| |
| |
| <h2 id="gradleTasks">5.5.2 Working with Gradle Tasks</h2> |
| As mentioned previously the <code>grails</code> command uses an embedded version of Gradle and certain Grails commands that existed in previous versions of Grails map onto their Gradle equivalents. The following table shows which Grails command invoke which Gradle task:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th><strong class="bold">Grails Command</strong></th><th><strong class="bold">Gradle Task</strong></th></tr><tr class="table-odd"><td>clean</td><td>clean</td></tr><tr class="table-even"><td>compile</td><td>classes</td></tr><tr class="table-odd"><td>package</td><td>assemble</td></tr><tr class="table-even"><td>run-app</td><td>run</td></tr><tr class="table-odd"><td>test-app</td><td>test</td></tr><tr class="table-even"><td>war</td><td>assemble</td></tr></table><p class="paragraph"/>You can invoke any of these Grails commands using their Gradle equivalents if you prefer:<p class="paragraph"/><div class="code"><pre>$ gradle test</pre></div><p class="paragraph"/>Note however that you will need to use a version of Gradle compatible with Grails 3.0 (Gradle 2.2 or above). If you wish to invoke a Gradle task using the version of Gradle used by Grails you can do so with the <code>grails</code> command:<p class="paragraph"/><div class="code"><pre>$ grails gradle compileGroovy</pre></div><p class="paragraph"/>However, it is recommended you do this via interactive mode, as it greatly speeds up execution and provides TAB completion for the available Gradle tasks:<p class="paragraph"/><div class="code"><pre>$ grails |
| | Enter a command name to run. Use TAB <span class="java-keyword">for</span> completion: |
| grails> gradle compileGroovy |
| ...</pre></div><p class="paragraph"/>To find out what Gradle tasks are available without using interactive mode TAB completion you can use the Gradle <code>tasks</code> task:<p class="paragraph"/><div class="code"><pre>gradle tasks</pre></div><p class="paragraph"/><p class="paragraph"/> |
| |
| |
| <h2 id="gradlePlugins">5.5.3 Grails plugins for Gradle</h2> |
| When you create a new project with the <a href="../ref/Command Line/create-app.html" class="commandLine">create-app</a> command, a default <code>build.gradle</code> is created. The default <code>build.gradle</code> configures the build with a set of Gradle plugins that allow Gradle to build the Grails project:<p class="paragraph"/><div class="code"><pre>plugins { |
| id <span class="java-quote">"io.spring.dependency-management"</span> version <span class="java-quote">"0.3.1.RELEASE"</span> |
| }<p class="paragraph"/>apply plugin: <span class="java-quote">"spring-boot"</span> |
| apply plugin: <span class="java-quote">"war"</span> |
| apply plugin: <span class="java-quote">"asset-pipeline"</span> |
| apply plugin: <span class="java-quote">"org.grails.grails-web"</span> |
| apply plugin: <span class="java-quote">"org.grails.grails-gsp"</span> |
| apply plugin: <span class="java-quote">"maven"</span></pre></div><p class="paragraph"/>The default plugins are as follows: |
| <ul class="star"> |
| <li><code>dependency-management</code> - The <a href="https://plugins.gradle.org/plugin/io.spring.dependency-management" target="blank">dependency management</a> plugin allows Gradle to read Maven BOM files that define the default dependency versions used by Grails.</li> |
| <li><code>spring-boot</code> - The <a href="http://docs.spring.io/spring-boot/docs/current/reference/html/build-tool-plugins-gradle-plugin.html" target="blank">Spring Boot</a> Gradle plugin enhances the default packaging tasks provided by Gradle to allow for the creation of runnable JAR/WAR files.</li> |
| <li><code>war</code> - The <a href="http://www.gradle.org/docs/current/userguide/war_plugin.html" target="blank">WAR plugin</a> changes the packaging so that Gradle creates as WAR file from you application. You can comment out this plugin if you wish to create only a runnable JAR file for standalone deployment.</li> |
| <li><code>asset-pipeline</code> - The <a href="https://github.com/bertramdev/asset-pipeline-core" target="blank">asset pipeline</a> plugin enables the compilation of static assets (JavaScript, CSS etc.)</li> |
| <li><code>maven</code> - The <a href="http://www.gradle.org/docs/current/userguide/maven_plugin.html" target="blank">maven plugin</a> allows installing your application into a local maven repository</li> |
| </ul><p class="paragraph"/>Many of these are built in plugins provided by Gradle or third party plugins. The Gradle plugins that Grails provides are as follows: |
| <ul class="star"> |
| <li><code>org.grails.grails-core</code> - The primary Grails plugin for Gradle, included by all other plugins and designed to operate with all profiles.</li> |
| <li><code>org.grails.grails-plugin</code> - A plugin for Gradle for building Grails plugins.</li> |
| <li><code>org.grails.grails-web</code> - The Grails Web gradle plugin configures Gradle to understand the Grails conventions and directory structure.</li> |
| <li><code>org.grails.grails-gsp</code> - The Grails GSP plugin adds precompilation of GSP files for production deployments.</li> |
| <li><code>org.grails.grails-doc</code> - A plugin for Gradle for using Grails 2.0's documentation engine.</li> |
| </ul><p class="paragraph"/> |
| |
| <a name="5. Object Relational Mapping (GORM)"><!-- Legacy link --></a> |
| <h1 id="GORM">6 Object Relational Mapping (GORM)</h1> |
| Domain classes are core to any business application. They hold state about business processes and hopefully also implement behavior. They are linked together through relationships; one-to-one, one-to-many, or many-to-many.<p class="paragraph"/>GORM is Grails' object relational mapping (ORM) implementation. Under the hood it uses Hibernate 3 (a very popular and flexible open source ORM solution) and thanks to the dynamic nature of Groovy with its static and dynamic typing, along with the convention of Grails, there is far less configuration involved in creating Grails domain classes.<p class="paragraph"/>You can also write Grails domain classes in Java. See the section on Hibernate Integration for how to write domain classes in Java but still use dynamic persistent methods. Below is a preview of GORM in action:<p class="paragraph"/><div class="code"><pre>def book = Book.findByTitle(<span class="java-quote">"Groovy in Action"</span>)<p class="paragraph"/>book |
| .addToAuthors(name:<span class="java-quote">"Dierk Koenig"</span>) |
| .addToAuthors(name:<span class="java-quote">"Guillaume LaForge"</span>) |
| .save()</pre></div> |
| |
| |
| <a name="5.1 Quick Start Guide"><!-- Legacy link --></a> |
| <h2 id="quickStartGuide">6.1 Quick Start Guide</h2> |
| A domain class can be created with the <a href="../ref/Command Line/create-domain-class.html" class="commandLine">create-domain-class</a> command:<p class="paragraph"/><div class="code"><pre>grails create-domain-class helloworld.Person</pre></div><p class="paragraph"/><blockquote class="note"> |
| If no package is specified with the create-domain-class script, Grails automatically uses the application name as the package name. |
| </blockquote><p class="paragraph"/>This will create a class at the location <code>grails-app/domain/helloworld/Person.groovy</code> such as the one below:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> helloworld<p class="paragraph"/>class Person { |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| If you have the <code>dbCreate</code> property set to "update", "create" or "create-drop" on your <a href="../guide/single.html#dataSource" class="guide">DataSource</a>, Grails will automatically generate/modify the database tables for you. |
| </blockquote><p class="paragraph"/>You can customize the class by adding properties:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> name |
| <span class="java-object">Integer</span> age |
| Date lastVisit |
| }</pre></div><p class="paragraph"/>Once you have a domain class try and manipulate it with the <a href="../ref/Command Line/shell.html" class="commandLine">shell</a> or <a href="../ref/Command Line/console.html" class="commandLine">console</a> by typing:<p class="paragraph"/><div class="code"><pre>grails console</pre></div><p class="paragraph"/>This loads an interactive GUI where you can run Groovy commands with access to the Spring ApplicationContext, GORM, etc. |
| |
| |
| <a name="5.1.1 Basic CRUD"><!-- Legacy link --></a> |
| <h2 id="basicCRUD">6.1.1 Basic CRUD</h2> |
| Try performing some basic CRUD (Create/Read/Update/Delete) operations.<p class="paragraph"/><h4>Create</h4><p class="paragraph"/>To create a domain class use Map constructor to set its properties and call <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a>:<p class="paragraph"/><div class="code"><pre>def p = <span class="java-keyword">new</span> Person(name: <span class="java-quote">"Fred"</span>, age: 40, lastVisit: <span class="java-keyword">new</span> Date()) |
| p.save()</pre></div><p class="paragraph"/>The <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> method will persist your class to the database using the underlying Hibernate ORM layer.<p class="paragraph"/><h4>Read</h4><p class="paragraph"/>Grails transparently adds an implicit <code>id</code> property to your domain class which you can use for retrieval:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1) |
| assert 1 == p.id</pre></div><p class="paragraph"/>This uses the <a href="../ref/Domain Classes/get.html" class="domainClasses">get</a> method that expects a database identifier to read the <code>Person</code> object back from the database. |
| You can also load an object in a read-only state by using the <a href="../ref/Domain Classes/read.html" class="domainClasses">read</a> method:<p class="paragraph"/><div class="code"><pre>def p = Person.read(1)</pre></div><p class="paragraph"/>In this case the underlying Hibernate engine will not do any dirty checking and the object will not be persisted. Note that |
| if you explicitly call the <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> method then the object is placed back into a read-write state.<p class="paragraph"/>In addition, you can also load a proxy for an instance by using the <a href="../ref/Domain Classes/load.html" class="domainClasses">load</a> method:<p class="paragraph"/><div class="code"><pre>def p = Person.load(1)</pre></div><p class="paragraph"/>This incurs no database access until a method other than getId() is called. Hibernate then initializes the proxied instance, or |
| throws an exception if no record is found for the specified id.<p class="paragraph"/><h4>Update</h4><p class="paragraph"/>To update an instance, change some properties and then call <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> again:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1) |
| p.name = <span class="java-quote">"Bob"</span> |
| p.save()</pre></div><p class="paragraph"/><h4>Delete</h4><p class="paragraph"/>To delete an instance use the <a href="../ref/Domain Classes/delete.html" class="domainClasses">delete</a> method:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1) |
| p.delete()</pre></div> |
| |
| |
| <a name="5.2 Domain Modelling in GORM"><!-- Legacy link --></a> |
| <h2 id="domainClasses">6.2 Domain Modelling in GORM</h2> |
| When building Grails applications you have to consider the problem domain you are trying to solve. For example if you were building an <a href="http://www.amazon.com/" target="blank">Amazon</a>-style bookstore you would be thinking about books, authors, customers and publishers to name a few.<p class="paragraph"/>These are modeled in GORM as Groovy classes, so a <code>Book</code> class may have a title, a release date, an ISBN number and so on. The next few sections show how to model the domain in GORM.<p class="paragraph"/>To create a domain class you run the <a href="../ref/Command Line/create-domain-class.html" class="commandLine">create-domain-class</a> command as follows:<p class="paragraph"/><div class="code"><pre>grails create-domain-class org.bookstore.Book</pre></div><p class="paragraph"/>The result will be a class at <code>grails-app/domain/org/bookstore/Book.groovy</code>:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> org.bookstore<p class="paragraph"/>class Book { |
| }</pre></div><p class="paragraph"/>This class will map automatically to a table in the database called <code>book</code> (the same name as the class). This behaviour is customizable through the <a href="../guide/single.html#ormdsl" class="guide">ORM Domain Specific Language</a><p class="paragraph"/>Now that you have a domain class you can define its properties as Java types. For example:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> org.bookstore<p class="paragraph"/>class Book { |
| <span class="java-object">String</span> title |
| Date releaseDate |
| <span class="java-object">String</span> ISBN |
| }</pre></div><p class="paragraph"/>Each property is mapped to a column in the database, where the convention for column names is all lower case separated by underscores. For example <code>releaseDate</code> maps onto a column <code>release_date</code>. The SQL types are auto-detected from the Java types, but can be customized with <a href="../guide/single.html#constraints" class="guide">Constraints</a> or the <a href="../guide/single.html#ormdsl" class="guide">ORM DSL</a>. |
| |
| |
| <a name="5.2.1 Association in GORM"><!-- Legacy link --></a> |
| <h2 id="gormAssociation">6.2.1 Association in GORM</h2> |
| Relationships define how domain classes interact with each other. Unless specified explicitly at both ends, a relationship exists only in the direction it is defined.<p class="paragraph"/> |
| |
| <a name="5.2.1.1 Many-to-one and one-to-one"><!-- Legacy link --></a> |
| <h2 id="manyToOneAndOneToOne">6.2.1.1 Many-to-one and one-to-one</h2> |
| A many-to-one relationship is the simplest kind, and is defined with a property of the type of another domain class. Consider this example:<p class="paragraph"/><h5>Example A</h5><p class="paragraph"/><div class="code"><pre>class Face { |
| Nose nose |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Nose { |
| }</pre></div><p class="paragraph"/>In this case we have a unidirectional many-to-one relationship from <code>Face</code> to <code>Nose</code>. To make this relationship bidirectional define the other side as follows (and see the section on controlling the ends of the association just below):<p class="paragraph"/><h5>Example B</h5><p class="paragraph"/><div class="code"><pre>class Face { |
| Nose nose |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Nose { |
| <span class="java-keyword">static</span> belongsTo = [face:Face] |
| }</pre></div><p class="paragraph"/>In this case we use the <code>belongsTo</code> setting to say that <code>Nose</code> "belongs to" <code>Face</code>. The result of this is that we can create a <code>Face</code>, attach a <code>Nose</code> instance to it and when we save or delete the <code>Face</code> instance, GORM will save or delete the <code>Nose</code>. In other words, saves and deletes will cascade from <code>Face</code> to the associated <code>Nose</code>:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">new</span> Face(nose:<span class="java-keyword">new</span> Nose()).save()</pre></div><p class="paragraph"/>The example above will save both face and nose. Note that the inverse <em class="italic">is not</em> true and will result in an error due to a transient <code>Face</code>:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">new</span> Nose(face:<span class="java-keyword">new</span> Face()).save() // will cause an error</pre></div><p class="paragraph"/>Now if we delete the <code>Face</code> instance, the <code>Nose</code> will go too:<p class="paragraph"/><div class="code"><pre>def f = Face.get(1) |
| f.delete() // both Face and Nose deleted</pre></div><p class="paragraph"/>To make the relationship a true one-to-one, use the <code>hasOne</code> property on the owning side, e.g. <code>Face</code>:<p class="paragraph"/><h5>Example C</h5><p class="paragraph"/><div class="code"><pre>class Face { |
| <span class="java-keyword">static</span> hasOne = [nose:Nose] |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Nose { |
| Face face |
| }</pre></div><p class="paragraph"/>Note that using this property puts the foreign key on the inverse table to the example A, so in this case the foreign key column is stored in the <code>nose</code> table inside a column called <code>face_id</code>. Also, <code>hasOne</code> only works with bidirectional relationships.<p class="paragraph"/>Finally, it's a good idea to add a unique constraint on one side of the one-to-one relationship:<p class="paragraph"/><div class="code"><pre>class Face { |
| <span class="java-keyword">static</span> hasOne = [nose:Nose]<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| nose unique: <span class="java-keyword">true</span> |
| } |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Nose { |
| Face face |
| }</pre></div><p class="paragraph"/><h5>Controlling the ends of the association</h5><p class="paragraph"/>Occasionally you may find yourself with domain classes that have multiple properties of the same type. They may even be self-referential, i.e. the association property has the same type as the domain class it's in. Such situations can cause problems because Grails may guess incorrectly the type of the association. Consider this simple class:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> name |
| Person parent<p class="paragraph"/> <span class="java-keyword">static</span> belongsTo = [ supervisor: Person ]<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { supervisor nullable: <span class="java-keyword">true</span> } |
| }</pre></div><p class="paragraph"/>As far as Grails is concerned, the <code>parent</code> and <code>supervisor</code> properties are two directions of the same association. So when you set the <code>parent</code> property on a <code>Person</code> instance, Grails will automatically set the <code>supervisor</code> property on the other <code>Person</code> instance. This may be what you want, but if you look at the class, what we in fact have are two unidirectional relationships.<p class="paragraph"/>To guide Grails to the correct mapping, you can tell it that a particular association is unidirectional through the <code>mappedBy</code> property:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> name |
| Person parent<p class="paragraph"/> <span class="java-keyword">static</span> belongsTo = [ supervisor: Person ]<p class="paragraph"/> <span class="java-keyword">static</span> mappedBy = [ supervisor: <span class="java-quote">"none"</span>, parent: <span class="java-quote">"none"</span> ]<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { supervisor nullable: <span class="java-keyword">true</span> } |
| }</pre></div><p class="paragraph"/>You can also replace "none" with any property name of the target class. And of course this works for normal domain classes too, not just self-referential ones. Nor is the <code>mappedBy</code> property limited to many-to-one and one-to-one associations: it also works for one-to-many and many-to-many associations as you'll see in the next section.<p class="paragraph"/><blockquote class="warning"> |
| If you have a property called "none" on your domain class, this approach won't work currently! The "none" property will be treated as the reverse direction of the association (or the "back reference"). Fortunately, "none" is not a common domain class property name. |
| </blockquote> |
| |
| |
| <a name="5.2.1.2 One-to-many"><!-- Legacy link --></a> |
| <h2 id="oneToMany">6.2.1.2 One-to-many</h2> |
| A one-to-many relationship is when one class, example <code>Author</code>, has many instances of another class, example <code>Book</code>. With Grails you define such a relationship with the <code>hasMany</code> setting:<p class="paragraph"/><div class="code"><pre>class Author { |
| <span class="java-keyword">static</span> hasMany = [books: Book]<p class="paragraph"/> <span class="java-object">String</span> name |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Book { |
| <span class="java-object">String</span> title |
| }</pre></div><p class="paragraph"/>In this case we have a unidirectional one-to-many. Grails will, by default, map this kind of relationship with a join table.<p class="paragraph"/><blockquote class="note"> |
| The <a href="../guide/single.html#ormdsl" class="guide">ORM DSL</a> allows mapping unidirectional relationships using a foreign key association instead |
| </blockquote><p class="paragraph"/>Grails will automatically inject a property of type <code>java.util.Set</code> into the domain class based on the <code>hasMany</code> setting. This can be used to iterate over the collection:<p class="paragraph"/><div class="code"><pre>def a = Author.get(1)<p class="paragraph"/><span class="java-keyword">for</span> (book in a.books) { |
| println book.title |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| The default fetch strategy used by Grails is "lazy", which means that the collection will be lazily initialized on first access. This can lead to the <a href="http://www.javalobby.org/java/forums/t20533.html" target="blank">n+1 problem</a> if you are not careful.<p class="paragraph"/>If you need "eager" fetching you can use the <a href="../guide/single.html#ormdsl" class="guide">ORM DSL</a> or specify eager fetching as part of a <a href="../guide/single.html#querying" class="guide">query</a> |
| </blockquote><p class="paragraph"/>The default cascading behaviour is to cascade saves and updates, but not deletes unless a <code>belongsTo</code> is also specified:<p class="paragraph"/><div class="code"><pre>class Author { |
| <span class="java-keyword">static</span> hasMany = [books: Book]<p class="paragraph"/> <span class="java-object">String</span> name |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Book { |
| <span class="java-keyword">static</span> belongsTo = [author: Author] |
| <span class="java-object">String</span> title |
| }</pre></div><p class="paragraph"/>If you have two properties of the same type on the many side of a one-to-many you have to use <code>mappedBy</code> to specify which the collection is mapped:<p class="paragraph"/><div class="code"><pre>class Airport { |
| <span class="java-keyword">static</span> hasMany = [flights: Flight] |
| <span class="java-keyword">static</span> mappedBy = [flights: <span class="java-quote">"departureAirport"</span>] |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Flight { |
| Airport departureAirport |
| Airport destinationAirport |
| }</pre></div><p class="paragraph"/>This is also true if you have multiple collections that map to different properties on the many side:<p class="paragraph"/><div class="code"><pre>class Airport { |
| <span class="java-keyword">static</span> hasMany = [outboundFlights: Flight, inboundFlights: Flight] |
| <span class="java-keyword">static</span> mappedBy = [outboundFlights: <span class="java-quote">"departureAirport"</span>, |
| inboundFlights: <span class="java-quote">"destinationAirport"</span>] |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Flight { |
| Airport departureAirport |
| Airport destinationAirport |
| }</pre></div><p class="paragraph"/> |
| |
| <a name="5.2.1.3 Many-to-many"><!-- Legacy link --></a> |
| <h2 id="manyToMany">6.2.1.3 Many-to-many</h2> |
| Grails supports many-to-many relationships by defining a <code>hasMany</code> on both sides of the relationship and having a <code>belongsTo</code> on the owned side of the relationship:<p class="paragraph"/><div class="code"><pre>class Book { |
| <span class="java-keyword">static</span> belongsTo = Author |
| <span class="java-keyword">static</span> hasMany = [authors:Author] |
| <span class="java-object">String</span> title |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Author { |
| <span class="java-keyword">static</span> hasMany = [books:Book] |
| <span class="java-object">String</span> name |
| }</pre></div><p class="paragraph"/>Grails maps a many-to-many using a join table at the database level. The owning side of the relationship, in this case <code>Author</code>, takes responsibility for persisting the relationship and is the only side that can cascade saves across.<p class="paragraph"/>For example this will work and cascade saves:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">new</span> Author(name:<span class="java-quote">"Stephen King"</span>) |
| .addToBooks(<span class="java-keyword">new</span> Book(title:<span class="java-quote">"The Stand"</span>)) |
| .addToBooks(<span class="java-keyword">new</span> Book(title:<span class="java-quote">"The Shining"</span>)) |
| .save()</pre></div><p class="paragraph"/>However this will only save the <code>Book</code> and not the authors!<p class="paragraph"/><div class="code"><pre><span class="java-keyword">new</span> Book(name:<span class="java-quote">"Groovy in Action"</span>) |
| .addToAuthors(<span class="java-keyword">new</span> Author(name:<span class="java-quote">"Dierk Koenig"</span>)) |
| .addToAuthors(<span class="java-keyword">new</span> Author(name:<span class="java-quote">"Guillaume Laforge"</span>)) |
| .save()</pre></div><p class="paragraph"/>This is the expected behaviour as, just like Hibernate, only one side of a many-to-many can take responsibility for managing the relationship.<p class="paragraph"/><blockquote class="warning"> |
| Grails' <a href="../guide/single.html#scaffolding" class="guide">Scaffolding</a> feature <strong class="bold">does not</strong> currently support many-to-many relationship and hence you must write the code to manage the relationship yourself |
| </blockquote> |
| |
| |
| <a name="5.2.1.4 Basic Collection Types"><!-- Legacy link --></a> |
| <h2 id="basicCollectionTypes">6.2.1.4 Basic Collection Types</h2> |
| As well as associations between different domain classes, GORM also supports mapping of basic collection types. |
| For example, the following class creates a <code>nicknames</code> association that is a <code>Set</code> of <code>String</code> instances:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-keyword">static</span> hasMany = [nicknames: <span class="java-object">String</span>] |
| }</pre></div><p class="paragraph"/>GORM will map an association like the above using a join table. You can alter various aspects of how the join table is mapped using the <code>joinTable</code> argument:<p class="paragraph"/><div class="code"><pre>class Person {<p class="paragraph"/> <span class="java-keyword">static</span> hasMany = [nicknames: <span class="java-object">String</span>]<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| hasMany joinTable: [name: 'bunch_o_nicknames', |
| key: 'person_id', |
| column: 'nickname', |
| type: <span class="java-quote">"text"</span>] |
| } |
| }</pre></div><p class="paragraph"/>The example above will map to a table that looks like the following:<p class="paragraph"/><strong class="bold">bunch_o_nicknames Table</strong> |
| <div class="code"><pre>--------------------------------------------- |
| | person_id | nickname | |
| --------------------------------------------- |
| | 1 | Fred | |
| ---------------------------------------------</pre></div> |
| |
| <a name="5.2.2 Composition in GORM"><!-- Legacy link --></a> |
| <h2 id="gormComposition">6.2.2 Composition in GORM</h2> |
| As well as <a href="../guide/single.html#gormAssociation" class="guide">association</a>, Grails supports the notion of composition. In this case instead of mapping classes onto separate tables a class can be "embedded" within the current table. For example:<p class="paragraph"/><div class="code"><pre>class Person { |
| Address homeAddress |
| Address workAddress |
| <span class="java-keyword">static</span> embedded = ['homeAddress', 'workAddress'] |
| }<p class="paragraph"/>class Address { |
| <span class="java-object">String</span> number |
| <span class="java-object">String</span> code |
| }</pre></div><p class="paragraph"/>The resulting mapping would looking like this:<p class="paragraph"/><img border="0" class="center" src="../img/5.2.2-composition.jpg"></img><p class="paragraph"/><blockquote class="note"> |
| If you define the <code>Address</code> class in a separate Groovy file in the <code>grails-app/domain</code> directory you will also get an <code>address</code> table. If you don't want this to happen use Groovy's ability to define multiple classes per file and include the <code>Address</code> class below the <code>Person</code> class in the <code>grails-app/domain/Person.groovy</code> file |
| </blockquote> |
| |
| |
| <a name="5.2.3 Inheritance in GORM"><!-- Legacy link --></a> |
| <h2 id="inheritanceInGORM">6.2.3 Inheritance in GORM</h2> |
| GORM supports inheritance both from abstract base classes and concrete persistent GORM entities. For example:<p class="paragraph"/><div class="code"><pre>class Content { |
| <span class="java-object">String</span> author |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class BlogEntry <span class="java-keyword">extends</span> Content { |
| URL url |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Book <span class="java-keyword">extends</span> Content { |
| <span class="java-object">String</span> ISBN |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class PodCast <span class="java-keyword">extends</span> Content { |
| <span class="java-object">byte</span>[] audioStream |
| }</pre></div><p class="paragraph"/>In the above example we have a parent <code>Content</code> class and then various child classes with more specific behaviour.<p class="paragraph"/><h4>Considerations</h4><p class="paragraph"/>At the database level Grails by default uses table-per-hierarchy mapping with a discriminator column called <code>class</code> so the parent class (<code>Content</code>) and its subclasses (<code>BlogEntry</code>, <code>Book</code> etc.), share the <strong class="bold">same</strong> table.<p class="paragraph"/>Table-per-hierarchy mapping has a down side in that you <strong class="bold">cannot</strong> have non-nullable properties with inheritance mapping. An alternative is to use table-per-subclass which can be enabled with the <a href="../guide/single.html#ormdsl" class="guide">ORM DSL</a><p class="paragraph"/>However, excessive use of inheritance and table-per-subclass can result in poor query performance due to the use of outer join queries. In general our advice is if you're going to use inheritance, don't abuse it and don't make your inheritance hierarchy too deep.<p class="paragraph"/><h4>Polymorphic Queries</h4><p class="paragraph"/>The upshot of inheritance is that you get the ability to polymorphically query. For example using the <a href="../ref/Domain Classes/list.html" class="domainClasses">list</a> method on the <code>Content</code> super class will return all subclasses of <code>Content</code>:<p class="paragraph"/><div class="code"><pre>def content = Content.list() // list all blog entries, books and podcasts |
| content = Content.findAllByAuthor('Joe Bloggs') // find all by author<p class="paragraph"/>def podCasts = PodCast.list() // list only podcasts</pre></div> |
| |
| <a name="5.2.4 Sets, Lists and Maps"><!-- Legacy link --></a> |
| <h2 id="sets,ListsAndMaps">6.2.4 Sets, Lists and Maps</h2> |
| <h4>Sets of Objects</h4><p class="paragraph"/>By default when you define a relationship with GORM it is a <code>java.util.Set</code> which is an unordered collection that cannot contain duplicates. In other words when you have:<p class="paragraph"/><div class="code"><pre>class Author { |
| <span class="java-keyword">static</span> hasMany = [books: Book] |
| }</pre></div><p class="paragraph"/>The books property that GORM injects is a <code>java.util.Set</code>. Sets guarantee uniqueness but not order, which may not be what you want. To have custom ordering you configure the Set as a <code>SortedSet</code>:<p class="paragraph"/><div class="code"><pre>class Author {<p class="paragraph"/> SortedSet books<p class="paragraph"/> <span class="java-keyword">static</span> hasMany = [books: Book] |
| }</pre></div><p class="paragraph"/>In this case a <code>java.util.SortedSet</code> implementation is used which means you must implement <code>java.lang.Comparable</code> in your Book class:<p class="paragraph"/><div class="code"><pre>class Book <span class="java-keyword">implements</span> Comparable {<p class="paragraph"/> <span class="java-object">String</span> title |
| Date releaseDate = <span class="java-keyword">new</span> Date()<p class="paragraph"/> <span class="java-object">int</span> compareTo(obj) { |
| releaseDate.compareTo(obj.releaseDate) |
| } |
| }</pre></div><p class="paragraph"/>The result of the above class is that the Book instances in the books collection of the Author class will be ordered by their release date.<p class="paragraph"/><h4>Lists of Objects</h4><p class="paragraph"/>To keep objects in the order which they were added and to be able to reference them by index like an array you can define your collection type as a <code>List</code>:<p class="paragraph"/><div class="code"><pre>class Author {<p class="paragraph"/> List books<p class="paragraph"/> <span class="java-keyword">static</span> hasMany = [books: Book] |
| }</pre></div><p class="paragraph"/>In this case when you add new elements to the books collection the order is retained in a sequential list indexed from 0 so you can do:<p class="paragraph"/><div class="code"><pre>author.books[0] // get the first book</pre></div><p class="paragraph"/>The way this works at the database level is Hibernate creates a <code>books_idx</code> column where it saves the index of the elements in the collection to retain this order at the database level.<p class="paragraph"/>When using a <code>List</code>, elements must be added to the collection before being saved, otherwise Hibernate will throw an exception (<code>org.hibernate.HibernateException</code>: null index column for collection):<p class="paragraph"/><div class="code"><pre>// This won't work! |
| def book = <span class="java-keyword">new</span> Book(title: 'The Shining') |
| book.save() |
| author.addToBooks(book)<p class="paragraph"/>// Do it <span class="java-keyword">this</span> way instead. |
| def book = <span class="java-keyword">new</span> Book(title: 'Misery') |
| author.addToBooks(book) |
| author.save()</pre></div><p class="paragraph"/><h4>Bags of Objects</h4><p class="paragraph"/>If ordering and uniqueness aren't a concern (or if you manage these explicitly) then you can use the Hibernate <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/collections.html" target="blank">Bag</a> type to represent mapped collections.<p class="paragraph"/>The only change required for this is to define the collection type as a <code>Collection</code>:<p class="paragraph"/><div class="code"><pre>class Author {<p class="paragraph"/> Collection books<p class="paragraph"/> <span class="java-keyword">static</span> hasMany = [books: Book] |
| }</pre></div><p class="paragraph"/>Since uniqueness and order aren't managed by Hibernate, adding to or removing from collections mapped as a Bag don't trigger a load of all existing instances from the database, so this approach will perform better and require less memory than using a <code>Set</code> or a <code>List</code>.<p class="paragraph"/><h4>Maps of Objects</h4><p class="paragraph"/>If you want a simple map of string/value pairs GORM can map this with the following:<p class="paragraph"/><div class="code"><pre>class Author { |
| Map books // map of ISBN:book names |
| }<p class="paragraph"/>def a = <span class="java-keyword">new</span> Author() |
| a.books = [<span class="java-quote">"1590597583"</span>:<span class="java-quote">"Grails Book"</span>] |
| a.save()</pre></div> |
| In this case the key and value of the map MUST be strings.<p class="paragraph"/>If you want a Map of objects then you can do this:<p class="paragraph"/><div class="code"><pre>class Book {<p class="paragraph"/> Map authors<p class="paragraph"/> <span class="java-keyword">static</span> hasMany = [authors: Author] |
| }<p class="paragraph"/>def a = <span class="java-keyword">new</span> Author(name:<span class="java-quote">"Stephen King"</span>)<p class="paragraph"/>def book = <span class="java-keyword">new</span> Book() |
| book.authors = [stephen:a] |
| book.save()</pre></div><p class="paragraph"/>The static <code>hasMany</code> property defines the type of the elements within the Map. The keys for the map <strong class="bold">must</strong> be strings.<p class="paragraph"/><h4>A Note on Collection Types and Performance</h4><p class="paragraph"/>The Java <code>Set</code> type doesn't allow duplicates. To ensure uniqueness when adding an entry to a <code>Set</code> association Hibernate has to load the entire associations from the database. If you have a large numbers of entries in the association this can be costly in terms of performance.<p class="paragraph"/>The same behavior is required for <code>List</code> types, since Hibernate needs to load the entire association to maintain order. Therefore it is recommended that if you anticipate a large numbers of records in the association that you make the association bidirectional so that the link can be created on the inverse side. For example consider the following code:<p class="paragraph"/><div class="code"><pre>def book = <span class="java-keyword">new</span> Book(title:<span class="java-quote">"New Grails Book"</span>) |
| def author = Author.get(1) |
| book.author = author |
| book.save()</pre></div><p class="paragraph"/>In this example the association link is being created by the child (Book) and hence it is not necessary to manipulate the collection directly resulting in fewer queries and more efficient code. Given an <code>Author</code> with a large number of associated <code>Book</code> instances if you were to write code like the following you would see an impact on performance:<p class="paragraph"/><div class="code"><pre>def book = <span class="java-keyword">new</span> Book(title:<span class="java-quote">"New Grails Book"</span>) |
| def author = Author.get(1) |
| author.addToBooks(book) |
| author.save()</pre></div><p class="paragraph"/>You could also model the collection as a Hibernate Bag as described above. |
| |
| |
| <a name="5.3 Persistence Basics"><!-- Legacy link --></a> |
| <h2 id="persistenceBasics">6.3 Persistence Basics</h2> |
| A key thing to remember about Grails is that under the surface Grails is using <a href="http://www.hibernate.org/" target="blank">Hibernate</a> for persistence. If you are coming from a background of using <a href="http://wiki.rubyonrails.org/rails/pages/ActiveRecord" target="blank">ActiveRecord</a> or <a href="http://www.mybatis.org/" target="blank">iBatis/MyBatis</a>, Hibernate's "session" model may feel a little strange.<p class="paragraph"/>Grails automatically binds a Hibernate session to the currently executing request. This lets you use the <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> and <a href="../ref/Domain Classes/delete.html" class="domainClasses">delete</a> methods as well as other GORM methods transparently.<p class="paragraph"/><h4>Transactional Write-Behind</h4><p class="paragraph"/>A useful feature of Hibernate over direct JDBC calls and even other frameworks is that when you call <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> or <a href="../ref/Domain Classes/delete.html" class="domainClasses">delete</a> it does not necessarily perform any SQL operations <strong class="bold">at that point</strong>. Hibernate batches up SQL statements and executes them as late as possible, often at the end of the request when flushing and closing the session. This is typically done for you automatically by Grails, which manages your Hibernate session.<p class="paragraph"/>Hibernate caches database updates where possible, only actually pushing the changes when it knows that a flush is required, or when a flush is triggered programmatically. One common case where Hibernate will flush cached updates is when performing queries since the cached information might be included in the query results. But as long as you're doing non-conflicting saves, updates, and deletes, they'll be batched until the session is flushed. This can be a significant performance boost for applications that do a lot of database writes.<p class="paragraph"/>Note that flushing is not the same as committing a transaction. If your actions are performed in the context of a transaction, flushing will execute SQL updates but the database will save the changes in its transaction queue and only finalize the updates when the transaction commits. |
| |
| |
| <a name="5.3.1 Saving and Updating"><!-- Legacy link --></a> |
| <h2 id="savingAndUpdating">6.3.1 Saving and Updating</h2> |
| An example of using the <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> method can be seen below:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1) |
| p.save()</pre></div><p class="paragraph"/>This save will be not be pushed to the database immediately - it will be pushed when the next flush occurs. But there are occasions when you want to control when those statements are executed or, in Hibernate terminology, when the session is "flushed". To do so you can use the flush argument to the save method:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1) |
| p.save(flush: <span class="java-keyword">true</span>)</pre></div><p class="paragraph"/>Note that in this case <em class="italic">all</em> pending SQL statements including previous saves, deletes, etc. will be synchronized with the database. This also lets you catch any exceptions, which is typically useful in highly concurrent scenarios involving <a href="../guide/single.html#locking" class="guide">optimistic locking</a>:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1) |
| <span class="java-keyword">try</span> { |
| p.save(flush: <span class="java-keyword">true</span>) |
| } |
| <span class="java-keyword">catch</span> (org.springframework.dao.DataIntegrityViolationException e) { |
| // deal with exception |
| }</pre></div><p class="paragraph"/>Another thing to bear in mind is that Grails <a href="../guide/single.html#validation" class="guide">validates</a> a domain instance every time you save it. If that validation fails the domain instance will <em class="italic">not</em> be persisted to the database. By default, <code>save()</code> will simply return <code>null</code> in this case, but if you would prefer it to throw an exception you can use the <code>failOnError</code> argument:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1) |
| <span class="java-keyword">try</span> { |
| p.save(failOnError: <span class="java-keyword">true</span>) |
| } |
| <span class="java-keyword">catch</span> (ValidationException e) { |
| // deal with exception |
| }</pre></div><p class="paragraph"/>You can even change the default behaviour with a setting in <code>Config.groovy</code>, as described in the <a href="../guide/single.html#configGORM" class="guide">section on configuration</a>. Just remember that when you are saving domain instances that have been bound with data provided by the user, the likelihood of validation exceptions is quite high and you won't want those exceptions propagating to the end user.<p class="paragraph"/>You can find out more about the subtleties of saving data in <a href="http://blog.springsource.com/2010/06/23/gorm-gotchas-part-1/" target="blank">this article</a> - a must read! |
| |
| |
| <a name="5.3.2 Deleting Objects"><!-- Legacy link --></a> |
| <h2 id="deletingObjects">6.3.2 Deleting Objects</h2> |
| An example of the <a href="../ref/Domain Classes/delete.html" class="domainClasses">delete</a> method can be seen below:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1) |
| p.delete()</pre></div><p class="paragraph"/>As with saves, Hibernate will use transactional write-behind to perform the delete; to perform the delete in-place you can use the <code>flush</code> argument:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1) |
| p.delete(flush: <span class="java-keyword">true</span>)</pre></div><p class="paragraph"/>Using the <code>flush</code> argument lets you catch any errors that occur during a delete. A common error that may occur is if you violate a database constraint, although this is normally down to a programming or schema error. The following example shows how to catch a <code>DataIntegrityViolationException</code> that is thrown when you violate the database constraints:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1)<p class="paragraph"/><span class="java-keyword">try</span> { |
| p.delete(flush: <span class="java-keyword">true</span>) |
| } |
| <span class="java-keyword">catch</span> (org.springframework.dao.DataIntegrityViolationException e) { |
| flash.message = <span class="java-quote">"Could not delete person ${p.name}"</span> |
| redirect(action: <span class="java-quote">"show"</span>, id: p.id) |
| }</pre></div><p class="paragraph"/>Note that Grails does not supply a <code>deleteAll</code> method as deleting data is discouraged and can often be avoided through boolean flags/logic.<p class="paragraph"/>If you really need to batch delete data you can use the <a href="../ref/Domain Classes/executeUpdate.html" class="domainClasses">executeUpdate</a> method to do batch DML statements:<p class="paragraph"/><div class="code"><pre>Customer.executeUpdate(<span class="java-quote">"delete Customer c where c.name = :oldName"</span>, |
| [oldName: <span class="java-quote">"Fred"</span>])</pre></div><p class="paragraph"/> |
| |
| <a name="5.3.3 Understanding Cascading Updates and Deletes"><!-- Legacy link --></a> |
| <h2 id="cascades">6.3.3 Understanding Cascading Updates and Deletes</h2> |
| It is critical that you understand how cascading updates and deletes work when using GORM. The key part to remember is the <code>belongsTo</code> setting which controls which class "owns" a relationship.<p class="paragraph"/>Whether it is a one-to-one, one-to-many or many-to-many, defining <code>belongsTo</code> will result in updates cascading from the owning class to its dependant (the other side of the relationship), and for many-/one-to-one and one-to-many relationships deletes will also cascade.<p class="paragraph"/>If you <em class="italic">do not</em> define <code>belongsTo</code> then no cascades will happen and you will have to manually save each object (except in the case of the one-to-many, in which case saves will cascade automatically if a new instance is in a <code>hasMany</code> collection).<p class="paragraph"/>Here is an example:<p class="paragraph"/><div class="code"><pre>class Airport { |
| <span class="java-object">String</span> name |
| <span class="java-keyword">static</span> hasMany = [flights: Flight] |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Flight { |
| <span class="java-object">String</span> number |
| <span class="java-keyword">static</span> belongsTo = [airport: Airport] |
| }</pre></div><p class="paragraph"/>If I now create an <code>Airport</code> and add some <code>Flight</code>s to it I can save the <code>Airport</code> and have the updates cascaded down to each flight, hence saving the whole object graph:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">new</span> Airport(name: <span class="java-quote">"Gatwick"</span>) |
| .addToFlights(<span class="java-keyword">new</span> Flight(number: <span class="java-quote">"BA3430"</span>)) |
| .addToFlights(<span class="java-keyword">new</span> Flight(number: <span class="java-quote">"EZ0938"</span>)) |
| .save()</pre></div><p class="paragraph"/>Conversely if I later delete the <code>Airport</code> all <code>Flight</code>s associated with it will also be deleted:<p class="paragraph"/><div class="code"><pre>def airport = Airport.findByName(<span class="java-quote">"Gatwick"</span>) |
| airport.delete()</pre></div><p class="paragraph"/>However, if I were to remove <code>belongsTo</code> then the above cascading deletion code <strong class="bold">would not work</strong>. To understand this better take a look at the summaries below that describe the default behaviour of GORM with regards to specific associations. Also read <a href="http://blog.springsource.com/2010/07/02/gorm-gotchas-part-2/" target="blank">part 2</a> of the GORM Gotchas series of articles to get a deeper understanding of relationships and cascading.<p class="paragraph"/><h5>Bidirectional one-to-many with belongsTo</h5><p class="paragraph"/><div class="code"><pre>class A { <span class="java-keyword">static</span> hasMany = [bees: B] }</pre></div><p class="paragraph"/><div class="code"><pre>class B { <span class="java-keyword">static</span> belongsTo = [a: A] }</pre></div><p class="paragraph"/>In the case of a bidirectional one-to-many where the many side defines a <code>belongsTo</code> then the cascade strategy is set to "ALL" for the one side and "NONE" for the many side.<p class="paragraph"/><h5>Unidirectional one-to-many</h5><p class="paragraph"/><div class="code"><pre>class A { <span class="java-keyword">static</span> hasMany = [bees: B] }</pre></div><p class="paragraph"/><div class="code"><pre>class B { }</pre></div><p class="paragraph"/>In the case of a unidirectional one-to-many where the many side defines no belongsTo then the cascade strategy is set to "SAVE-UPDATE".<p class="paragraph"/><h5>Bidirectional one-to-many, no belongsTo</h5><p class="paragraph"/><div class="code"><pre>class A { <span class="java-keyword">static</span> hasMany = [bees: B] }</pre></div><p class="paragraph"/><div class="code"><pre>class B { A a }</pre></div><p class="paragraph"/>In the case of a bidirectional one-to-many where the many side does not define a <code>belongsTo</code> then the cascade strategy is set to "SAVE-UPDATE" for the one side and "NONE" for the many side.<p class="paragraph"/><h5>Unidirectional one-to-one with belongsTo</h5><p class="paragraph"/><div class="code"><pre>class A { }</pre></div><p class="paragraph"/><div class="code"><pre>class B { <span class="java-keyword">static</span> belongsTo = [a: A] }</pre></div><p class="paragraph"/>In the case of a unidirectional one-to-one association that defines a <code>belongsTo</code> then the cascade strategy is set to "ALL" for the owning side of the relationship (A->B) and "NONE" from the side that defines the <code>belongsTo</code> (B->A)<p class="paragraph"/>Note that if you need further control over cascading behaviour, you can use the <a href="../guide/single.html#ormdsl" class="guide">ORM DSL</a>. |
| |
| |
| <a name="5.3.4 Eager and Lazy Fetching"><!-- Legacy link --></a> |
| <h2 id="fetching">6.3.4 Eager and Lazy Fetching</h2> |
| Associations in GORM are by default lazy. This is best explained by example:<p class="paragraph"/><div class="code"><pre>class Airport { |
| <span class="java-object">String</span> name |
| <span class="java-keyword">static</span> hasMany = [flights: Flight] |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Flight { |
| <span class="java-object">String</span> number |
| Location destination |
| <span class="java-keyword">static</span> belongsTo = [airport: Airport] |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Location { |
| <span class="java-object">String</span> city |
| <span class="java-object">String</span> country |
| }</pre></div><p class="paragraph"/>Given the above domain classes and the following code:<p class="paragraph"/><div class="code"><pre>def airport = Airport.findByName(<span class="java-quote">"Gatwick"</span>) |
| <span class="java-keyword">for</span> (flight in airport.flights) { |
| println flight.destination.city |
| }</pre></div><p class="paragraph"/>GORM will execute a single SQL query to fetch the <code>Airport</code> instance, another to get its flights, and then 1 extra query for <em class="italic">each iteration</em> over the <code>flights</code> association to get the current flight's destination. In other words you get N+1 queries (if you exclude the original one to get the airport).<p class="paragraph"/><h3>Configuring Eager Fetching</h3><p class="paragraph"/>An alternative approach that avoids the N+1 queries is to use eager fetching, which can be specified as follows:<p class="paragraph"/><div class="code"><pre>class Airport { |
| <span class="java-object">String</span> name |
| <span class="java-keyword">static</span> hasMany = [flights: Flight] |
| <span class="java-keyword">static</span> mapping = { |
| flights lazy: <span class="java-keyword">false</span> |
| } |
| }</pre></div><p class="paragraph"/>In this case the <code>flights</code> association will be loaded at the same time as its <code>Airport</code> instance, although a second query will be executed to fetch the collection. You can also use <code>fetch: 'join'</code> instead of <code>lazy: false</code> , in which case GORM will only execute a single query to get the airports and their flights. This works well for single-ended associations, but you need to be careful with one-to-manys. Queries will work as you'd expect right up to the moment you add a limit to the number of results you want. At that point, you will likely end up with fewer results than you were expecting. The reason for this is quite technical but ultimately the problem arises from GORM using a left outer join.<p class="paragraph"/>So, the recommendation is currently to use <code>fetch: 'join'</code> for single-ended associations and <code>lazy: false</code> for one-to-manys.<p class="paragraph"/>Be careful how and where you use eager loading because you could load your entire database into memory with too many eager associations. You can find more information on the mapping options in the <a href="../guide/single.html#fetchingDSL" class="guide">section on the ORM DSL</a>.<p class="paragraph"/><h3>Using Batch Fetching</h3><p class="paragraph"/>Although eager fetching is appropriate for some cases, it is not always desirable. If you made everything eager you could quite possibly load your entire database into memory resulting in performance and memory problems. An alternative to eager fetching is to use batch fetching. You can configure Hibernate to lazily fetch results in "batches". For example:<p class="paragraph"/><div class="code"><pre>class Airport { |
| <span class="java-object">String</span> name |
| <span class="java-keyword">static</span> hasMany = [flights: Flight] |
| <span class="java-keyword">static</span> mapping = { |
| flights batchSize: 10 |
| } |
| }</pre></div><p class="paragraph"/>In this case, due to the <code>batchSize</code> argument, when you iterate over the <code>flights</code> association, Hibernate will fetch results in batches of 10. For example if you had an <code>Airport</code> that had 30 flights, if you didn't configure batch fetching you would get 1 query to fetch the <code>Airport</code> and then <code>30</code> queries to fetch each flight. With batch fetching you get 1 query to fetch the <code>Airport</code> and 3 queries to fetch each <code>Flight</code> in batches of 10. In other words, batch fetching is an optimization of the lazy fetching strategy. Batch fetching can also be configured at the class level as follows:<p class="paragraph"/><div class="code"><pre>class Flight { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| batchSize 10 |
| } |
| }</pre></div><p class="paragraph"/>Check out <a href="http://blog.springsource.com/2010/07/28/gorm-gotchas-part-3/" target="blank">part 3</a> of the GORM Gotchas series for more in-depth coverage of this tricky topic. |
| |
| |
| <a name="5.3.5 Pessimistic and Optimistic Locking"><!-- Legacy link --></a> |
| <h2 id="locking">6.3.5 Pessimistic and Optimistic Locking</h2> |
| <h4>Optimistic Locking</h4><p class="paragraph"/>By default GORM classes are configured for optimistic locking. Optimistic locking is a feature of Hibernate which involves storing a version value in a special <code>version</code> column in the database that is incremented after each update.<p class="paragraph"/>The <code>version</code> column gets read into a <code>version</code> property that contains the current versioned state of persistent instance which you can access:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10)<p class="paragraph"/>println airport.version</pre></div><p class="paragraph"/>When you perform updates Hibernate will automatically check the version property against the version column in the database and if they differ will throw a <a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/StaleObjectStateException.html" class="api">StaleObjectException</a>. This will roll back the transaction if one is active.<p class="paragraph"/>This is useful as it allows a certain level of atomicity without resorting to pessimistic locking that has an inherit performance penalty. The downside is that you have to deal with this exception if you have highly concurrent writes. This requires flushing the session:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10)<p class="paragraph"/><span class="java-keyword">try</span> { |
| airport.name = <span class="java-quote">"Heathrow"</span> |
| airport.save(flush: <span class="java-keyword">true</span>) |
| } |
| <span class="java-keyword">catch</span> (org.springframework.dao.OptimisticLockingFailureException e) { |
| // deal with exception |
| }</pre></div><p class="paragraph"/>The way you deal with the exception depends on the application. You could attempt a programmatic merge of the data or go back to the user and ask them to resolve the conflict.<p class="paragraph"/>Alternatively, if it becomes a problem you can resort to pessimistic locking.<p class="paragraph"/><blockquote class="note"> |
| The <code>version</code> will only be updated after flushing the session. |
| </blockquote><p class="paragraph"/><h4>Pessimistic Locking</h4><p class="paragraph"/>Pessimistic locking is equivalent to doing a SQL "SELECT * FOR UPDATE" statement and locking a row in the database. This has the implication that other read operations will be blocking until the lock is released.<p class="paragraph"/>In Grails pessimistic locking is performed on an existing instance with the <a href="../ref/Domain Classes/lock.html" class="domainClasses">lock</a> method:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10) |
| airport.lock() // lock <span class="java-keyword">for</span> update |
| airport.name = <span class="java-quote">"Heathrow"</span> |
| airport.save()</pre></div><p class="paragraph"/>Grails will automatically deal with releasing the lock for you once the transaction has been committed. However, in the above case what we are doing is "upgrading" from a regular SELECT to a SELECT..FOR UPDATE and another thread could still have updated the record in between the call to <code>get()</code> and the call to <code>lock()</code>.<p class="paragraph"/>To get around this problem you can use the static <a href="../ref/Domain Classes/lock.html" class="domainClasses">lock</a> method that takes an id just like <a href="../ref/Domain Classes/get.html" class="domainClasses">get</a>:<p class="paragraph"/><div class="code"><pre>def airport = Airport.lock(10) // lock <span class="java-keyword">for</span> update |
| airport.name = <span class="java-quote">"Heathrow"</span> |
| airport.save()</pre></div><p class="paragraph"/>In this case only SELECT..FOR UPDATE is issued.<p class="paragraph"/>As well as the <a href="../ref/Domain Classes/lock.html" class="domainClasses">lock</a> method you can also obtain a pessimistic locking using queries. For example using a dynamic finder:<p class="paragraph"/><div class="code"><pre>def airport = Airport.findByName(<span class="java-quote">"Heathrow"</span>, [lock: <span class="java-keyword">true</span>])</pre></div><p class="paragraph"/>Or using criteria:<p class="paragraph"/><div class="code"><pre>def airport = Airport.createCriteria().get { |
| eq('name', 'Heathrow') |
| lock <span class="java-keyword">true</span> |
| }</pre></div><p class="paragraph"/> |
| |
| <a name="5.3.6 Modification Checking"><!-- Legacy link --></a> |
| <h2 id="modificationChecking">6.3.6 Modification Checking</h2> |
| Once you have loaded and possibly modified a persistent domain class instance, it isn't straightforward to retrieve the original values. If you try to reload the instance using <a href="../ref/Domain Classes/get.html" class="domainClasses">get</a> Hibernate will return the current modified instance from its Session cache. Reloading using another query would trigger a flush which could cause problems if your data isn't ready to be flushed yet. So GORM provides some methods to retrieve the original values that Hibernate caches when it loads the instance (which it uses for dirty checking).<p class="paragraph"/><h4>isDirty</h4><p class="paragraph"/>You can use the <a href="../ref/Domain Classes/isDirty.html" class="domainClasses">isDirty</a> method to check if any field has been modified:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10) |
| assert !airport.isDirty()<p class="paragraph"/>airport.properties = params |
| <span class="java-keyword">if</span> (airport.isDirty()) { |
| // <span class="java-keyword">do</span> something based on changed state |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| <code>isDirty()</code> does not currently check collection associations, but it does check all other persistent properties and associations. |
| </blockquote><p class="paragraph"/>You can also check if individual fields have been modified:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10) |
| assert !airport.isDirty()<p class="paragraph"/>airport.properties = params |
| <span class="java-keyword">if</span> (airport.isDirty('name')) { |
| // <span class="java-keyword">do</span> something based on changed name |
| }</pre></div><p class="paragraph"/><h4>getDirtyPropertyNames</h4><p class="paragraph"/>You can use the <a href="../ref/Domain Classes/getDirtyPropertyNames.html" class="domainClasses">getDirtyPropertyNames</a> method to retrieve the names of modified fields; this may be empty but will not be null:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10) |
| assert !airport.isDirty()<p class="paragraph"/>airport.properties = params |
| def modifiedFieldNames = airport.getDirtyPropertyNames() |
| <span class="java-keyword">for</span> (fieldName in modifiedFieldNames) { |
| // <span class="java-keyword">do</span> something based on changed value |
| }</pre></div><p class="paragraph"/><h4>getPersistentValue</h4><p class="paragraph"/>You can use the <a href="../ref/Domain Classes/getPersistentValue.html" class="domainClasses">getPersistentValue</a> method to retrieve the value of a modified field:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10) |
| assert !airport.isDirty()<p class="paragraph"/>airport.properties = params |
| def modifiedFieldNames = airport.getDirtyPropertyNames() |
| <span class="java-keyword">for</span> (fieldName in modifiedFieldNames) { |
| def currentValue = airport.<span class="java-quote">"$fieldName"</span> |
| def originalValue = airport.getPersistentValue(fieldName) |
| <span class="java-keyword">if</span> (currentValue != originalValue) { |
| // <span class="java-keyword">do</span> something based on changed value |
| } |
| }</pre></div><p class="paragraph"/> |
| |
| <a name="5.4 Querying with GORM"><!-- Legacy link --></a> |
| <h2 id="querying">6.4 Querying with GORM</h2> |
| GORM supports a number of powerful ways to query from dynamic finders, to criteria to Hibernate's object oriented query language HQL. Depending on the complexity of the query you have the following options in order of flexibility and power: |
| <ul class="star"> |
| <li>Dynamic Finders</li> |
| <li>Where Queries</li> |
| <li>Criteria Queries</li> |
| <li>Hibernate Query Language (HQL)</li> |
| </ul><p class="paragraph"/>In addition, Groovy's ability to manipulate collections with <a href="http://groovy.codehaus.org/GPath" target="blank">GPath</a> and methods like sort, findAll and so on combined with GORM results in a powerful combination.<p class="paragraph"/>However, let's start with the basics.<p class="paragraph"/><h4>Listing instances</h4><p class="paragraph"/>Use the <a href="../ref/Domain Classes/list.html" class="domainClasses">list</a> method to obtain all instances of a given class:<p class="paragraph"/><div class="code"><pre>def books = Book.list()</pre></div><p class="paragraph"/>The <a href="../ref/Domain Classes/list.html" class="domainClasses">list</a> method supports arguments to perform pagination:<p class="paragraph"/><div class="code"><pre>def books = Book.list(offset:10, max:20)</pre></div><p class="paragraph"/>as well as sorting:<p class="paragraph"/><div class="code"><pre>def books = Book.list(sort:<span class="java-quote">"title"</span>, order:<span class="java-quote">"asc"</span>)</pre></div><p class="paragraph"/>Here, the <code>sort</code> argument is the name of the domain class property that you wish to sort on, and the <code>order</code> argument is either <code>asc</code> for <strong class="bold">asc</strong>ending or <code>desc</code> for <strong class="bold">desc</strong>ending.<p class="paragraph"/><h4>Retrieval by Database Identifier</h4><p class="paragraph"/>The second basic form of retrieval is by database identifier using the <a href="../ref/Domain Classes/get.html" class="domainClasses">get</a> method:<p class="paragraph"/><div class="code"><pre>def book = Book.get(23)</pre></div><p class="paragraph"/>You can also obtain a list of instances for a set of identifiers using <a href="../ref/Domain Classes/getAll.html" class="domainClasses">getAll</a>:<p class="paragraph"/><div class="code"><pre>def books = Book.getAll(23, 93, 81)</pre></div> |
| |
| |
| <a name="5.4.1 Dynamic Finders"><!-- Legacy link --></a> |
| <h2 id="finders">6.4.1 Dynamic Finders</h2> |
| GORM supports the concept of <strong class="bold">dynamic finders</strong>. A dynamic finder looks like a static method invocation, but the methods themselves don't actually exist in any form at the code level.<p class="paragraph"/>Instead, a method is auto-magically generated using code synthesis at runtime, based on the properties of a given class. Take for example the <code>Book</code> class:<p class="paragraph"/><div class="code"><pre>class Book { |
| <span class="java-object">String</span> title |
| Date releaseDate |
| Author author |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Author { |
| <span class="java-object">String</span> name |
| }</pre></div><p class="paragraph"/>The <code>Book</code> class has properties such as <code>title</code>, <code>releaseDate</code> and <code>author</code>. These can be used by the <a href="../ref/Domain Classes/findBy.html" class="domainClasses">findBy</a> and <a href="../ref/Domain Classes/findAllBy.html" class="domainClasses">findAllBy</a> methods in the form of "method expressions":<p class="paragraph"/><div class="code"><pre>def book = Book.findByTitle(<span class="java-quote">"The Stand"</span>)<p class="paragraph"/>book = Book.findByTitleLike(<span class="java-quote">"Harry Pot%"</span>)<p class="paragraph"/>book = Book.findByReleaseDateBetween(firstDate, secondDate)<p class="paragraph"/>book = Book.findByReleaseDateGreaterThan(someDate)<p class="paragraph"/>book = Book.findByTitleLikeOrReleaseDateLessThan(<span class="java-quote">"%Something%"</span>, someDate)</pre></div><p class="paragraph"/><h4>Method Expressions</h4><p class="paragraph"/>A method expression in GORM is made up of the prefix such as <a href="../ref/Domain Classes/findBy.html" class="domainClasses">findBy</a> followed by an expression that combines one or more properties. The basic form is:<p class="paragraph"/><div class="code"><pre>Book.findBy([Property][Comparator][<span class="java-object">Boolean</span> Operator])?[Property][Comparator]</pre></div><p class="paragraph"/>The tokens marked with a '?' are optional. Each comparator changes the nature of the query. For example:<p class="paragraph"/><div class="code"><pre>def book = Book.findByTitle(<span class="java-quote">"The Stand"</span>)<p class="paragraph"/>book = Book.findByTitleLike(<span class="java-quote">"Harry Pot%"</span>)</pre></div><p class="paragraph"/>In the above example the first query is equivalent to equality whilst the latter, due to the <code>Like</code> comparator, is equivalent to a SQL <code>like</code> expression.<p class="paragraph"/>The possible comparators include: |
| <ul class="star"> |
| <li><code>InList</code> - In the list of given values</li> |
| <li><code>LessThan</code> - less than a given value</li> |
| <li><code>LessThanEquals</code> - less than or equal a give value</li> |
| <li><code>GreaterThan</code> - greater than a given value</li> |
| <li><code>GreaterThanEquals</code> - greater than or equal a given value</li> |
| <li><code>Like</code> - Equivalent to a SQL like expression</li> |
| <li><code>Ilike</code> - Similar to a <code>Like</code>, except case insensitive</li> |
| <li><code>NotEqual</code> - Negates equality</li> |
| <li><code>InRange</code> - Between the <code>from</code> and <code>to</code> values of a Groovy Range</li> |
| <li><code>Rlike</code> - Performs a Regexp LIKE in MySQL or Oracle otherwise falls back to <code>Like</code></li> |
| <li><code>Between</code> - Between two values (requires two arguments)</li> |
| <li><code>IsNotNull</code> - Not a null value (doesn't take an argument)</li> |
| <li><code>IsNull</code> - Is a null value (doesn't take an argument)</li> |
| </ul><p class="paragraph"/>Notice that the last three require different numbers of method arguments compared to the rest, as demonstrated in the following example:<p class="paragraph"/><div class="code"><pre>def now = <span class="java-keyword">new</span> Date() |
| def lastWeek = now - 7 |
| def book = Book.findByReleaseDateBetween(lastWeek, now)<p class="paragraph"/>books = Book.findAllByReleaseDateIsNull() |
| books = Book.findAllByReleaseDateIsNotNull()</pre></div><p class="paragraph"/><h4>Boolean logic (AND/OR)</h4><p class="paragraph"/>Method expressions can also use a boolean operator to combine two or more criteria:<p class="paragraph"/><div class="code"><pre>def books = Book.findAllByTitleLikeAndReleaseDateGreaterThan( |
| <span class="java-quote">"%Java%"</span>, <span class="java-keyword">new</span> Date() - 30)</pre></div><p class="paragraph"/>In this case we're using <code>And</code> in the middle of the query to make sure both conditions are satisfied, but you could equally use <code>Or</code>:<p class="paragraph"/><div class="code"><pre>def books = Book.findAllByTitleLikeOrReleaseDateGreaterThan( |
| <span class="java-quote">"%Java%"</span>, <span class="java-keyword">new</span> Date() - 30)</pre></div><p class="paragraph"/>You can combine as many criteria as you like, but they must all be combined with <code>And</code> or all <code>Or</code>. If you need to combine <code>And</code> and <code>Or</code> or if the number of criteria creates a very long method name, just convert the query to a <a href="../guide/single.html#criteria" class="guide">Criteria</a> or <a href="../guide/single.html#hql" class="guide">HQL</a> query.<p class="paragraph"/><h4>Querying Associations</h4><p class="paragraph"/>Associations can also be used within queries:<p class="paragraph"/><div class="code"><pre>def author = Author.findByName(<span class="java-quote">"Stephen King"</span>)<p class="paragraph"/>def books = author ? Book.findAllByAuthor(author) : []</pre></div><p class="paragraph"/>In this case if the <code>Author</code> instance is not null we use it in a query to obtain all the <code>Book</code> instances for the given <code>Author</code>.<p class="paragraph"/><h4>Pagination and Sorting</h4><p class="paragraph"/>The same pagination and sorting parameters available on the <a href="../ref/Domain Classes/list.html" class="domainClasses">list</a> method can also be used with dynamic finders by supplying a map as the final parameter:<p class="paragraph"/><div class="code"><pre>def books = Book.findAllByTitleLike(<span class="java-quote">"Harry Pot%"</span>, |
| [max: 3, offset: 2, sort: <span class="java-quote">"title"</span>, order: <span class="java-quote">"desc"</span>])</pre></div> |
| |
| |
| |
| <h2 id="whereQueries">6.4.2 Where Queries</h2> |
| The <code>where</code> method, introduced in Grails 2.0, builds on the support for <a href="../guide/single.html#detachedCriteria" class="guide">Detached Criteria</a> by providing an enhanced, compile-time checked query DSL for common queries. The <code>where</code> method is more flexible than dynamic finders, less verbose than criteria and provides a powerful mechanism to compose queries.<p class="paragraph"/><h4>Basic Querying</h4><p class="paragraph"/>The <code>where</code> method accepts a closure that looks very similar to Groovy's regular collection methods. The closure should define the logical criteria in regular Groovy syntax, for example:<p class="paragraph"/><div class="code"><pre>def query = Person.where { |
| firstName == <span class="java-quote">"Bart"</span> |
| } |
| Person bart = query.find()</pre></div><p class="paragraph"/>The returned object is a <code>DetachedCriteria</code> instance, which means it is not associated with any particular database connection or session. This means you can use the <code>where</code> method to define common queries at the class level:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-keyword">static</span> simpsons = where { |
| lastName == <span class="java-quote">"Simpson"</span> |
| } |
| … |
| } |
| … |
| Person.simpsons.each { |
| println it.firstname |
| }</pre></div><p class="paragraph"/>Query execution is lazy and only happens upon usage of the <a href="../guide/single.html#detachedCriteria" class="guide">DetachedCriteria</a> instance. If you want to execute a where-style query immediately there are variations of the <code>findAll</code> and <code>find</code> methods to accomplish this:<p class="paragraph"/><div class="code"><pre>def results = Person.findAll { |
| lastName == <span class="java-quote">"Simpson"</span> |
| } |
| def results = Person.findAll(sort:<span class="java-quote">"firstName"</span>) { |
| lastName == <span class="java-quote">"Simpson"</span> |
| } |
| Person p = Person.find { firstName == <span class="java-quote">"Bart"</span> }</pre></div><p class="paragraph"/>Each Groovy operator maps onto a regular criteria method. The following table provides a map of Groovy operators to methods:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Operator</th><th>Criteria Method</th><th>Description</th></tr><tr class="table-odd"><td><strong class="bold">==</strong></td><td>eq</td><td>Equal to</td></tr><tr class="table-even"><td><strong class="bold">!=</strong></td><td>ne</td><td>Not equal to</td></tr><tr class="table-odd"><td><strong class="bold">></strong></td><td>gt</td><td>Greater than</td></tr><tr class="table-even"><td><strong class="bold"><</strong></td><td>lt</td><td>Less than</td></tr><tr class="table-odd"><td><strong class="bold">>=</strong></td><td>ge</td><td>Greater than or equal to</td></tr><tr class="table-even"><td><strong class="bold"><=</strong></td><td>le</td><td>Less than or equal to</td></tr><tr class="table-odd"><td><strong class="bold">in</strong></td><td>inList</td><td>Contained within the given list</td></tr><tr class="table-even"><td><strong class="bold">==~</strong></td><td>like</td><td>Like a given string</td></tr><tr class="table-odd"><td><strong class="bold">=~</strong></td><td>ilike</td><td>Case insensitive like</td></tr></table><p class="paragraph"/>It is possible use regular Groovy comparison operators and logic to formulate complex queries:<p class="paragraph"/><div class="code"><pre>def query = Person.where { |
| (lastName != <span class="java-quote">"Simpson"</span> && firstName != <span class="java-quote">"Fred"</span>) || (firstName == <span class="java-quote">"Bart"</span> && age > 9) |
| } |
| def results = query.list(sort:<span class="java-quote">"firstName"</span>)</pre></div><p class="paragraph"/>The Groovy regex matching operators map onto like and ilike queries unless the expression on the right hand side is a <code>Pattern</code> object, in which case they map onto an <code>rlike</code> query:<p class="paragraph"/><div class="code"><pre>def query = Person.where { |
| firstName ==~ ~/B.+/ |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| Note that <code>rlike</code> queries are only supported if the underlying database supports regular expressions |
| </blockquote><p class="paragraph"/>A <code>between</code> criteria query can be done by combining the <code>in</code> keyword with a range:<p class="paragraph"/><div class="code"><pre>def query = Person.where { |
| age in 18..65 |
| }</pre></div><p class="paragraph"/>Finally, you can do <code>isNull</code> and <code>isNotNull</code> style queries by using <code>null</code> with regular comparison operators:<p class="paragraph"/><div class="code"><pre>def query = Person.where { |
| middleName == <span class="java-keyword">null</span> |
| }</pre></div><p class="paragraph"/><h4>Query Composition</h4><p class="paragraph"/>Since the return value of the <code>where</code> method is a <a href="../guide/single.html#detachedCriteria" class="guide">DetachedCriteria</a> instance you can compose new queries from the original query:<p class="paragraph"/><div class="code"><pre>def query = Person.where { |
| lastName == <span class="java-quote">"Simpson"</span> |
| } |
| def bartQuery = query.where { |
| firstName == <span class="java-quote">"Bart"</span> |
| } |
| Person p = bartQuery.find()</pre></div><p class="paragraph"/>Note that you cannot pass a closure defined as a variable into the <code>where</code> method unless it has been explicitly cast to a <code>DetachedCriteria</code> instance. In other words the following will produce an error:<p class="paragraph"/><div class="code"><pre>def callable = { |
| lastName == <span class="java-quote">"Simpson"</span> |
| } |
| def query = Person.where(callable)</pre></div><p class="paragraph"/>The above must be written as follows:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.gorm.DetachedCriteria<p class="paragraph"/>def callable = { |
| lastName == <span class="java-quote">"Simpson"</span> |
| } as DetachedCriteria<Person> |
| def query = Person.where(callable)</pre></div><p class="paragraph"/>As you can see the closure definition is cast (using the Groovy <code>as</code> keyword) to a <a href="../guide/single.html#detachedCriteria" class="guide">DetachedCriteria</a> instance targeted at the <code>Person</code> class.<p class="paragraph"/><h4>Conjunction, Disjunction and Negation</h4><p class="paragraph"/>As mentioned previously you can combine regular Groovy logical operators (<code>||</code> and <code>&&</code>) to form conjunctions and disjunctions:<p class="paragraph"/><div class="code"><pre>def query = Person.where { |
| (lastName != <span class="java-quote">"Simpson"</span> && firstName != <span class="java-quote">"Fred"</span>) || (firstName == <span class="java-quote">"Bart"</span> && age > 9) |
| }</pre></div><p class="paragraph"/>You can also negate a logical comparison using <code>!</code>:<p class="paragraph"/><div class="code"><pre>def query = Person.where { |
| firstName == <span class="java-quote">"Fred"</span> && !(lastName == 'Simpson') |
| }</pre></div><p class="paragraph"/><h4>Property Comparison Queries</h4><p class="paragraph"/>If you use a property name on both the left hand and right side of a comparison expression then the appropriate property comparison criteria is automatically used:<p class="paragraph"/><div class="code"><pre>def query = Person.where { |
| firstName == lastName |
| }</pre></div><p class="paragraph"/>The following table described how each comparison operator maps onto each criteria property comparison method:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Operator</th><th>Criteria Method</th><th>Description</th></tr><tr class="table-odd"><td><strong class="bold">==</strong></td><td>eqProperty</td><td>Equal to</td></tr><tr class="table-even"><td><strong class="bold">!=</strong></td><td>neProperty</td><td>Not equal to</td></tr><tr class="table-odd"><td><strong class="bold">></strong></td><td>gtProperty</td><td>Greater than</td></tr><tr class="table-even"><td><strong class="bold"><</strong></td><td>ltProperty</td><td>Less than</td></tr><tr class="table-odd"><td><strong class="bold">>=</strong></td><td>geProperty</td><td>Greater than or equal to</td></tr><tr class="table-even"><td><strong class="bold"><=</strong></td><td>leProperty</td><td>Less than or equal to</td></tr></table><p class="paragraph"/><h4>Querying Associations</h4><p class="paragraph"/>Associations can be queried by using the dot operator to specify the property name of the association to be queried:<p class="paragraph"/><div class="code"><pre>def query = Pet.where { |
| owner.firstName == <span class="java-quote">"Joe"</span> || owner.firstName == <span class="java-quote">"Fred"</span> |
| }</pre></div><p class="paragraph"/>You can group multiple criterion inside a closure method call where the name of the method matches the association name:<p class="paragraph"/><div class="code"><pre>def query = Person.where { |
| pets { name == <span class="java-quote">"Jack"</span> || name == <span class="java-quote">"Joe"</span> } |
| }</pre></div><p class="paragraph"/>This technique can be combined with other top-level criteria:<p class="paragraph"/><div class="code"><pre>def query = Person.where { |
| pets { name == <span class="java-quote">"Jack"</span> } || firstName == <span class="java-quote">"Ed"</span> |
| }</pre></div><p class="paragraph"/>For collection associations it is possible to apply queries to the size of the collection:<p class="paragraph"/><div class="code"><pre>def query = Person.where { |
| pets.size() == 2 |
| }</pre></div><p class="paragraph"/>The following table shows which operator maps onto which criteria method for each size() comparison:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Operator</th><th>Criteria Method</th><th>Description</th></tr><tr class="table-odd"><td><strong class="bold">==</strong></td><td>sizeEq</td><td>The collection size is equal to</td></tr><tr class="table-even"><td><strong class="bold">!=</strong></td><td>sizeNe</td><td>The collection size is not equal to</td></tr><tr class="table-odd"><td><strong class="bold">></strong></td><td>sizeGt</td><td>The collection size is greater than</td></tr><tr class="table-even"><td><strong class="bold"><</strong></td><td>sizeLt</td><td>The collection size is less than</td></tr><tr class="table-odd"><td><strong class="bold">>=</strong></td><td>sizeGe</td><td>The collection size is greater than or equal to</td></tr><tr class="table-even"><td><strong class="bold"><=</strong></td><td>sizeLe</td><td>The collection size is less than or equal to</td></tr></table><p class="paragraph"/> |
| <h4>Subqueries</h4><p class="paragraph"/>It is possible to execute subqueries within where queries. For example to find all the people older than the average age the following query can be used:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">final</span> query = Person.where { |
| age > avg(age) |
| }</pre></div><p class="paragraph"/>The following table lists the possible subqueries:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Method</th><th>Description</th></tr><tr class="table-odd"><td><strong class="bold">avg</strong></td><td>The average of all values</td></tr><tr class="table-even"><td><strong class="bold">sum</strong></td><td>The sum of all values</td></tr><tr class="table-odd"><td><strong class="bold">max</strong></td><td>The maximum value</td></tr><tr class="table-even"><td><strong class="bold">min</strong></td><td>The minimum value</td></tr><tr class="table-odd"><td><strong class="bold">count</strong></td><td>The count of all values</td></tr><tr class="table-even"><td><strong class="bold">property</strong></td><td>Retrieves a property of the resulting entities</td></tr></table><p class="paragraph"/>You can apply additional criteria to any subquery by using the <code>of</code> method and passing in a closure containing the criteria:<p class="paragraph"/><div class="code"><pre>def query = Person.where { |
| age > avg(age).of { lastName == <span class="java-quote">"Simpson"</span> } && firstName == <span class="java-quote">"Homer"</span> |
| }</pre></div><p class="paragraph"/>Since the <code>property</code> subquery returns multiple results, the criterion used compares all results. For example the following query will find all people younger than people with the surname "Simpson":<p class="paragraph"/><div class="code"><pre>Person.where { |
| age < property(age).of { lastName == <span class="java-quote">"Simpson"</span> } |
| }</pre></div><p class="paragraph"/> |
| <h4>Other Functions</h4><p class="paragraph"/>There are several functions available to you within the context of a query. These are summarized in the table below:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Method</th><th>Description</th></tr><tr class="table-odd"><td><strong class="bold">second</strong></td><td>The second of a date property</td></tr><tr class="table-even"><td><strong class="bold">minute</strong></td><td>The minute of a date property</td></tr><tr class="table-odd"><td><strong class="bold">hour</strong></td><td>The hour of a date property</td></tr><tr class="table-even"><td><strong class="bold">day</strong></td><td>The day of the month of a date property</td></tr><tr class="table-odd"><td><strong class="bold">month</strong></td><td>The month of a date property</td></tr><tr class="table-even"><td><strong class="bold">year</strong></td><td>The year of a date property</td></tr><tr class="table-odd"><td><strong class="bold">lower</strong></td><td>Converts a string property to upper case</td></tr><tr class="table-even"><td><strong class="bold">upper</strong></td><td>Converts a string property to lower case</td></tr><tr class="table-odd"><td><strong class="bold">length</strong></td><td>The length of a string property</td></tr><tr class="table-even"><td><strong class="bold">trim</strong></td><td>Trims a string property</td></tr></table><p class="paragraph"/><blockquote class="note"> |
| Currently functions can only be applied to properties or associations of domain classes. You cannot, for example, use a function on a result of a subquery. |
| </blockquote><p class="paragraph"/>For example the following query can be used to find all pet's born in 2011:<p class="paragraph"/><div class="code"><pre>def query = Pet.where { |
| year(birthDate) == 2011 |
| }</pre></div><p class="paragraph"/>You can also apply functions to associations:<p class="paragraph"/><div class="code"><pre>def query = Person.where { |
| year(pets.birthDate) == 2009 |
| }</pre></div><p class="paragraph"/> |
| <h4>Batch Updates and Deletes</h4><p class="paragraph"/>Since each <code>where</code> method call returns a <a href="../guide/single.html#detachedCriteria" class="guide">DetachedCriteria</a> instance, you can use <code>where</code> queries to execute batch operations such as batch updates and deletes. For example, the following query will update all people with the surname "Simpson" to have the surname "Bloggs":<p class="paragraph"/><div class="code"><pre>def query = Person.where { |
| lastName == 'Simpson' |
| } |
| <span class="java-object">int</span> total = query.updateAll(lastName:<span class="java-quote">"Bloggs"</span>)</pre></div><p class="paragraph"/><blockquote class="note"> |
| Note that one limitation with regards to batch operations is that join queries (queries that query associations) are not allowed. |
| </blockquote><p class="paragraph"/>To batch delete records you can use the <code>deleteAll</code> method:<p class="paragraph"/><div class="code"><pre>def query = Person.where { |
| lastName == 'Simpson' |
| } |
| <span class="java-object">int</span> total = query.deleteAll()</pre></div> |
| |
| <a name="5.4.2 Criteria"><!-- Legacy link --></a> |
| <h2 id="criteria">6.4.3 Criteria</h2> |
| Criteria is an advanced way to query that uses a Groovy builder to construct potentially complex queries. It is a much better approach than building up query strings using a <code>StringBuffer</code>.<p class="paragraph"/>Criteria can be used either with the <a href="../ref/Domain Classes/createCriteria.html" class="domainClasses">createCriteria</a> or <a href="../ref/Domain Classes/withCriteria.html" class="domainClasses">withCriteria</a> methods. The builder uses Hibernate's Criteria API. The nodes on this builder map the static methods found in the <a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/criterion/Restrictions.html" class="api">Restrictions</a> class of the Hibernate Criteria API. For example:<p class="paragraph"/><div class="code"><pre>def c = Account.createCriteria() |
| def results = c { |
| between(<span class="java-quote">"balance"</span>, 500, 1000) |
| eq(<span class="java-quote">"branch"</span>, <span class="java-quote">"London"</span>) |
| or { |
| like(<span class="java-quote">"holderFirstName"</span>, <span class="java-quote">"Fred%"</span>) |
| like(<span class="java-quote">"holderFirstName"</span>, <span class="java-quote">"Barney%"</span>) |
| } |
| maxResults(10) |
| order(<span class="java-quote">"holderLastName"</span>, <span class="java-quote">"desc"</span>) |
| }</pre></div><p class="paragraph"/>This criteria will select up to 10 <code>Account</code> objects in a List matching the following criteria: |
| <ul class="star"> |
| <li><code>balance</code> is between 500 and 1000</li> |
| <li><code>branch</code> is 'London'</li> |
| <li><code>holderFirstName</code> starts with 'Fred' or 'Barney'</li> |
| </ul><p class="paragraph"/>The results will be sorted in descending order by <code>holderLastName</code>.<p class="paragraph"/>If no records are found with the above criteria, an empty List is returned.<p class="paragraph"/><h4>Conjunctions and Disjunctions</h4><p class="paragraph"/>As demonstrated in the previous example you can group criteria in a logical OR using an <code>or { }</code> block:<p class="paragraph"/><div class="code"><pre>or { |
| between(<span class="java-quote">"balance"</span>, 500, 1000) |
| eq(<span class="java-quote">"branch"</span>, <span class="java-quote">"London"</span>) |
| }</pre></div><p class="paragraph"/>This also works with logical AND:<p class="paragraph"/><div class="code"><pre>and { |
| between(<span class="java-quote">"balance"</span>, 500, 1000) |
| eq(<span class="java-quote">"branch"</span>, <span class="java-quote">"London"</span>) |
| }</pre></div><p class="paragraph"/>And you can also negate using logical NOT:<p class="paragraph"/><div class="code"><pre>not { |
| between(<span class="java-quote">"balance"</span>, 500, 1000) |
| eq(<span class="java-quote">"branch"</span>, <span class="java-quote">"London"</span>) |
| }</pre></div><p class="paragraph"/>All top level conditions are implied to be AND'd together.<p class="paragraph"/><h4>Querying Associations</h4><p class="paragraph"/>Associations can be queried by having a node that matches the property name. For example say the <code>Account</code> class had many <code>Transaction</code> objects:<p class="paragraph"/><div class="code"><pre>class Account { |
| … |
| <span class="java-keyword">static</span> hasMany = [transactions: Transaction] |
| … |
| }</pre></div><p class="paragraph"/>We can query this association by using the property name <code>transactions</code> as a builder node:<p class="paragraph"/><div class="code"><pre>def c = Account.createCriteria() |
| def now = <span class="java-keyword">new</span> Date() |
| def results = c.list { |
| transactions { |
| between('date', now - 10, now) |
| } |
| }</pre></div><p class="paragraph"/>The above code will find all the <code>Account</code> instances that have performed <code>transactions</code> within the last 10 days. |
| You can also nest such association queries within logical blocks:<p class="paragraph"/><div class="code"><pre>def c = Account.createCriteria() |
| def now = <span class="java-keyword">new</span> Date() |
| def results = c.list { |
| or { |
| between('created', now - 10, now) |
| transactions { |
| between('date', now - 10, now) |
| } |
| } |
| }</pre></div><p class="paragraph"/>Here we find all accounts that have either performed transactions in the last 10 days OR have been recently created in the last 10 days.<p class="paragraph"/><h4>Querying with Projections</h4><p class="paragraph"/>Projections may be used to customise the results. Define a "projections" node within the criteria builder tree to use projections. There are equivalent methods within the projections node to the methods found in the Hibernate <a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/criterion/Projections.html" class="api">Projections</a> class:<p class="paragraph"/><div class="code"><pre>def c = Account.createCriteria()<p class="paragraph"/>def numberOfBranches = c.get { |
| projections { |
| countDistinct('branch') |
| } |
| }</pre></div><p class="paragraph"/>When multiple fields are specified in the projection, a List of values will be returned. A single value will be returned otherwise.<p class="paragraph"/><h4>SQL Projections</h4><p class="paragraph"/>The criteria DSL provides access to Hibernate's SQL projection API.<p class="paragraph"/><div class="code"><pre>// Box is a domain class… |
| class Box { |
| <span class="java-object">int</span> width |
| <span class="java-object">int</span> height |
| }</pre></div><p class="paragraph"/><div class="code"><pre>// Use SQL projections to retrieve the perimeter and area of all of the Box instances… |
| def c = Box.createCriteria()<p class="paragraph"/>def results = c.list { |
| projections { |
| sqlProjection '(2 * (width + height)) as perimeter, (width * height) as area', ['perimeter', 'area'], [INTEGER, INTEGER] |
| } |
| }</pre></div><p class="paragraph"/>The first argument to the <code>sqlProjection</code> method is the SQL which defines the projections. The second argument is a list of |
| Strings which represent column aliases corresponding to the projected values expressed in the SQL. The third argument |
| is a list of <code>org.hibernate.type.Type</code> instances which correspond to the projected values expressed in the SQL. The API |
| supports all <code>org.hibernate.type.Type</code> objects but constants like INTEGER, LONG, FLOAT etc. are provided by the DSL which |
| correspond to all of the types defined in <code>org.hibernate.type.StandardBasicTypes</code>.<p class="paragraph"/>Consider that the following table represents the data in the |
| <code>BOX</code> table. |
| <table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>width</th><th>height</th></tr><tr class="table-odd"><td>2</td><td>7</td></tr><tr class="table-even"><td>2</td><td>8</td></tr><tr class="table-odd"><td>2</td><td>9</td></tr><tr class="table-even"><td>4</td><td>9</td></tr></table><p class="paragraph"/>The query above would return results like this:<p class="paragraph"/><div class="code"><pre>[[18, 14], [20, 16], [22, 18], [26, 36]]</pre></div><p class="paragraph"/>Each of the inner lists contains the 2 projected values for each <code>Box</code>, perimeter and area.<p class="paragraph"/><blockquote class="note"> |
| Note that if there are other references in scope wherever your criteria query is expressed that have names that conflict |
| with any of the type constants described above, the code in your criteria will refer to those references, not the type |
| constants provided by the DSL. In the unlikely event of that happening you can disambiguate the conflict by referring |
| to the fully qualified Hibernate type. For example <code>StandardBasicTypes.INTEGER</code> instead of <code>INTEGER</code>. |
| </blockquote><p class="paragraph"/>If only 1 value is being projected, the alias and the type do not need to be included in a list.<p class="paragraph"/><div class="code"><pre>def results = c.list { |
| projections { |
| sqlProjection 'sum(width * height) as totalArea', 'totalArea', INTEGER |
| } |
| }</pre></div><p class="paragraph"/>That query would return a single result with the value of 84 as the total area of all of the <code>Box</code> instances.<p class="paragraph"/>The DSL supports grouped projections with the <code>sqlGroupProjection</code> method.<p class="paragraph"/><div class="code"><pre>def results = c.list { |
| projections { |
| sqlGroupProjection 'width, sum(height) as combinedHeightsForThisWidth', 'width', ['width', 'combinedHeightsForThisWidth'], [INTEGER, INTEGER] |
| } |
| }</pre></div><p class="paragraph"/>The first argument to the <code>sqlGroupProjection</code> method is the SQL which defines the projections. The second argument represents the |
| group by clause that should be part of the query. That string may be single column name or a comma separated list of column |
| names. The third argument is a list of |
| Strings which represent column aliases corresponding to the projected values expressed in the SQL. The fourth argument |
| is a list of <code>org.hibernate.type.Type</code> instances which correspond to the projected values expressed in the SQL.<p class="paragraph"/>The query above is projecting the combined heights of boxes grouped by width and would return results that look like this:<p class="paragraph"/><div class="code"><pre>[[2, 24], [4, 9]]</pre></div><p class="paragraph"/>Each of the inner lists contains 2 values. The first value is a box width and the second value is the sum of the heights |
| of all of the boxes which have that width.<p class="paragraph"/><h4>Using SQL Restrictions</h4><p class="paragraph"/>You can access Hibernate's SQL Restrictions capabilities.<p class="paragraph"/><div class="code"><pre>def c = Person.createCriteria()<p class="paragraph"/>def peopleWithShortFirstNames = c.list { |
| sqlRestriction <span class="java-quote">"char_length(first_name) <= 4"</span> |
| }</pre></div><p class="paragraph"/>SQL Restrictions may be parameterized to deal with SQL injection vulnerabilities related to dynamic restrictions.<p class="paragraph"/> |
| <div class="code"><pre>def c = Person.createCriteria()<p class="paragraph"/>def peopleWithShortFirstNames = c.list { |
| sqlRestriction <span class="java-quote">"char_length(first_name) < ? AND char_length(first_name) > ?"</span>, [maxValue, minValue] |
| }</pre></div><p class="paragraph"/> |
| <blockquote class="note"> |
| Note that the parameter there is SQL. The <code>first_name</code> attribute referenced in the example refers to the persistence model, not the object model like in HQL queries. The <code>Person</code> property named <code>firstName</code> is mapped to the <code>first_name</code> column in the database and you must refer to that in the <code>sqlRestriction</code> string.<p class="paragraph"/>Also note that the SQL used here is not necessarily portable across databases. |
| </blockquote><p class="paragraph"/><h4>Using Scrollable Results</h4><p class="paragraph"/>You can use Hibernate's <a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/ScrollableResults.html" class="api">ScrollableResults</a> feature by calling the scroll method:<p class="paragraph"/><div class="code"><pre>def results = crit.scroll { |
| maxResults(10) |
| } |
| def f = results.first() |
| def l = results.last() |
| def n = results.next() |
| def p = results.previous()<p class="paragraph"/>def <span class="java-keyword">future</span> = results.scroll(10) |
| def accountNumber = results.getLong('number')</pre></div><p class="paragraph"/>To quote the documentation of Hibernate ScrollableResults:<p class="paragraph"/><blockquote class="quote"> |
| A result iterator that allows moving around within the results by arbitrary increments. The Query / ScrollableResults pattern is very similar to the JDBC PreparedStatement / ResultSet pattern and the semantics of methods of this interface are similar to the similarly named methods on ResultSet. |
| </blockquote><p class="paragraph"/>Contrary to JDBC, columns of results are numbered from zero.<p class="paragraph"/><h4>Setting properties in the Criteria instance</h4><p class="paragraph"/>If a node within the builder tree doesn't match a particular criterion it will attempt to set a property on the Criteria object itself. This allows full access to all the properties in this class. This example calls <code>setMaxResults</code> and <code>setFirstResult</code> on the <a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/Criteria.html" class="api">Criteria</a> instance:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.hibernate.FetchMode as FM |
| … |
| def results = c.list { |
| maxResults(10) |
| firstResult(50) |
| fetchMode(<span class="java-quote">"aRelationship"</span>, FM.JOIN) |
| }</pre></div><p class="paragraph"/><h4>Querying with Eager Fetching</h4><p class="paragraph"/>In the section on <a href="../guide/single.html#fetching" class="guide">Eager and Lazy Fetching</a> we discussed how to declaratively specify fetching to avoid the N+1 SELECT problem. However, this can also be achieved using a criteria query:<p class="paragraph"/><div class="code"><pre>def criteria = Task.createCriteria() |
| def tasks = criteria.list{ |
| eq <span class="java-quote">"assignee.id"</span>, task.assignee.id |
| join 'assignee' |
| join 'project' |
| order 'priority', 'asc' |
| }</pre></div><p class="paragraph"/>Notice the usage of the <code>join</code> method: it tells the criteria API to use a <code>JOIN</code> to fetch the named associations with the <code>Task</code> instances. It's probably best not to use this for one-to-many associations though, because you will most likely end up with duplicate results. Instead, use the 'select' fetch mode: |
| <div class="code"><pre><span class="java-keyword">import</span> org.hibernate.FetchMode as FM |
| … |
| def results = Airport.withCriteria { |
| eq <span class="java-quote">"region"</span>, <span class="java-quote">"EMEA"</span> |
| fetchMode <span class="java-quote">"flights"</span>, FM.SELECT |
| }</pre></div> |
| Although this approach triggers a second query to get the <code>flights</code> association, you will get reliable results - even with the <code>maxResults</code> option.<p class="paragraph"/><blockquote class="note"> |
| <code>fetchMode</code> and <code>join</code> are general settings of the query and can only be specified at the top-level, i.e. you cannot use them inside projections or association constraints. |
| </blockquote><p class="paragraph"/>An important point to bear in mind is that if you include associations in the query constraints, those associations will automatically be eagerly loaded. For example, in this query: |
| <div class="code"><pre>def results = Airport.withCriteria { |
| eq <span class="java-quote">"region"</span>, <span class="java-quote">"EMEA"</span> |
| flights { |
| like <span class="java-quote">"number"</span>, <span class="java-quote">"BA%"</span> |
| } |
| }</pre></div> |
| the <code>flights</code> collection would be loaded eagerly via a join even though the fetch mode has not been explicitly set.<p class="paragraph"/><h4>Method Reference</h4><p class="paragraph"/>If you invoke the builder with no method name such as:<p class="paragraph"/><div class="code"><pre>c { … }</pre></div><p class="paragraph"/>The build defaults to listing all the results and hence the above is equivalent to:<p class="paragraph"/><div class="code"><pre>c.list { … }</pre></div><p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Method</th><th>Description</th></tr><tr class="table-odd"><td><strong class="bold">list</strong></td><td>This is the default method. It returns all matching rows.</td></tr><tr class="table-even"><td><strong class="bold">get</strong></td><td>Returns a unique result set, i.e. just one row. The criteria has to be formed that way, that it only queries one row. This method is not to be confused with a limit to just the first row.</td></tr><tr class="table-odd"><td><strong class="bold">scroll</strong></td><td>Returns a scrollable result set.</td></tr><tr class="table-even"><td><strong class="bold">listDistinct</strong></td><td>If subqueries or associations are used, one may end up with the same row multiple times in the result set, this allows listing only distinct entities and is equivalent to <code>DISTINCT_ROOT_ENTITY</code> of the <a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/criterion/CriteriaSpecification.html" class="api">CriteriaSpecification</a> class.</td></tr><tr class="table-odd"><td><strong class="bold">count</strong></td><td>Returns the number of matching rows.</td></tr></table><p class="paragraph"/><h4>Combining Criteria</h4><p class="paragraph"/>You can combine multiple criteria closures in the following way:<p class="paragraph"/><div class="code"><pre>def emeaCriteria = { |
| eq <span class="java-quote">"region"</span>, <span class="java-quote">"EMEA"</span> |
| }<p class="paragraph"/>def results = Airport.withCriteria { |
| emeaCriteria.delegate = delegate |
| emeaCriteria() |
| flights { |
| like <span class="java-quote">"number"</span>, <span class="java-quote">"BA%"</span> |
| } |
| }</pre></div><p class="paragraph"/>This technique requires that each criteria must refer to the same domain class (i.e. <code>Airport</code>). |
| A more flexible approach is to use Detached Criteria, as described in the following section. |
| |
| |
| |
| <h2 id="detachedCriteria">6.4.4 Detached Criteria</h2> |
| Detached Criteria are criteria queries that are not associated with any given database session/connection. Supported since Grails 2.0, Detached Criteria queries have many uses including allowing you to create common reusable criteria queries, execute subqueries and execute batch updates/deletes.<p class="paragraph"/> |
| <h4>Building Detached Criteria Queries</h4><p class="paragraph"/>The primary point of entry for using the Detached Criteria is the <code>grails.gorm.DetachedCriteria</code> class which accepts a domain class as the only argument to its constructor:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.gorm.* |
| … |
| def criteria = <span class="java-keyword">new</span> DetachedCriteria(Person)</pre></div><p class="paragraph"/>Once you have obtained a reference to a detached criteria instance you can execute <a href="../guide/single.html#whereQueries" class="guide">where</a> queries or criteria queries to build up the appropriate query. To build a normal criteria query you can use the <code>build</code> method:<p class="paragraph"/><div class="code"><pre>def criteria = <span class="java-keyword">new</span> DetachedCriteria(Person).build { |
| eq 'lastName', 'Simpson' |
| }</pre></div><p class="paragraph"/>Note that methods on the <code>DetachedCriteria</code> instance <strong class="bold">do not</strong> mutate the original object but instead return a new query. In other words, you have to use the return value of the <code>build</code> method to obtain the mutated criteria object:<p class="paragraph"/><div class="code"><pre>def criteria = <span class="java-keyword">new</span> DetachedCriteria(Person).build { |
| eq 'lastName', 'Simpson' |
| } |
| def bartQuery = criteria.build { |
| eq 'firstName', 'Bart' |
| }</pre></div><p class="paragraph"/><h4>Executing Detached Criteria Queries</h4><p class="paragraph"/>Unlike regular criteria, Detached Criteria are lazy, in that no query is executed at the point of definition. Once a Detached Criteria query has been constructed then there are a number of useful query methods which are summarized in the table below:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Method</th><th>Description</th></tr><tr class="table-odd"><td><strong class="bold">list</strong></td><td>List all matching entities</td></tr><tr class="table-even"><td><strong class="bold">get</strong></td><td>Return a single matching result</td></tr><tr class="table-odd"><td><strong class="bold">count</strong></td><td>Count all matching records</td></tr><tr class="table-even"><td><strong class="bold">exists</strong></td><td>Return true if any matching records exist</td></tr><tr class="table-odd"><td><strong class="bold">deleteAll</strong></td><td>Delete all matching records</td></tr><tr class="table-even"><td><strong class="bold">updateAll(Map)</strong></td><td>Update all matching records with the given properties</td></tr></table><p class="paragraph"/>As an example the following code will list the first 4 matching records sorted by the <code>firstName</code> property:<p class="paragraph"/><div class="code"><pre>def criteria = <span class="java-keyword">new</span> DetachedCriteria(Person).build { |
| eq 'lastName', 'Simpson' |
| } |
| def results = criteria.list(max:4, sort:<span class="java-quote">"firstName"</span>)</pre></div><p class="paragraph"/>You can also supply additional criteria to the list method:<p class="paragraph"/><div class="code"><pre>def results = criteria.list(max:4, sort:<span class="java-quote">"firstName"</span>) { |
| gt 'age', 30 |
| }</pre></div><p class="paragraph"/>To retrieve a single result you can use the <code>get</code> or <code>find</code> methods (which are synonyms):<p class="paragraph"/><div class="code"><pre>Person p = criteria.find() // or criteria.get()</pre></div><p class="paragraph"/>The <code>DetachedCriteria</code> class itself also implements the <code>Iterable</code> interface which means that it can be treated like a list:<p class="paragraph"/><div class="code"><pre>def criteria = <span class="java-keyword">new</span> DetachedCriteria(Person).build { |
| eq 'lastName', 'Simpson' |
| } |
| criteria.each { |
| println it.firstName |
| }</pre></div><p class="paragraph"/>In this case the query is only executed when the <code>each</code> method is called. The same applies to all other Groovy collection iteration methods.<p class="paragraph"/>You can also execute dynamic finders on <code>DetachedCriteria</code> just like on domain classes. For example:<p class="paragraph"/><div class="code"><pre>def criteria = <span class="java-keyword">new</span> DetachedCriteria(Person).build { |
| eq 'lastName', 'Simpson' |
| } |
| def bart = criteria.findByFirstName(<span class="java-quote">"Bart"</span>)</pre></div><p class="paragraph"/><h4>Using Detached Criteria for Subqueries</h4><p class="paragraph"/>Within the context of a regular criteria query you can use <code>DetachedCriteria</code> to execute subquery. For example if you want to find all people who are older than the average age the following query will accomplish that:<p class="paragraph"/><div class="code"><pre>def results = Person.withCriteria { |
| gt <span class="java-quote">"age"</span>, <span class="java-keyword">new</span> DetachedCriteria(Person).build { |
| projections { |
| avg <span class="java-quote">"age"</span> |
| } |
| } |
| order <span class="java-quote">"firstName"</span> |
| }</pre></div><p class="paragraph"/>Notice that in this case the subquery class is the same as the original criteria query class (i.e. <code>Person</code>) and hence the query can be shortened to:<p class="paragraph"/><div class="code"><pre>def results = Person.withCriteria { |
| gt <span class="java-quote">"age"</span>, { |
| projections { |
| avg <span class="java-quote">"age"</span> |
| } |
| } |
| order <span class="java-quote">"firstName"</span> |
| }</pre></div><p class="paragraph"/>If the subquery class differs from the original criteria query then you will have to use the original syntax.<p class="paragraph"/>In the previous example the projection ensured that only a single result was returned (the average age). If your subquery returns multiple results then there are different criteria methods that need to be used to compare the result. For example to find all the people older than the ages 18 to 65 a <code>gtAll</code> query can be used:<p class="paragraph"/><div class="code"><pre>def results = Person.withCriteria { |
| gtAll <span class="java-quote">"age"</span>, { |
| projections { |
| property <span class="java-quote">"age"</span> |
| } |
| between 'age', 18, 65 |
| }<p class="paragraph"/> order <span class="java-quote">"firstName"</span> |
| }</pre></div><p class="paragraph"/>The following table summarizes criteria methods for operating on subqueries that return multiple results:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Method</th><th>Description</th></tr><tr class="table-odd"><td><strong class="bold">gtAll</strong></td><td>greater than all subquery results</td></tr><tr class="table-even"><td><strong class="bold">geAll</strong></td><td>greater than or equal to all subquery results</td></tr><tr class="table-odd"><td><strong class="bold">ltAll</strong></td><td>less than all subquery results</td></tr><tr class="table-even"><td><strong class="bold">leAll</strong></td><td>less than or equal to all subquery results</td></tr><tr class="table-odd"><td><strong class="bold">eqAll</strong></td><td>equal to all subquery results</td></tr><tr class="table-even"><td><strong class="bold">neAll</strong></td><td>not equal to all subquery results</td></tr></table><p class="paragraph"/><h4>Batch Operations with Detached Criteria</h4><p class="paragraph"/>The <code>DetachedCriteria</code> class can be used to execute batch operations such as batch updates and deletes. For example, the following query will update all people with the surname "Simpson" to have the surname "Bloggs":<p class="paragraph"/><div class="code"><pre>def criteria = <span class="java-keyword">new</span> DetachedCriteria(Person).build { |
| eq 'lastName', 'Simpson' |
| } |
| <span class="java-object">int</span> total = criteria.updateAll(lastName:<span class="java-quote">"Bloggs"</span>)</pre></div><p class="paragraph"/><blockquote class="note"> |
| Note that one limitation with regards to batch operations is that join queries (queries that query associations) are not allowed within the <code>DetachedCriteria</code> instance. |
| </blockquote><p class="paragraph"/>To batch delete records you can use the <code>deleteAll</code> method:<p class="paragraph"/><div class="code"><pre>def criteria = <span class="java-keyword">new</span> DetachedCriteria(Person).build { |
| eq 'lastName', 'Simpson' |
| } |
| <span class="java-object">int</span> total = criteria.deleteAll()</pre></div> |
| |
| |
| <a name="5.4.3 Hibernate Query Language (HQL)"><!-- Legacy link --></a> |
| <h2 id="hql">6.4.5 Hibernate Query Language (HQL)</h2> |
| GORM classes also support Hibernate's query language HQL, a very complete reference for which can be found <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/queryhql.html" target="blank">in the Hibernate documentation</a> of the Hibernate documentation.<p class="paragraph"/>GORM provides a number of methods that work with HQL including <a href="../ref/Domain Classes/find.html" class="domainClasses">find</a>, <a href="../ref/Domain Classes/findAll.html" class="domainClasses">findAll</a> and <a href="../ref/Domain Classes/executeQuery.html" class="domainClasses">executeQuery</a>. An example of a query can be seen below:<p class="paragraph"/><div class="code"><pre>def results = |
| Book.findAll(<span class="java-quote">"from Book as b where b.title like 'Lord of the%'"</span>)</pre></div><p class="paragraph"/><h4>Positional and Named Parameters</h4><p class="paragraph"/>In this case the value passed to the query is hard coded, however you can equally use positional parameters:<p class="paragraph"/><div class="code"><pre>def results = |
| Book.findAll(<span class="java-quote">"from Book as b where b.title like ?"</span>, [<span class="java-quote">"The Shi%"</span>])</pre></div><p class="paragraph"/><div class="code"><pre>def author = Author.findByName(<span class="java-quote">"Stephen King"</span>) |
| def books = Book.findAll(<span class="java-quote">"from Book as book where book.author = ?"</span>, |
| [author])</pre></div><p class="paragraph"/>Or even named parameters:<p class="paragraph"/><div class="code"><pre>def results = |
| Book.findAll(<span class="java-quote">"from Book as b "</span> + |
| <span class="java-quote">"where b.title like :search or b.author like :search"</span>, |
| [search: <span class="java-quote">"The Shi%"</span>])</pre></div><p class="paragraph"/><div class="code"><pre>def author = Author.findByName(<span class="java-quote">"Stephen King"</span>) |
| def books = Book.findAll(<span class="java-quote">"from Book as book where book.author = :author"</span>, |
| [author: author])</pre></div><p class="paragraph"/><h4>Multiline Queries</h4><p class="paragraph"/>Use the line continuation character to separate the query across multiple lines:<p class="paragraph"/><div class="code"><pre>def results = Book.findAll(<span class="java-quote">"\ |
| from Book as b, \ |
| Author as a \ |
| where b.author = a and a.surname = ?"</span>, ['Smith'])</pre></div><p class="paragraph"/><blockquote class="note"> |
| Triple-quoted Groovy multiline Strings will NOT work with HQL queries. |
| </blockquote><p class="paragraph"/><h4>Pagination and Sorting</h4><p class="paragraph"/>You can also perform pagination and sorting whilst using HQL queries. To do so simply specify the pagination options as a Map at the end of the method call and include an "ORDER BY" clause in the HQL:<p class="paragraph"/><div class="code"><pre>def results = |
| Book.findAll(<span class="java-quote">"from Book as b where "</span> + |
| <span class="java-quote">"b.title like 'Lord of the%' "</span> + |
| <span class="java-quote">"order by b.title asc"</span>, |
| [max: 10, offset: 20])</pre></div> |
| |
| |
| <a name="5.5 Advanced GORM Features"><!-- Legacy link --></a> |
| <h2 id="advancedGORMFeatures">6.5 Advanced GORM Features</h2> |
| The following sections cover more advanced usages of GORM including caching, custom mapping and events. |
| |
| <a name="5.5.1 Events and Auto Timestamping"><!-- Legacy link --></a> |
| <h2 id="eventsAutoTimestamping">6.5.1 Events and Auto Timestamping</h2> |
| GORM supports the registration of events as methods that get fired when certain events occurs such as deletes, inserts and updates. The following is a list of supported events: |
| <ul class="star"> |
| <li><code>beforeInsert</code> - Executed before an object is initially persisted to the database. If you return false, the insert will be cancelled.</li> |
| <li><code>beforeUpdate</code> - Executed before an object is updated. If you return false, the update will be cancelled.</li> |
| <li><code>beforeDelete</code> - Executed before an object is deleted. If you return false, the delete will be cancelled.</li> |
| <li><code>beforeValidate</code> - Executed before an object is validated</li> |
| <li><code>afterInsert</code> - Executed after an object is persisted to the database</li> |
| <li><code>afterUpdate</code> - Executed after an object has been updated</li> |
| <li><code>afterDelete</code> - Executed after an object has been deleted</li> |
| <li><code>onLoad</code> - Executed when an object is loaded from the database</li> |
| </ul><p class="paragraph"/>To add an event simply register the relevant method with your domain class.<p class="paragraph"/><blockquote class="warning"> |
| Do not attempt to flush the session within an event (such as with obj.save(flush:true)). Since events are fired during flushing this will cause a StackOverflowError. |
| </blockquote><p class="paragraph"/><h3>Event types</h3><p class="paragraph"/><h4>The beforeInsert event</h4><p class="paragraph"/>Fired before an object is saved to the database<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-keyword">private</span> <span class="java-keyword">static</span> <span class="java-keyword">final</span> Date NULL_DATE = <span class="java-keyword">new</span> Date(0)<p class="paragraph"/> <span class="java-object">String</span> firstName |
| <span class="java-object">String</span> lastName |
| Date signupDate = NULL_DATE<p class="paragraph"/> def beforeInsert() { |
| <span class="java-keyword">if</span> (signupDate == NULL_DATE) { |
| signupDate = <span class="java-keyword">new</span> Date() |
| } |
| } |
| }</pre></div><p class="paragraph"/><h4>The beforeUpdate event</h4><p class="paragraph"/>Fired before an existing object is updated<p class="paragraph"/><div class="code"><pre>class Person {<p class="paragraph"/> def securityService<p class="paragraph"/> <span class="java-object">String</span> firstName |
| <span class="java-object">String</span> lastName |
| <span class="java-object">String</span> lastUpdatedBy<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| lastUpdatedBy nullable: <span class="java-keyword">true</span> |
| }<p class="paragraph"/> def beforeUpdate() { |
| lastUpdatedBy = securityService.currentAuthenticatedUsername() |
| } |
| }</pre></div><p class="paragraph"/><h4>The beforeDelete event</h4><p class="paragraph"/>Fired before an object is deleted.<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> name<p class="paragraph"/> def beforeDelete() { |
| ActivityTrace.withNewSession { |
| <span class="java-keyword">new</span> ActivityTrace(eventName: <span class="java-quote">"Person Deleted"</span>, data: name).save() |
| } |
| } |
| }</pre></div><p class="paragraph"/>Notice the usage of <code>withNewSession</code> method above. Since events are triggered whilst Hibernate is flushing using persistence methods like <code>save()</code> and <code>delete()</code> won't result in objects being saved unless you run your operations with a new <code>Session</code>.<p class="paragraph"/>Fortunately the <code>withNewSession</code> method lets you share the same transactional JDBC connection even though you're using a different underlying <code>Session</code>.<p class="paragraph"/><h4>The beforeValidate event</h4><p class="paragraph"/>Fired before an object is validated.<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> name<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| name size: 5..45 |
| }<p class="paragraph"/> def beforeValidate() { |
| name = name?.trim() |
| } |
| }</pre></div><p class="paragraph"/>The <code>beforeValidate</code> method is run before any validators are run.<p class="paragraph"/><blockquote class="note"> |
| Validation may run more often than you think. It is triggered by the <code>validate()</code> and <code>save()</code> methods as you'd expect, but it is also typically triggered just before the view is rendered as well. So when writing <code>beforeValidate()</code> implementations, make sure that they can handle being called multiple times with the same property values. |
| </blockquote><p class="paragraph"/>GORM supports an overloaded version of <code>beforeValidate</code> which accepts a <code>List</code> parameter which may include |
| the names of the properties which are about to be validated. This version of <code>beforeValidate</code> will be called |
| when the <code>validate</code> method has been invoked and passed a <code>List</code> of property names as an argument.<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> name |
| <span class="java-object">String</span> town |
| <span class="java-object">Integer</span> age<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| name size: 5..45 |
| age range: 4..99 |
| }<p class="paragraph"/> def beforeValidate(List propertiesBeingValidated) { |
| // <span class="java-keyword">do</span> pre validation work based on propertiesBeingValidated |
| } |
| }<p class="paragraph"/>def p = <span class="java-keyword">new</span> Person(name: 'Jacob Brown', age: 10) |
| p.validate(['age', 'name'])</pre></div><p class="paragraph"/><blockquote class="note"> |
| Note that when <code>validate</code> is triggered indirectly because of a call to the <code>save</code> method that |
| the <code>validate</code> method is being invoked with no arguments, not a <code>List</code> that includes all of |
| the property names. |
| </blockquote><p class="paragraph"/>Either or both versions of <code>beforeValidate</code> may be defined in a domain class. GORM will |
| prefer the <code>List</code> version if a <code>List</code> is passed to <code>validate</code> but will fall back on the |
| no-arg version if the <code>List</code> version does not exist. Likewise, GORM will prefer the |
| no-arg version if no arguments are passed to <code>validate</code> but will fall back on the |
| <code>List</code> version if the no-arg version does not exist. In that case, <code>null</code> is passed to <code>beforeValidate</code>.<p class="paragraph"/><h4>The onLoad/beforeLoad event</h4><p class="paragraph"/>Fired immediately before an object is loaded from the database:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> name |
| Date dateCreated |
| Date lastUpdated<p class="paragraph"/> def onLoad() { |
| log.debug <span class="java-quote">"Loading ${id}"</span> |
| } |
| }</pre></div><p class="paragraph"/><code>beforeLoad()</code> is effectively a synonym for <code>onLoad()</code>, so only declare one or the other.<p class="paragraph"/><h4>The afterLoad event</h4><p class="paragraph"/>Fired immediately after an object is loaded from the database:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> name |
| Date dateCreated |
| Date lastUpdated<p class="paragraph"/> def afterLoad() { |
| name = <span class="java-quote">"I'm loaded"</span> |
| } |
| }</pre></div><p class="paragraph"/><h4>Custom Event Listeners</h4><p class="paragraph"/>As of Grails 2.0 there is a new API for plugins and applications to register and listen for persistence events. This API is not tied to Hibernate and also works for other persistence plugins such as the <a href="http://grails.org/plugin/mongodb" target="blank">MongoDB plugin for GORM</a>.<p class="paragraph"/>To use this API you need to subclass <code>AbstractPersistenceEventListener</code> (in package <em class="italic">org.grails.datastore.mapping.engine.event</em> ) and implement the methods <code>onPersistenceEvent</code> and <code>supportsEventType</code>. You also must provide a reference to the datastore to the listener. The simplest possible implementation can be seen below:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">public</span> MyPersistenceListener(<span class="java-keyword">final</span> Datastore datastore) { |
| <span class="java-keyword">super</span>(datastore) |
| }<p class="paragraph"/>@Override |
| <span class="java-keyword">protected</span> void onPersistenceEvent(<span class="java-keyword">final</span> AbstractPersistenceEvent event) { |
| <span class="java-keyword">switch</span>(event.eventType) { |
| <span class="java-keyword">case</span> PreInsert: |
| println <span class="java-quote">"PRE INSERT ${event.entityObject}"</span> |
| <span class="java-keyword">break</span> |
| <span class="java-keyword">case</span> PostInsert: |
| println <span class="java-quote">"POST INSERT ${event.entityObject}"</span> |
| <span class="java-keyword">break</span> |
| <span class="java-keyword">case</span> PreUpdate: |
| println <span class="java-quote">"PRE UPDATE ${event.entityObject}"</span> |
| <span class="java-keyword">break</span>; |
| <span class="java-keyword">case</span> PostUpdate: |
| println <span class="java-quote">"POST UPDATE ${event.entityObject}"</span> |
| <span class="java-keyword">break</span>; |
| <span class="java-keyword">case</span> PreDelete: |
| println <span class="java-quote">"PRE DELETE ${event.entityObject}"</span> |
| <span class="java-keyword">break</span>; |
| <span class="java-keyword">case</span> PostDelete: |
| println <span class="java-quote">"POST DELETE ${event.entityObject}"</span> |
| <span class="java-keyword">break</span>; |
| <span class="java-keyword">case</span> PreLoad: |
| println <span class="java-quote">"PRE LOAD ${event.entityObject}"</span> |
| <span class="java-keyword">break</span>; |
| <span class="java-keyword">case</span> PostLoad: |
| println <span class="java-quote">"POST LOAD ${event.entityObject}"</span> |
| <span class="java-keyword">break</span>; |
| } |
| }<p class="paragraph"/>@Override |
| <span class="java-keyword">public</span> <span class="java-object">boolean</span> supportsEventType(<span class="java-object">Class</span><? <span class="java-keyword">extends</span> ApplicationEvent> eventType) { |
| <span class="java-keyword">return</span> <span class="java-keyword">true</span> |
| }</pre></div><p class="paragraph"/>The <code>AbstractPersistenceEvent</code> class has many subclasses (<code>PreInsertEvent</code>, <code>PostInsertEvent</code> etc.) that provide further information specific to the event. A <code>cancel()</code> method is also provided on the event which allows you to veto an insert, update or delete operation.<p class="paragraph"/>Once you have created your event listener you need to register it with the <code>ApplicationContext</code>. This can be done in <code>BootStrap.groovy</code>:<p class="paragraph"/><div class="code"><pre>def init = { |
| application.mainContext.eventTriggeringInterceptor.datastores.each { k, datastore -> |
| applicationContext.addApplicationListener <span class="java-keyword">new</span> MyPersistenceListener(datastore) |
| } |
| }</pre></div><p class="paragraph"/>or use this in a plugin:<p class="paragraph"/><div class="code"><pre>def doWithApplicationContext = { applicationContext -> |
| application.mainContext.eventTriggeringInterceptor.datastores.each { k, datastore -> |
| applicationContext.addApplicationListener <span class="java-keyword">new</span> MyPersistenceListener(datastore) |
| } |
| }</pre></div><p class="paragraph"/><h4>Hibernate Events</h4><p class="paragraph"/>It is generally encouraged to use the non-Hibernate specific API described above, but if you need access to more detailed Hibernate events then you can define custom Hibernate-specific event listeners.<p class="paragraph"/>You can also register event handler classes in an application's <code>grails-app/conf/spring/resources.groovy</code> or in the <code>doWithSpring</code> closure in a plugin descriptor by registering a Spring bean named <code>hibernateEventListeners</code>. This bean has one property, <code>listenerMap</code> which specifies the listeners to register for various Hibernate events.<p class="paragraph"/>The values of the Map are instances of classes that implement one or more Hibernate listener interfaces. You can use one class that implements all of the required interfaces, or one concrete class per interface, or any combination. The valid Map keys and corresponding interfaces are listed here:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th><strong class="bold">Name</strong></th><th><strong class="bold">Interface</strong></th></tr><tr class="table-odd"><td>auto-flush</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/AutoFlushEventListener.html" class="api">AutoFlushEventListener</a></td></tr><tr class="table-even"><td>merge</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/MergeEventListener.html" class="api">MergeEventListener</a></td></tr><tr class="table-odd"><td>create</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PersistEventListener.html" class="api">PersistEventListener</a></td></tr><tr class="table-even"><td>create-onflush</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PersistEventListener.html" class="api">PersistEventListener</a></td></tr><tr class="table-odd"><td>delete</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/DeleteEventListener.html" class="api">DeleteEventListener</a></td></tr><tr class="table-even"><td>dirty-check</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/DirtyCheckEventListener.html" class="api">DirtyCheckEventListener</a></td></tr><tr class="table-odd"><td>evict</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/EvictEventListener.html" class="api">EvictEventListener</a></td></tr><tr class="table-even"><td>flush</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/FlushEventListener.html" class="api">FlushEventListener</a></td></tr><tr class="table-odd"><td>flush-entity</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/FlushEntityEventListener.html" class="api">FlushEntityEventListener</a></td></tr><tr class="table-even"><td>load</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/LoadEventListener.html" class="api">LoadEventListener</a></td></tr><tr class="table-odd"><td>load-collection</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/InitializeCollectionEventListener.html" class="api">InitializeCollectionEventListener</a></td></tr><tr class="table-even"><td>lock</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/LockEventListener.html" class="api">LockEventListener</a></td></tr><tr class="table-odd"><td>refresh</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/RefreshEventListener.html" class="api">RefreshEventListener</a></td></tr><tr class="table-even"><td>replicate</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/ReplicateEventListener.html" class="api">ReplicateEventListener</a></td></tr><tr class="table-odd"><td>save-update</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/SaveOrUpdateEventListener.html" class="api">SaveOrUpdateEventListener</a></td></tr><tr class="table-even"><td>save</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/SaveOrUpdateEventListener.html" class="api">SaveOrUpdateEventListener</a></td></tr><tr class="table-odd"><td>update</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/SaveOrUpdateEventListener.html" class="api">SaveOrUpdateEventListener</a></td></tr><tr class="table-even"><td>pre-load</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PreLoadEventListener.html" class="api">PreLoadEventListener</a></td></tr><tr class="table-odd"><td>pre-update</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PreUpdateEventListener.html" class="api">PreUpdateEventListener</a></td></tr><tr class="table-even"><td>pre-delete</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PreDeleteEventListener.html" class="api">PreDeleteEventListener</a></td></tr><tr class="table-odd"><td>pre-insert</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PreInsertEventListener.html" class="api">PreInsertEventListener</a></td></tr><tr class="table-even"><td>pre-collection-recreate</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PreCollectionRecreateEventListener.html" class="api">PreCollectionRecreateEventListener</a></td></tr><tr class="table-odd"><td>pre-collection-remove</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PreCollectionRemoveEventListener.html" class="api">PreCollectionRemoveEventListener</a></td></tr><tr class="table-even"><td>pre-collection-update</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PreCollectionUpdateEventListener.html" class="api">PreCollectionUpdateEventListener</a></td></tr><tr class="table-odd"><td>post-load</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PostLoadEventListener.html" class="api">PostLoadEventListener</a></td></tr><tr class="table-even"><td>post-update</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PostUpdateEventListener.html" class="api">PostUpdateEventListener</a></td></tr><tr class="table-odd"><td>post-delete</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PostDeleteEventListener.html" class="api">PostDeleteEventListener</a></td></tr><tr class="table-even"><td>post-insert</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PostInsertEventListener.html" class="api">PostInsertEventListener</a></td></tr><tr class="table-odd"><td>post-commit-update</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PostUpdateEventListener.html" class="api">PostUpdateEventListener</a></td></tr><tr class="table-even"><td>post-commit-delete</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PostDeleteEventListener.html" class="api">PostDeleteEventListener</a></td></tr><tr class="table-odd"><td>post-commit-insert</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PostInsertEventListener.html" class="api">PostInsertEventListener</a></td></tr><tr class="table-even"><td>post-collection-recreate</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PostCollectionRecreateEventListener.html" class="api">PostCollectionRecreateEventListener</a></td></tr><tr class="table-odd"><td>post-collection-remove</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PostCollectionRemoveEventListener.html" class="api">PostCollectionRemoveEventListener</a></td></tr><tr class="table-even"><td>post-collection-update</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PostCollectionUpdateEventListener.html" class="api">PostCollectionUpdateEventListener</a></td></tr></table><p class="paragraph"/>For example, you could register a class <code>AuditEventListener</code> which implements <code>PostInsertEventListener</code>, <code>PostUpdateEventListener</code>, and <code>PostDeleteEventListener</code> using the following in an application:<p class="paragraph"/><div class="code"><pre>beans = {<p class="paragraph"/> auditListener(AuditEventListener)<p class="paragraph"/> hibernateEventListeners(HibernateEventListeners) { |
| listenerMap = ['post-insert': auditListener, |
| 'post-update': auditListener, |
| 'post-delete': auditListener] |
| } |
| }</pre></div><p class="paragraph"/>or use this in a plugin:<p class="paragraph"/><div class="code"><pre>def doWithSpring = {<p class="paragraph"/> auditListener(AuditEventListener)<p class="paragraph"/> hibernateEventListeners(HibernateEventListeners) { |
| listenerMap = ['post-insert': auditListener, |
| 'post-update': auditListener, |
| 'post-delete': auditListener] |
| } |
| }</pre></div><p class="paragraph"/><h4>Automatic timestamping</h4><p class="paragraph"/>If you define a <code>dateCreated</code> property it will be set to the current date for you when you create new instances. Likewise, if you define a <code>lastUpdated</code> property it will be automatically be updated for you when you change persistent instances.<p class="paragraph"/>If this is not the behaviour you want you can disable this feature with:<p class="paragraph"/><div class="code"><pre>class Person { |
| Date dateCreated |
| Date lastUpdated |
| <span class="java-keyword">static</span> mapping = { |
| autoTimestamp <span class="java-keyword">false</span> |
| } |
| }</pre></div><p class="paragraph"/><blockquote class="warning"> |
| If you have <code>nullable: false</code> constraints on either <code>dateCreated</code> or <code>lastUpdated</code>, your domain instances will fail validation - probably not what you want. Omit constraints from these properties unless you disable automatic timestamping. |
| </blockquote> |
| |
| |
| <a name="5.5.2 Custom ORM Mapping"><!-- Legacy link --></a> |
| <h2 id="ormdsl">6.5.2 Custom ORM Mapping</h2> |
| Grails domain classes can be mapped onto many legacy schemas with an Object Relational Mapping DSL (domain specific language). The following sections takes you through what is possible with the ORM DSL.<p class="paragraph"/><blockquote class="note"> |
| None of this is necessary if you are happy to stick to the conventions defined by GORM for table names, column names and so on. You only needs this functionality if you need to tailor the way GORM maps onto legacy schemas or configures caching |
| </blockquote><p class="paragraph"/>Custom mappings are defined using a static <code>mapping</code> block defined within your domain class:<p class="paragraph"/><div class="code"><pre>class Person { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| version <span class="java-keyword">false</span> |
| autoTimestamp <span class="java-keyword">false</span> |
| } |
| }</pre></div><p class="paragraph"/>You can also configure global mappings in Config.groovy (or an external config file) using this setting:<p class="paragraph"/><div class="code"><pre>grails.gorm.<span class="java-keyword">default</span>.mapping = { |
| version <span class="java-keyword">false</span> |
| autoTimestamp <span class="java-keyword">false</span> |
| }</pre></div><p class="paragraph"/>It has the same syntax as the standard <code>mapping</code> block but it applies to all your domain classes! You can then override these defaults within the <code>mapping</code> block of a domain class. |
| |
| <a name="5.5.2.1 Table and Column Names"><!-- Legacy link --></a> |
| <h2 id="tableAndColumnNames">6.5.2.1 Table and Column Names</h2> |
| <h4>Table names</h4><p class="paragraph"/>The database table name which the class maps to can be customized using the <code>table</code> method:<p class="paragraph"/><div class="code"><pre>class Person { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| } |
| }</pre></div><p class="paragraph"/>In this case the class would be mapped to a table called <code>people</code> instead of the default name of <code>person</code>.<p class="paragraph"/><h4>Column names</h4><p class="paragraph"/>It is also possible to customize the mapping for individual columns onto the database. For example to change the name you can do:<p class="paragraph"/><div class="code"><pre>class Person {<p class="paragraph"/> <span class="java-object">String</span> firstName<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| firstName column: 'First_Name' |
| } |
| }</pre></div><p class="paragraph"/>Here <code>firstName</code> is a dynamic method within the <code>mapping</code> Closure that has a single Map parameter. Since its name corresponds to a domain class persistent field, the parameter values (in this case just <code>"column"</code>) are used to configure the mapping for that property.<p class="paragraph"/><h4>Column type</h4><p class="paragraph"/>GORM supports configuration of Hibernate types with the DSL using the type attribute. This includes specifying user types that implement the Hibernate <a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/usertype/UserType.html" class="api">org.hibernate.usertype.UserType</a> interface, which allows complete customization of how a type is persisted. As an example if you had a <code>PostCodeType</code> you could use it as follows:<p class="paragraph"/><div class="code"><pre>class Address {<p class="paragraph"/> <span class="java-object">String</span> number |
| <span class="java-object">String</span> postCode<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| postCode type: PostCodeType |
| } |
| }</pre></div><p class="paragraph"/>Alternatively if you just wanted to map it to one of Hibernate's basic types other than the default chosen by Grails you could use:<p class="paragraph"/><div class="code"><pre>class Address {<p class="paragraph"/> <span class="java-object">String</span> number |
| <span class="java-object">String</span> postCode<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| postCode type: 'text' |
| } |
| }</pre></div><p class="paragraph"/>This would make the <code>postCode</code> column map to the default large-text type for the database you're using (for example TEXT or CLOB).<p class="paragraph"/>See the Hibernate documentation regarding <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#mapping-types-basictypes" target="blank">Basic Types</a> for further information.<p class="paragraph"/><h4>Many-to-One/One-to-One Mappings</h4><p class="paragraph"/>In the case of associations it is also possible to configure the foreign keys used to map associations. In the case of a many-to-one or one-to-one association this is exactly the same as any regular column. For example consider the following:<p class="paragraph"/><div class="code"><pre>class Person {<p class="paragraph"/> <span class="java-object">String</span> firstName |
| Address address<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| firstName column: 'First_Name' |
| address column: 'Person_Address_Id' |
| } |
| }</pre></div><p class="paragraph"/>By default the <code>address</code> association would map to a foreign key column called <code>address_id</code>. By using the above mapping we have changed the name of the foreign key column to <code>Person_Adress_Id</code>.<p class="paragraph"/><h4>One-to-Many Mapping</h4><p class="paragraph"/>With a bidirectional one-to-many you can change the foreign key column used by changing the column name on the many side of the association as per the example in the previous section on one-to-one associations. However, with unidirectional associations the foreign key needs to be specified on the association itself. For example given a unidirectional one-to-many relationship between <code>Person</code> and <code>Address</code> the following code will change the foreign key in the <code>address</code> table:<p class="paragraph"/><div class="code"><pre>class Person {<p class="paragraph"/> <span class="java-object">String</span> firstName<p class="paragraph"/> <span class="java-keyword">static</span> hasMany = [addresses: Address]<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| firstName column: 'First_Name' |
| addresses column: 'Person_Address_Id' |
| } |
| }</pre></div><p class="paragraph"/>If you don't want the column to be in the <code>address</code> table, but instead some intermediate join table you can use the <code>joinTable</code> parameter:<p class="paragraph"/><div class="code"><pre>class Person {<p class="paragraph"/> <span class="java-object">String</span> firstName<p class="paragraph"/> <span class="java-keyword">static</span> hasMany = [addresses: Address]<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| firstName column: 'First_Name' |
| addresses joinTable: [name: 'Person_Addresses', |
| key: 'Person_Id', |
| column: 'Address_Id'] |
| } |
| }</pre></div><p class="paragraph"/><h4>Many-to-Many Mapping</h4><p class="paragraph"/>Grails, by default maps a many-to-many association using a join table. For example consider this many-to-many association:<p class="paragraph"/><div class="code"><pre>class Group { |
| … |
| <span class="java-keyword">static</span> hasMany = [people: Person] |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Person { |
| … |
| <span class="java-keyword">static</span> belongsTo = Group |
| <span class="java-keyword">static</span> hasMany = [groups: Group] |
| }</pre></div><p class="paragraph"/>In this case Grails will create a join table called <code>group_person</code> containing foreign keys called <code>person_id</code> and <code>group_id</code> referencing the <code>person</code> and <code>group</code> tables. To change the column names you can specify a column within the mappings for each class.<p class="paragraph"/><div class="code"><pre>class Group { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| people column: 'Group_Person_Id' |
| } |
| } |
| class Person { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| groups column: 'Group_Group_Id' |
| } |
| }</pre></div><p class="paragraph"/>You can also specify the name of the join table to use:<p class="paragraph"/><div class="code"><pre>class Group { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| people column: 'Group_Person_Id', |
| joinTable: 'PERSON_GROUP_ASSOCIATIONS' |
| } |
| } |
| class Person { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| groups column: 'Group_Group_Id', |
| joinTable: 'PERSON_GROUP_ASSOCIATIONS' |
| } |
| }</pre></div> |
| |
| |
| <a name="5.5.2.2 Caching Strategy"><!-- Legacy link --></a> |
| <h2 id="caching">6.5.2.2 Caching Strategy</h2> |
| <h4>Setting up caching</h4><p class="paragraph"/><a href="http://www.hibernate.org/" target="blank">Hibernate</a> features a second-level cache with a customizable cache provider. This needs to be configured in the <code>grails-app/conf/DataSource.groovy</code> file as follows:<p class="paragraph"/><div class="code"><pre>hibernate { |
| cache.use_second_level_cache=<span class="java-keyword">true</span> |
| cache.use_query_cache=<span class="java-keyword">true</span> |
| cache.provider_class='org.hibernate.cache.EhCacheProvider' |
| }</pre></div><p class="paragraph"/>You can customize any of these settings, for example to use a distributed caching mechanism.<p class="paragraph"/><blockquote class="note"> |
| For further reading on caching and in particular Hibernate's second-level cache, refer to the <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/performance.html#performance-cache" target="blank">Hibernate documentation</a> on the subject. |
| </blockquote><p class="paragraph"/><h4>Caching instances</h4><p class="paragraph"/>Call the <code>cache</code> method in your mapping block to enable caching with the default settings:<p class="paragraph"/><div class="code"><pre>class Person { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| cache <span class="java-keyword">true</span> |
| } |
| }</pre></div><p class="paragraph"/>This will configure a 'read-write' cache that includes both lazy and non-lazy properties. You can customize this further:<p class="paragraph"/><div class="code"><pre>class Person { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| cache usage: 'read-only', include: 'non-lazy' |
| } |
| }</pre></div><p class="paragraph"/><h4>Caching associations</h4><p class="paragraph"/>As well as the ability to use Hibernate's second level cache to cache instances you can also cache collections (associations) of objects. For example:<p class="paragraph"/><div class="code"><pre>class Person {<p class="paragraph"/> <span class="java-object">String</span> firstName<p class="paragraph"/> <span class="java-keyword">static</span> hasMany = [addresses: Address]<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| version <span class="java-keyword">false</span> |
| addresses column: 'Address', cache: <span class="java-keyword">true</span> |
| } |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Address { |
| <span class="java-object">String</span> number |
| <span class="java-object">String</span> postCode |
| }</pre></div><p class="paragraph"/>This will enable a 'read-write' caching mechanism on the <code>addresses</code> collection. You can also use:<p class="paragraph"/><div class="code"><pre>cache: 'read-write' // or 'read-only' or 'transactional'</pre></div><p class="paragraph"/>to further configure the cache usage.<p class="paragraph"/><h4>Caching Queries</h4><p class="paragraph"/>You can cache queries such as dynamic finders and criteria. To do so using a dynamic finder you can pass the <code>cache</code> argument:<p class="paragraph"/><div class="code"><pre>def person = Person.findByFirstName(<span class="java-quote">"Fred"</span>, [cache: <span class="java-keyword">true</span>])</pre></div><p class="paragraph"/><blockquote class="note"> |
| In order for the results of the query to be cached, you must enable caching in your mapping as discussed in the previous section. |
| </blockquote><p class="paragraph"/>You can also cache criteria queries:<p class="paragraph"/><div class="code"><pre>def people = Person.withCriteria { |
| like('firstName', 'Fr%') |
| cache <span class="java-keyword">true</span> |
| }</pre></div><p class="paragraph"/><h4>Cache usages</h4><p class="paragraph"/>Below is a description of the different cache settings and their usages: |
| <ul class="star"> |
| <li><code>read-only</code> - If your application needs to read but never modify instances of a persistent class, a read-only cache may be used.</li> |
| <li><code>read-write</code> - If the application needs to update data, a read-write cache might be appropriate.</li> |
| <li><code>nonstrict-read-write</code> - If the application only occasionally needs to update data (i.e. if it is very unlikely that two transactions would try to update the same item simultaneously) and strict transaction isolation is not required, a <code>nonstrict-read-write</code> cache might be appropriate.</li> |
| <li><code>transactional</code> - The <code>transactional</code> cache strategy provides support for fully transactional cache providers such as JBoss TreeCache. Such a cache may only be used in a JTA environment and you must specify <code>hibernate.transaction.manager_lookup_class</code> in the <code>grails-app/conf/DataSource.groovy</code> file's <code>hibernate</code> config.</li> |
| </ul><p class="paragraph"/> |
| |
| <a name="5.5.2.3 Inheritance Strategies"><!-- Legacy link --></a> |
| <h2 id="inheritanceStrategies">6.5.2.3 Inheritance Strategies</h2> |
| By default GORM classes use <code>table-per-hierarchy</code> inheritance mapping. This has the disadvantage that columns cannot have a <code>NOT-NULL</code> constraint applied to them at the database level. If you would prefer to use a <code>table-per-subclass</code> inheritance strategy you can do so as follows:<p class="paragraph"/><div class="code"><pre>class Payment { |
| <span class="java-object">Integer</span> amount<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| tablePerHierarchy <span class="java-keyword">false</span> |
| } |
| }<p class="paragraph"/>class CreditCardPayment <span class="java-keyword">extends</span> Payment { |
| <span class="java-object">String</span> cardNumber |
| }</pre></div><p class="paragraph"/>The mapping of the root <code>Payment</code> class specifies that it will not be using <code>table-per-hierarchy</code> mapping for all child classes. |
| |
| <a name="5.5.2.4 Custom Database Identity"><!-- Legacy link --></a> |
| <h2 id="identity">6.5.2.4 Custom Database Identity</h2> |
| You can customize how GORM generates identifiers for the database using the DSL. By default GORM relies on the native database mechanism for generating ids. This is by far the best approach, but there are still many schemas that have different approaches to identity.<p class="paragraph"/>To deal with this Hibernate defines the concept of an id generator. You can customize the id generator and the column it maps to as follows:<p class="paragraph"/><div class="code"><pre>class Person { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| version <span class="java-keyword">false</span> |
| id generator: 'hilo', |
| params: [table: 'hi_value', |
| column: 'next_value', |
| max_lo: 100] |
| } |
| }</pre></div><p class="paragraph"/>In this case we're using one of Hibernate's built in 'hilo' generators that uses a separate table to generate ids.<p class="paragraph"/><blockquote class="note"> |
| For more information on the different Hibernate generators refer to the <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#mapping-declaration-id-generator" target="blank">Hibernate reference documentation</a> |
| </blockquote><p class="paragraph"/>Although you don't typically specify the <code>id</code> field (Grails adds it for you) you can still configure its mapping like the other properties. For example to customise the column for the id property you can do:<p class="paragraph"/><div class="code"><pre>class Person { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| version <span class="java-keyword">false</span> |
| id column: 'person_id' |
| } |
| }</pre></div> |
| |
| |
| <a name="5.5.2.5 Composite Primary Keys"><!-- Legacy link --></a> |
| <h2 id="compositePrimaryKeys">6.5.2.5 Composite Primary Keys</h2> |
| GORM supports the concept of composite identifiers (identifiers composed from 2 or more properties). It is not an approach we recommend, but is available to you if you need it:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.apache.commons.lang.builder.HashCodeBuilder<p class="paragraph"/>class Person <span class="java-keyword">implements</span> Serializable {<p class="paragraph"/> <span class="java-object">String</span> firstName |
| <span class="java-object">String</span> lastName<p class="paragraph"/> <span class="java-object">boolean</span> equals(other) { |
| <span class="java-keyword">if</span> (!(other <span class="java-keyword">instanceof</span> Person)) { |
| <span class="java-keyword">return</span> <span class="java-keyword">false</span> |
| }<p class="paragraph"/> other.firstName == firstName && other.lastName == lastName |
| }<p class="paragraph"/> <span class="java-object">int</span> hashCode() { |
| def builder = <span class="java-keyword">new</span> HashCodeBuilder() |
| builder.append firstName |
| builder.append lastName |
| builder.toHashCode() |
| }<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| id composite: ['firstName', 'lastName'] |
| } |
| }</pre></div><p class="paragraph"/>The above will create a composite id of the <code>firstName</code> and <code>lastName</code> properties of the Person class. To retrieve an instance by id you use a prototype of the object itself:<p class="paragraph"/><div class="code"><pre>def p = Person.get(<span class="java-keyword">new</span> Person(firstName: <span class="java-quote">"Fred"</span>, lastName: <span class="java-quote">"Flintstone"</span>)) |
| println p.firstName</pre></div><p class="paragraph"/>Domain classes mapped with composite primary keys must implement the <code>Serializable</code> interface and override the <code>equals</code> and <code>hashCode</code> methods, using the properties in the composite key for the calculations. The example above uses a <code>HashCodeBuilder</code> for convenience but it's fine to implement it yourself.<p class="paragraph"/>Another important consideration when using composite primary keys is associations. If for example you have a many-to-one association where the foreign keys are stored in the associated table then 2 columns will be present in the associated table.<p class="paragraph"/>For example consider the following domain class:<p class="paragraph"/><div class="code"><pre>class Address { |
| Person person |
| }</pre></div><p class="paragraph"/>In this case the <code>address</code> table will have an additional two columns called <code>person_first_name</code> and <code>person_last_name</code>. If you wish the change the mapping of these columns then you can do so using the following technique:<p class="paragraph"/><div class="code"><pre>class Address { |
| Person person |
| <span class="java-keyword">static</span> mapping = { |
| columns { |
| person { |
| column name: <span class="java-quote">"FirstName"</span> |
| column name: <span class="java-quote">"LastName"</span> |
| } |
| } |
| } |
| }</pre></div> |
| |
| |
| <a name="5.5.2.6 Database Indices"><!-- Legacy link --></a> |
| <h2 id="databaseIndices">6.5.2.6 Database Indices</h2> |
| To get the best performance out of your queries it is often necessary to tailor the table index definitions. How you tailor them is domain specific and a matter of monitoring usage patterns of your queries. With GORM's DSL you can specify which columns are used in which indexes:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> firstName |
| <span class="java-object">String</span> address |
| <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| version <span class="java-keyword">false</span> |
| id column: 'person_id' |
| firstName column: 'First_Name', index: 'Name_Idx' |
| address column: 'Address', index: 'Name_Idx,Address_Index' |
| } |
| }</pre></div><p class="paragraph"/>Note that you cannot have any spaces in the value of the <code>index</code> attribute; in this example <code>index:'Name_Idx, Address_Index'</code> will cause an error. |
| |
| |
| <a name="5.5.2.7 Optimistic Locking and Versioning"><!-- Legacy link --></a> |
| <h2 id="optimisticLockingAndVersioning">6.5.2.7 Optimistic Locking and Versioning</h2> |
| As discussed in the section on <a href="../guide/single.html#locking" class="guide">Optimistic and Pessimistic Locking</a>, by default GORM uses optimistic locking and automatically injects a <code>version</code> property into every class which is in turn mapped to a <code>version</code> column at the database level.<p class="paragraph"/>If you're mapping to a legacy schema that doesn't have version columns (or there's some other reason why you don't want/need this feature) you can disable this with the <code>version</code> method:<p class="paragraph"/><div class="code"><pre>class Person { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| version <span class="java-keyword">false</span> |
| } |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| If you disable optimistic locking you are essentially on your own with regards to concurrent updates and are open to the risk of users losing data (due to data overriding) unless you use <a href="../guide/single.html#locking" class="guide">pessimistic locking</a> |
| </blockquote><p class="paragraph"/><h4>Version columns types</h4><p class="paragraph"/>By default Grails maps the <code>version</code> property as a <code>Long</code> that gets incremented by one each time an instance is updated. But Hibernate also supports using a <code>Timestamp</code>, for example:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> java.sql.Timestamp<p class="paragraph"/>class Person {<p class="paragraph"/> … |
| Timestamp version<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| } |
| }</pre></div><p class="paragraph"/>There's a slight risk that two updates occurring at nearly the same time on a fast server can end up with the same timestamp value but this risk is very low. One benefit of using a <code>Timestamp</code> instead of a <code>Long</code> is that you combine the optimistic locking and last-updated semantics into a single column. |
| |
| |
| <a name="5.5.2.8 Eager and Lazy Fetching"><!-- Legacy link --></a> |
| <h2 id="fetchingDSL">6.5.2.8 Eager and Lazy Fetching</h2> |
| <h4>Lazy Collections</h4><p class="paragraph"/>As discussed in the section on <a href="../guide/single.html#fetching" class="guide">Eager and Lazy fetching</a>, GORM collections are lazily loaded by default but you can change this behaviour with the ORM DSL. There are several options available to you, but the most common ones are: |
| <ul class="star"> |
| <li>lazy: false</li> |
| <li>fetch: 'join'</li> |
| </ul><p class="paragraph"/>and they're used like this:<p class="paragraph"/><div class="code"><pre>class Person {<p class="paragraph"/> <span class="java-object">String</span> firstName |
| Pet pet<p class="paragraph"/> <span class="java-keyword">static</span> hasMany = [addresses: Address]<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| addresses lazy: <span class="java-keyword">false</span> |
| pet fetch: 'join' |
| } |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Address { |
| <span class="java-object">String</span> street |
| <span class="java-object">String</span> postCode |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Pet { |
| <span class="java-object">String</span> name |
| }</pre></div><p class="paragraph"/>The first option, <code>lazy: false</code> , ensures that when a <code>Person</code> instance is loaded, its <code>addresses</code> collection is loaded at the same time with a second SELECT. The second option is basically the same, except the collection is loaded with a JOIN rather than another SELECT. Typically you want to reduce the number of queries, so <code>fetch: 'join'</code> is the more appropriate option. On the other hand, it could feasibly be the more expensive approach if your domain model and data result in more and larger results than would otherwise be necessary.<p class="paragraph"/>For more advanced users, the other settings available are: |
| <ol> |
| <li>batchSize: N</li> |
| <li>lazy: false, batchSize: N</li> |
| </ol><p class="paragraph"/>where N is an integer. These let you fetch results in batches, with one query per batch. As a simple example, consider this mapping for <code>Person</code>:<p class="paragraph"/><div class="code"><pre>class Person {<p class="paragraph"/> <span class="java-object">String</span> firstName |
| Pet pet<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| pet batchSize: 5 |
| } |
| }</pre></div> |
| If a query returns multiple <code>Person</code> instances, then when we access the first <code>pet</code> property, Hibernate will fetch that <code>Pet</code> plus the four next ones. You can get the same behaviour with eager loading by combining <code>batchSize</code> with the <code>lazy: false</code> option. You can find out more about these options in the <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/performance.html#performance-fetching" target="blank">Hibernate user guide</a> and this <a href="http://community.jboss.org/wiki/AShortPrimerOnFetchingStrategies" target="blank">primer on fetching strategies</a>. Note that ORM DSL does not currently support the "subselect" fetching strategy.<p class="paragraph"/><h4>Lazy Single-Ended Associations</h4><p class="paragraph"/>In GORM, one-to-one and many-to-one associations are by default lazy. Non-lazy single ended associations can be problematic when you load many entities because each non-lazy association will result in an extra SELECT statement. If the associated entities also have non-lazy associations, the number of queries grows significantly!<p class="paragraph"/>Use the same technique as for lazy collections to make a one-to-one or many-to-one association non-lazy/eager:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> firstName |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Address {<p class="paragraph"/> <span class="java-object">String</span> street |
| <span class="java-object">String</span> postCode<p class="paragraph"/> <span class="java-keyword">static</span> belongsTo = [person: Person]<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| person lazy: <span class="java-keyword">false</span> |
| } |
| }</pre></div><p class="paragraph"/>Here we configure GORM to load the associated <code>Person</code> instance (through the <code>person</code> property) whenever an <code>Address</code> is loaded.<p class="paragraph"/><h4>Lazy Single-Ended Associations and Proxies</h4><p class="paragraph"/>Hibernate uses runtime-generated proxies to facilitate single-ended lazy associations; Hibernate dynamically subclasses the entity class to create the proxy.<p class="paragraph"/>Consider the previous example but with a lazily-loaded <code>person</code> association: Hibernate will set the <code>person</code> property to a proxy that is a subclass of <code>Person</code>. When you call any of the getters (except for the <code>id</code> property) or setters on that proxy, Hibernate will load the entity from the database.<p class="paragraph"/>Unfortunately this technique can produce surprising results. Consider the following example classes:<p class="paragraph"/><div class="code"><pre>class Pet { |
| <span class="java-object">String</span> name |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Dog <span class="java-keyword">extends</span> Pet { |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> name |
| Pet pet |
| }</pre></div><p class="paragraph"/>and assume that we have a single <code>Person</code> instance with a <code>Dog</code> as the <code>pet</code>. The following code will work as you would expect: |
| <div class="code"><pre>def person = Person.get(1) |
| assert person.pet <span class="java-keyword">instanceof</span> Dog |
| assert Pet.get(person.petId) <span class="java-keyword">instanceof</span> Dog</pre></div><p class="paragraph"/>But this won't:<p class="paragraph"/><div class="code"><pre>def person = Person.get(1) |
| assert person.pet <span class="java-keyword">instanceof</span> Dog |
| assert Pet.list()[0] <span class="java-keyword">instanceof</span> Dog</pre></div><p class="paragraph"/>The second assertion fails, and to add to the confusion, this will work:<p class="paragraph"/><div class="code"><pre>assert Pet.list()[0] <span class="java-keyword">instanceof</span> Dog</pre></div><p class="paragraph"/>What's going on here? It's down to a combination of how proxies work and the guarantees that the Hibernate session makes. When you load the <code>Person</code> instance, Hibernate creates a proxy for its <code>pet</code> relation and attaches it to the session. Once that happens, whenever you retrieve that <code>Pet</code> instance with a query, a <code>get()</code>, or the <code>pet</code> relation <em class="italic">within the same session</em> , Hibernate gives you the proxy.<p class="paragraph"/>Fortunately for us, GORM automatically unwraps the proxy when you use <code>get()</code> and <code>findBy*()</code>, or when you directly access the relation. That means you don't have to worry at all about proxies in the majority of cases. But GORM doesn't do that for objects returned with a query that returns a list, such as <code>list()</code> and <code>findAllBy*()</code>. However, if Hibernate hasn't attached the proxy to the session, those queries will return the real instances - hence why the last example works.<p class="paragraph"/>You can protect yourself to a degree from this problem by using the <code>instanceOf</code> method by GORM:<p class="paragraph"/><div class="code"><pre>def person = Person.get(1) |
| assert Pet.list()[0].instanceOf(Dog)</pre></div><p class="paragraph"/>However, it won't help here if casting is involved. For example, the following code will throw a <code>ClassCastException</code> because the first pet in the list is a proxy instance with a class that is neither <code>Dog</code> nor a sub-class of <code>Dog</code>:<p class="paragraph"/><div class="code"><pre>def person = Person.get(1) |
| Dog pet = Pet.list()[0]</pre></div><p class="paragraph"/>Of course, it's best not to use static types in this situation. If you use an untyped variable for the pet instead, you can access any <code>Dog</code> properties or methods on the instance without any problems.<p class="paragraph"/>These days it's rare that you will come across this issue, but it's best to be aware of it just in case. At least you will know why such an error occurs and be able to work around it. |
| |
| |
| <a name="5.5.2.9 Custom Cascade Behaviour"><!-- Legacy link --></a> |
| <h2 id="customCascadeBehaviour">6.5.2.9 Custom Cascade Behaviour</h2> |
| As described in the section on <a href="../guide/single.html#cascades" class="guide">cascading updates</a>, the primary mechanism to control the way updates and deletes cascade from one association to another is the static <a href="../ref/Domain Classes/belongsTo.html" class="domainClasses">belongsTo</a> property.<p class="paragraph"/>However, the ORM DSL gives you complete access to Hibernate's <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/objectstate.html#objectstate-transitive" target="blank">transitive persistence</a> capabilities using the <code>cascade</code> attribute.<p class="paragraph"/>Valid settings for the cascade attribute include: |
| <ul class="star"> |
| <li><code>merge</code> - merges the state of a detached association</li> |
| <li><code>save-update</code> - cascades only saves and updates to an association</li> |
| <li><code>delete</code> - cascades only deletes to an association</li> |
| <li><code>lock</code> - useful if a pessimistic lock should be cascaded to its associations</li> |
| <li><code>refresh</code> - cascades refreshes to an association</li> |
| <li><code>evict</code> - cascades evictions (equivalent to <code>discard()</code> in GORM) to associations if set</li> |
| <li><code>all</code> - cascade <em class="italic">all</em> operations to associations</li> |
| <li><code>all-delete-orphan</code> - Applies only to one-to-many associations and indicates that when a child is removed from an association then it should be automatically deleted. Children are also deleted when the parent is.</li> |
| </ul><p class="paragraph"/><blockquote class="note"> |
| It is advisable to read the section in the Hibernate documentation on <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/objectstate.html#objectstate-transitive" target="blank">transitive persistence</a> to obtain a better understanding of the different cascade styles and recommendations for their usage |
| </blockquote><p class="paragraph"/>To specify the cascade attribute simply define one or more (comma-separated) of the aforementioned settings as its value:<p class="paragraph"/><div class="code"><pre>class Person {<p class="paragraph"/> <span class="java-object">String</span> firstName<p class="paragraph"/> <span class="java-keyword">static</span> hasMany = [addresses: Address]<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| addresses cascade: <span class="java-quote">"all-delete-orphan"</span> |
| } |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class Address { |
| <span class="java-object">String</span> street |
| <span class="java-object">String</span> postCode |
| }</pre></div> |
| |
| |
| <a name="5.5.2.10 Custom Hibernate Types"><!-- Legacy link --></a> |
| <h2 id="customHibernateTypes">6.5.2.10 Custom Hibernate Types</h2> |
| You saw in an earlier section that you can use composition (with the <code>embedded</code> property) to break a table into multiple objects. You can achieve a similar effect with Hibernate's custom user types. These are not domain classes themselves, but plain Java or Groovy classes. Each of these types also has a corresponding "meta-type" class that implements <a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/usertype/UserType.html" class="api">org.hibernate.usertype.UserType</a>.<p class="paragraph"/>The <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#mapping-types-custom" target="blank">Hibernate reference manual</a> has some information on custom types, but here we will focus on how to map them in Grails. Let's start by taking a look at a simple domain class that uses an old-fashioned (pre-Java 1.5) type-safe enum class:<p class="paragraph"/><div class="code"><pre>class Book {<p class="paragraph"/> <span class="java-object">String</span> title |
| <span class="java-object">String</span> author |
| Rating rating<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| rating type: RatingUserType |
| } |
| }</pre></div><p class="paragraph"/>All we have done is declare the <code>rating</code> field the enum type and set the property's type in the custom mapping to the corresponding <code>UserType</code> implementation. That's all you have to do to start using your custom type. If you want, you can also use the other column settings such as "column" to change the column name and "index" to add it to an index.<p class="paragraph"/>Custom types aren't limited to just a single column - they can be mapped to as many columns as you want. In such cases you explicitly define in the mapping what columns to use, since Hibernate can only use the property name for a single column. Fortunately, Grails lets you map multiple columns to a property using this syntax:<p class="paragraph"/><div class="code"><pre>class Book {<p class="paragraph"/> <span class="java-object">String</span> title |
| Name author |
| Rating rating<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| author type: NameUserType, { |
| column name: <span class="java-quote">"first_name"</span> |
| column name: <span class="java-quote">"last_name"</span> |
| } |
| rating type: RatingUserType |
| } |
| }</pre></div><p class="paragraph"/>The above example will create "first_name" and "last_name" columns for the <code>author</code> property. You'll be pleased to know that you can also use some of the normal column/property mapping attributes in the column definitions. For example:<p class="paragraph"/><div class="code"><pre>column name: <span class="java-quote">"first_name"</span>, index: <span class="java-quote">"my_idx"</span>, unique: <span class="java-keyword">true</span></pre></div><p class="paragraph"/>The column definitions do <em class="italic">not</em> support the following attributes: <code>type</code>, <code>cascade</code>, <code>lazy</code>, <code>cache</code>, and <code>joinTable</code>.<p class="paragraph"/>One thing to bear in mind with custom types is that they define the <em class="italic">SQL types</em> for the corresponding database columns. That helps take the burden of configuring them yourself, but what happens if you have a legacy database that uses a different SQL type for one of the columns? In that case, override the column's SQL type using the <code>sqlType</code> attribute:<p class="paragraph"/><div class="code"><pre>class Book {<p class="paragraph"/> <span class="java-object">String</span> title |
| Name author |
| Rating rating<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| author type: NameUserType, { |
| column name: <span class="java-quote">"first_name"</span>, sqlType: <span class="java-quote">"text"</span> |
| column name: <span class="java-quote">"last_name"</span>, sqlType: <span class="java-quote">"text"</span> |
| } |
| rating type: RatingUserType, sqlType: <span class="java-quote">"text"</span> |
| } |
| }</pre></div><p class="paragraph"/>Mind you, the SQL type you specify needs to still work with the custom type. So overriding a default of "varchar" with "text" is fine, but overriding "text" with "yes_no" isn't going to work. |
| |
| |
| <a name="5.5.2.11 Derived Properties"><!-- Legacy link --></a> |
| <h2 id="derivedProperties">6.5.2.11 Derived Properties</h2> |
| A derived property is one that takes its value from a SQL expression, often but not necessarily based on the value of one or more other persistent properties. Consider a Product class like this:<p class="paragraph"/><div class="code"><pre>class Product { |
| <span class="java-object">Float</span> price |
| <span class="java-object">Float</span> taxRate |
| <span class="java-object">Float</span> tax |
| }</pre></div><p class="paragraph"/>If the <code>tax</code> property is derived based on the value of <code>price</code> and <code>taxRate</code> properties then is probably no need to persist the <code>tax</code> property. The SQL used to derive the value of a derived property may be expressed in the ORM DSL like this:<p class="paragraph"/><div class="code"><pre>class Product { |
| <span class="java-object">Float</span> price |
| <span class="java-object">Float</span> taxRate |
| <span class="java-object">Float</span> tax<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| tax formula: 'PRICE * TAX_RATE' |
| } |
| }</pre></div><p class="paragraph"/>Note that the formula expressed in the ORM DSL is SQL so references to other properties should relate to the persistence model not the object model, which is why the example refers to <code>PRICE</code> and <code>TAX_RATE</code> instead of <code>price</code> and <code>taxRate</code>.<p class="paragraph"/>With that in place, when a Product is retrieved with something like <code>Product.get(42)</code>, the SQL that is generated to support that will look something like this:<p class="paragraph"/><div class="code"><pre>select |
| product0_.id as id1_0_, |
| product0_.version as version1_0_, |
| product0_.price as price1_0_, |
| product0_.tax_rate as tax4_1_0_, |
| product0_.PRICE * product0_.TAX_RATE as formula1_0_ |
| from |
| product product0_ |
| where |
| product0_.id=?</pre></div><p class="paragraph"/>Since the <code>tax</code> property is derived at runtime and not stored in the database it might seem that the same effect could be achieved by adding a method like <code>getTax()</code> to the <code>Product</code> class that simply returns the product of the <code>taxRate</code> and <code>price</code> properties. With an approach like that you would give up the ability query the database based on the value of the <code>tax</code> property. Using a derived property allows exactly that. To retrieve all <code>Product</code> objects that have a <code>tax</code> value greater than 21.12 you could execute a query like this:<p class="paragraph"/><div class="code"><pre>Product.findAllByTaxGreaterThan(21.12)</pre></div><p class="paragraph"/>Derived properties may be referenced in the Criteria API:<p class="paragraph"/><div class="code"><pre>Product.withCriteria { |
| gt 'tax', 21.12f |
| }</pre></div><p class="paragraph"/>The SQL that is generated to support either of those would look something like this:<p class="paragraph"/><div class="code"><pre>select |
| this_.id as id1_0_, |
| this_.version as version1_0_, |
| this_.price as price1_0_, |
| this_.tax_rate as tax4_1_0_, |
| this_.PRICE * this_.TAX_RATE as formula1_0_ |
| from |
| product this_ |
| where |
| this_.PRICE * this_.TAX_RATE>?</pre></div><p class="paragraph"/><blockquote class="note"> |
| Because the value of a derived property is generated in the database and depends on the execution of SQL code, derived properties may not have GORM constraints applied to them. If constraints are specified for a derived property, they will be ignored. |
| </blockquote> |
| |
| |
| <a name="5.5.2.12 Custom Naming Strategy"><!-- Legacy link --></a> |
| <h2 id="customNamingStrategy">6.5.2.12 Custom Naming Strategy</h2> |
| By default Grails uses Hibernate's <code>ImprovedNamingStrategy</code> to convert domain class Class and field names to SQL table and column names by converting from camel-cased Strings to ones that use underscores as word separators. You can customize these on a per-class basis in the <code>mapping</code> closure but if there's a consistent pattern you can specify a different <code>NamingStrategy</code> class to use.<p class="paragraph"/>Configure the class name to be used in <code>grails-app/conf/DataSource.groovy</code> in the <code>hibernate</code> section, e.g.<p class="paragraph"/><div class="code"><pre>dataSource { |
| pooled = <span class="java-keyword">true</span> |
| dbCreate = <span class="java-quote">"create-drop"</span> |
| … |
| }<p class="paragraph"/>hibernate { |
| cache.use_second_level_cache = <span class="java-keyword">true</span> |
| … |
| naming_strategy = com.myco.myproj.CustomNamingStrategy |
| }</pre></div><p class="paragraph"/>You can also specify the name of the class and it will be loaded for you:<p class="paragraph"/><div class="code"><pre>hibernate { |
| … |
| naming_strategy = 'com.myco.myproj.CustomNamingStrategy' |
| }</pre></div><p class="paragraph"/>A third option is to provide an instance if there is some configuration required beyond calling the default constructor:<p class="paragraph"/><div class="code"><pre>hibernate { |
| … |
| def strategy = <span class="java-keyword">new</span> com.myco.myproj.CustomNamingStrategy() |
| // configure as needed |
| naming_strategy = strategy |
| }</pre></div><p class="paragraph"/>You can use an existing class or write your own, for example one that prefixes table names and column names:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> com.myco.myproj<p class="paragraph"/><span class="java-keyword">import</span> org.hibernate.cfg.ImprovedNamingStrategy |
| <span class="java-keyword">import</span> org.hibernate.util.StringHelper<p class="paragraph"/>class CustomNamingStrategy <span class="java-keyword">extends</span> ImprovedNamingStrategy {<p class="paragraph"/> <span class="java-object">String</span> classToTableName(<span class="java-object">String</span> className) { |
| <span class="java-quote">"table_"</span> + StringHelper.unqualify(className) |
| }<p class="paragraph"/> <span class="java-object">String</span> propertyToColumnName(<span class="java-object">String</span> propertyName) { |
| <span class="java-quote">"col_"</span> + StringHelper.unqualify(propertyName) |
| } |
| }</pre></div><p class="paragraph"/> |
| |
| <a name="5.5.3 Default Sort Order"><!-- Legacy link --></a> |
| <h2 id="defaultSortOrder">6.5.3 Default Sort Order</h2> |
| You can sort objects using query arguments such as those found in the <a href="../ref/Domain Classes/list.html" class="domainClasses">list</a> method:<p class="paragraph"/><div class="code"><pre>def airports = Airport.list(sort:'name')</pre></div><p class="paragraph"/>However, you can also declare the default sort order for a collection in the mapping:<p class="paragraph"/><div class="code"><pre>class Airport { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| sort <span class="java-quote">"name"</span> |
| } |
| }</pre></div><p class="paragraph"/>The above means that all collections of <code>Airport</code> instances will by default be sorted by the airport name. If you also want to change the sort <em class="italic">order</em> , use this syntax:<p class="paragraph"/><div class="code"><pre>class Airport { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| sort name: <span class="java-quote">"desc"</span> |
| } |
| }</pre></div><p class="paragraph"/>Finally, you can configure sorting at the association level:<p class="paragraph"/><div class="code"><pre>class Airport { |
| … |
| <span class="java-keyword">static</span> hasMany = [flights: Flight]<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| flights sort: 'number', order: 'desc' |
| } |
| }</pre></div><p class="paragraph"/>In this case, the <code>flights</code> collection will always be sorted in descending order of flight number.<p class="paragraph"/><blockquote class="warning"> |
| These mappings will not work for default unidirectional one-to-many or many-to-many relationships because they involve a join table. See <a href="http://jira.codehaus.org/browse/GRAILS-4089" target="blank">this issue</a> for more details. Consider using a <code>SortedSet</code> or queries with sort parameters to fetch the data you need. |
| </blockquote> |
| |
| |
| <a name="5.6 Programmatic Transactions"><!-- Legacy link --></a> |
| <h2 id="programmaticTransactions">6.6 Programmatic Transactions</h2> |
| Grails is built on Spring and uses Spring's Transaction abstraction for dealing with programmatic transactions. However, GORM classes have been enhanced to make this simpler with the <a href="../ref/Domain Classes/withTransaction.html" class="domainClasses">withTransaction</a> method. This method has a single parameter, a Closure, which has a single parameter which is a Spring <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/transaction/TransactionStatus.html" class="api">TransactionStatus</a> instance.<p class="paragraph"/>Here's an example of using <code>withTransaction</code> in a controller methods:<p class="paragraph"/><div class="code"><pre>def transferFunds() { |
| Account.withTransaction { status -> |
| def source = Account.get(params.from) |
| def dest = Account.get(params.to)<p class="paragraph"/> def amount = params.amount.toInteger() |
| <span class="java-keyword">if</span> (source.active) { |
| <span class="java-keyword">if</span> (dest.active) { |
| source.balance -= amount |
| dest.amount += amount |
| } |
| <span class="java-keyword">else</span> { |
| status.setRollbackOnly() |
| } |
| } |
| } |
| }</pre></div><p class="paragraph"/>In this example we rollback the transaction if the destination account is not active. Also, if an unchecked <code>Exception</code> or <code>Error</code> (but not a checked <code>Exception</code>, even though Groovy doesn't require that you catch checked exceptions) is thrown during the process the transaction will automatically be rolled back.<p class="paragraph"/>You can also use "save points" to rollback a transaction to a particular point in time if you don't want to rollback the entire transaction. This can be achieved through the use of Spring's <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/transaction/SavepointManager.html" class="api">SavePointManager</a> interface.<p class="paragraph"/>The <code>withTransaction</code> method deals with the begin/commit/rollback logic for you within the scope of the block. |
| |
| |
| <a name="5.7 GORM and Constraints"><!-- Legacy link --></a> |
| <h2 id="gormConstraints">6.7 GORM and Constraints</h2> |
| Although constraints are covered in the <a href="../guide/single.html#constraints" class="guide">Validation</a> section, it is important to mention them here as some of the constraints can affect the way in which the database schema is generated.<p class="paragraph"/>Where feasible, Grails uses a domain class's constraints to influence the database columns generated for the corresponding domain class properties.<p class="paragraph"/>Consider the following example. Suppose we have a domain model with the following properties:<p class="paragraph"/><div class="code"><pre><span class="java-object">String</span> name |
| <span class="java-object">String</span> description</pre></div><p class="paragraph"/>By default, in MySQL, Grails would define these columns as<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Column</th><th>Data Type</th></tr><tr class="table-odd"><td>name</td><td>varchar(255)</td></tr><tr class="table-even"><td>description</td><td>varchar(255)</td></tr></table><p class="paragraph"/>But perhaps the business rules for this domain class state that a description can be up to 1000 characters in length. If that were the case, we would likely define the column as follows <em class="italic">if</em> we were creating the table with an SQL script.<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Column</th><th>Data Type</th></tr><tr class="table-odd"><td>description</td><td>TEXT</td></tr></table><p class="paragraph"/>Chances are we would also want to have some application-based validation to make sure we don't exceed that 1000 character limit <em class="italic">before</em> we persist any records. In Grails, we achieve this validation with <a href="../guide/single.html#constraints" class="guide">constraints</a>. We would add the following constraint declaration to the domain class.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> constraints = { |
| description maxSize: 1000 |
| }</pre></div><p class="paragraph"/>This constraint would provide both the application-based validation we want and it would also cause the schema to be generated as shown above. Below is a description of the other constraints that influence schema generation.<p class="paragraph"/><h4>Constraints Affecting String Properties</h4> |
| <ul class="star"> |
| <li><a href="../ref/Constraints/inList.html" class="constraints">inList</a></li> |
| <li><a href="../ref/Constraints/maxSize.html" class="constraints">maxSize</a></li> |
| <li><a href="../ref/Constraints/size.html" class="constraints">size</a></li> |
| </ul><p class="paragraph"/>If either the <code>maxSize</code> or the <code>size</code> constraint is defined, Grails sets the maximum column length based on the constraint value.<p class="paragraph"/>In general, it's not advisable to use both constraints on the same domain class property. However, if both the <code>maxSize</code> constraint and the <code>size</code> constraint are defined, then Grails sets the column length to the minimum of the <code>maxSize</code> constraint and the upper bound of the size constraint. (Grails uses the minimum of the two, because any length that exceeds that minimum will result in a validation error.)<p class="paragraph"/>If the <code>inList</code> constraint is defined (and the <code>maxSize</code> and the <code>size</code> constraints are not defined), then Grails sets the maximum column length based on the length of the longest string in the list of valid values. For example, given a list including values "Java", "Groovy", and "C++", Grails would set the column length to 6 (i.e., the number of characters in the string "Groovy").<p class="paragraph"/><h4>Constraints Affecting Numeric Properties</h4> |
| <ul class="star"> |
| <li><a href="../ref/Constraints/min.html" class="constraints">min</a></li> |
| <li><a href="../ref/Constraints/max.html" class="constraints">max</a></li> |
| <li><a href="../ref/Constraints/range.html" class="constraints">range</a></li> |
| </ul><p class="paragraph"/>If the <code>max</code>, <code>min</code>, or <code>range</code> constraint is defined, Grails attempts to set the column precision based on the constraint value. (The success of this attempted influence is largely dependent on how Hibernate interacts with the underlying DBMS.)<p class="paragraph"/>In general, it's not advisable to combine the pair <code>min</code>/<code>max</code> and <code>range</code> constraints together on the same domain class property. However, if both of these constraints is defined, then Grails uses the minimum precision value from the constraints. (Grails uses the minimum of the two, because any length that exceeds that minimum precision will result in a validation error.) |
| <ul class="star"> |
| <li><a href="../ref/Constraints/scale.html" class="constraints">scale</a></li> |
| </ul><p class="paragraph"/>If the scale constraint is defined, then Grails attempts to set the column <a href="../ref/Constraints/scale.html" class="constraints">scale</a> based on the constraint value. This rule only applies to floating point numbers (i.e., <code>java.lang.Float</code>, <code>java.Lang.Double</code>, <code>java.lang.BigDecimal</code>, or subclasses of <code>java.lang.BigDecimal</code>). The success of this attempted influence is largely dependent on how Hibernate interacts with the underlying DBMS.<p class="paragraph"/>The constraints define the minimum/maximum numeric values, and Grails derives the maximum number of digits for use in the precision. Keep in mind that specifying only one of <code>min</code>/<code>max</code> constraints will not affect schema generation (since there could be large negative value of property with max:100, for example), unless the specified constraint value requires more digits than default Hibernate column precision is (19 at the moment). For example:<p class="paragraph"/><div class="code"><pre>someFloatValue max: 1000000, scale: 3</pre></div><p class="paragraph"/>would yield:<p class="paragraph"/><div class="code"><pre>someFloatValue DECIMAL(19, 3) // precision is <span class="java-keyword">default</span></pre></div><p class="paragraph"/>but<p class="paragraph"/><div class="code"><pre>someFloatValue max: 12345678901234567890, scale: 5</pre></div><p class="paragraph"/>would yield: |
| <div class="code"><pre>someFloatValue DECIMAL(25, 5) // precision = digits in max + scale</pre></div><p class="paragraph"/>and<p class="paragraph"/><div class="code"><pre>someFloatValue max: 100, min: -100000</pre></div><p class="paragraph"/>would yield:<p class="paragraph"/><div class="code"><pre>someFloatValue DECIMAL(8, 2) // precision = digits in min + <span class="java-keyword">default</span> scale</pre></div> |
| |
| |
| <a name="7. The Web Layer"><!-- Legacy link --></a> |
| <h1 id="theWebLayer">7 The Web Layer</h1> |
| |
| |
| <a name="7.1 Controllers"><!-- Legacy link --></a> |
| <h2 id="controllers">7.1 Controllers</h2> |
| A controller handles requests and creates or prepares the response. A controller can generate the response directly or delegate to a view. To create a controller, simply create a class whose name ends with <code>Controller</code> in the <code>grails-app/controllers</code> directory (in a subdirectory if it's in a package).<p class="paragraph"/>The default <a href="../guide/single.html#urlmappings" class="guide">URL Mapping</a> configuration ensures that the first part of your controller name is mapped to a URI and each action defined within your controller maps to URIs within the controller name URI. |
| |
| |
| <a name="7.1.1 Understanding Controllers and Actions"><!-- Legacy link --></a> |
| <h2 id="understandingControllersAndActions">7.1.1 Understanding Controllers and Actions</h2> |
| <h4>Creating a controller</h4><p class="paragraph"/>Controllers can be created with the <a href="../ref/Command Line/create-controller.html" class="commandLine">create-controller</a> or <a href="../ref/Command Line/generate-controller.html" class="commandLine">generate-controller</a> command. For example try running the following command from the root of a Grails project:<p class="paragraph"/><div class="code"><pre>grails create-controller book</pre></div><p class="paragraph"/>The command will create a controller at the location <code>grails-app/controllers/myapp/BookController.groovy</code>:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> myapp<p class="paragraph"/>class BookController {<p class="paragraph"/> def index() { } |
| }</pre></div><p class="paragraph"/>where "myapp" will be the name of your application, the default package name if one isn't specified.<p class="paragraph"/><code>BookController</code> by default maps to the /book URI (relative to your application root).<p class="paragraph"/><blockquote class="note"> |
| The <code>create-controller</code> and <code>generate-controller</code> commands are just for convenience and you can just as easily create controllers using your favorite text editor or IDE |
| </blockquote><p class="paragraph"/><h4>Creating Actions</h4><p class="paragraph"/>A controller can have multiple public action methods; each one maps to a URI:<p class="paragraph"/><div class="code"><pre>class BookController {<p class="paragraph"/> def list() {<p class="paragraph"/> // <span class="java-keyword">do</span> controller logic |
| // create model<p class="paragraph"/> <span class="java-keyword">return</span> model |
| } |
| }</pre></div><p class="paragraph"/>This example maps to the <code>/book/list</code> URI by default thanks to the property being named <code>list</code>.<p class="paragraph"/><h4>Public Methods as Actions</h4><p class="paragraph"/>In earlier versions of Grails actions were implemented with Closures. This is still supported, but the preferred approach is to use methods.<p class="paragraph"/>Leveraging methods instead of Closure properties has some advantages: |
| <ul class="star"> |
| <li>Memory efficient</li> |
| <li>Allow use of stateless controllers (<code>singleton</code> scope)</li> |
| <li>You can override actions from subclasses and call the overridden superclass method with <code>super.actionName()</code></li> |
| <li>Methods can be intercepted with standard proxying mechanisms, something that is complicated to do with Closures since they're fields.</li> |
| </ul><p class="paragraph"/>If you prefer the Closure syntax or have older controller classes created in earlier versions of Grails and still want the advantages of using methods, you can set the <code>grails.compile.artefacts.closures.convert</code> property to true in <code>BuildConfig.groovy</code>: |
| <div class="code"><pre>grails.compile.artefacts.closures.convert = <span class="java-keyword">true</span></pre></div><p class="paragraph"/>and a compile-time AST transformation will convert your Closures to methods in the generated bytecode.<p class="paragraph"/><blockquote class="note"> |
| If a controller class extends some other class which is not defined under the <code>grails-app/controllers/</code> directory, methods inherited from that class are not converted to controller actions. If the intent is to expose those inherited methods as controller actions the methods may be overridden in the subclass and the subclass method may invoke the method in the super class. |
| </blockquote><p class="paragraph"/><h4>The Default Action</h4><p class="paragraph"/>A controller has the concept of a default URI that maps to the root URI of the controller, for example <code>/book</code> for <code>BookController</code>. The action that is called when the default URI is requested is dictated by the following rules: |
| <ul class="star"> |
| <li>If there is only one action, it's the default</li> |
| <li>If you have an action named <code>index</code>, it's the default</li> |
| <li>Alternatively you can set it explicitly with the <code>defaultAction</code> property:</li> |
| </ul><p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> defaultAction = <span class="java-quote">"list"</span></pre></div> |
| |
| |
| <a name="7.1.2 Controllers and Scopes"><!-- Legacy link --></a> |
| <h2 id="controllersAndScopes">7.1.2 Controllers and Scopes</h2> |
| <h4>Available Scopes</h4><p class="paragraph"/>Scopes are hash-like objects where you can store variables. The following scopes are available to controllers: |
| <ul class="star"> |
| <li><a href="../ref/Controllers/servletContext.html" class="controllers">servletContext</a> - Also known as application scope, this scope lets you share state across the entire web application. The servletContext is an instance of <a href="http://download.oracle.com/javaee/1.4/api/javax/servlet/ServletContext.html" class="api">ServletContext</a></li> |
| <li><a href="../ref/Controllers/session.html" class="controllers">session</a> - The session allows associating state with a given user and typically uses cookies to associate a session with a client. The session object is an instance of <a href="http://download.oracle.com/javaee/1.4/api/javax/servlet/http/HttpSession.html" class="api">HttpSession</a></li> |
| <li><a href="../ref/Controllers/request.html" class="controllers">request</a> - The request object allows the storage of objects for the current request only. The request object is an instance of <a href="http://download.oracle.com/javaee/1.4/api/javax/servlet/http/HttpServletRequest.html" class="api">HttpServletRequest</a></li> |
| <li><a href="../ref/Controllers/params.html" class="controllers">params</a> - Mutable map of incoming request query string or POST parameters</li> |
| <li><a href="../ref/Controllers/flash.html" class="controllers">flash</a> - See below</li> |
| </ul><p class="paragraph"/><h4>Accessing Scopes</h4><p class="paragraph"/>Scopes can be accessed using the variable names above in combination with Groovy's array index operator, even on classes provided by the Servlet API such as the <a href="http://download.oracle.com/javaee/1.4/api/javax/servlet/http/HttpServletRequest.html" class="api">HttpServletRequest</a>:<p class="paragraph"/><div class="code"><pre>class BookController { |
| def find() { |
| def findBy = params[<span class="java-quote">"findBy"</span>] |
| def appContext = request[<span class="java-quote">"foo"</span>] |
| def loggedUser = session[<span class="java-quote">"logged_user"</span>] |
| } |
| }</pre></div><p class="paragraph"/>You can also access values within scopes using the de-reference operator, making the syntax even more clear:<p class="paragraph"/><div class="code"><pre>class BookController { |
| def find() { |
| def findBy = params.findBy |
| def appContext = request.foo |
| def loggedUser = session.logged_user |
| } |
| }</pre></div><p class="paragraph"/>This is one of the ways that Grails unifies access to the different scopes.<p class="paragraph"/><h4>Using Flash Scope</h4><p class="paragraph"/>Grails supports the concept of <a href="../ref/Controllers/flash.html" class="controllers">flash</a> scope as a temporary store to make attributes available for this request and the next request only. Afterwards the attributes are cleared. This is useful for setting a message directly before redirecting, for example:<p class="paragraph"/><div class="code"><pre>def delete() { |
| def b = Book.get(params.id) |
| <span class="java-keyword">if</span> (!b) { |
| flash.message = <span class="java-quote">"User not found <span class="java-keyword">for</span> id ${params.id}"</span> |
| redirect(action:list) |
| } |
| … // remaining code |
| }</pre></div><p class="paragraph"/>When the <code>list</code> action is requested, the <code>message</code> value will be in scope and can be used to display an information message. It will be removed from the <code>flash</code> scope after this second request.<p class="paragraph"/>Note that the attribute name can be anything you want, and the values are often strings used to display messages, but can be any object type.<p class="paragraph"/><h4>Scoped Controllers</h4><p class="paragraph"/>Supported controller scopes are: |
| <ul class="star"> |
| <li><code>prototype</code> (default) - A new controller will be created for each request (recommended for actions as Closure properties)</li> |
| <li><code>session</code> - One controller is created for the scope of a user session</li> |
| <li><code>singleton</code> - Only one instance of the controller ever exists (recommended for actions as methods)</li> |
| </ul><p class="paragraph"/>To enable one of the scopes, add a static <code>scope</code> property to your class with one of the valid scope values listed above, for example<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> scope = <span class="java-quote">"singleton"</span></pre></div><p class="paragraph"/>You can define the default strategy under in <code>Config.groovy</code> with the <code>grails.controllers.defaultScope</code> key, for example:<p class="paragraph"/><div class="code"><pre>grails.controllers.defaultScope = <span class="java-quote">"singleton"</span></pre></div><p class="paragraph"/>Newly created applications have the <code>grails.controllers.defaultScope</code> property set in <code>grails-app/conf/Config.groovy</code> with a value of "singleton". You may change this value to any |
| of the supported scopes listed above. If the property is not assigned a value at all, controllers will default to "prototype" scope.<p class="paragraph"/><blockquote class="note"> |
| Use scoped controllers wisely. For instance, we don't recommend having any properties in a singleton-scoped controller since they will be shared for <em class="italic">all</em> requests. |
| </blockquote> |
| |
| |
| <a name="7.1.3 Models and Views"><!-- Legacy link --></a> |
| <h2 id="modelsAndViews">7.1.3 Models and Views</h2> |
| <h4>Returning the Model</h4><p class="paragraph"/>A model is a Map that the view uses when rendering. The keys within that Map correspond to variable names accessible by the view. There are a couple of ways to return a model. First, you can explicitly return a Map instance:<p class="paragraph"/><div class="code"><pre>def show() { |
| [book: Book.get(params.id)] |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| The above does <em class="italic">not</em> reflect what you should use with the scaffolding views - see the <a href="../guide/single.html#scaffolding" class="guide">scaffolding section</a> for more details. |
| </blockquote><p class="paragraph"/>A more advanced approach is to return an instance of the Spring <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/web/servlet/ModelAndView.html" class="api">ModelAndView</a> class:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.springframework.web.servlet.ModelAndView<p class="paragraph"/>def index() { |
| // get some books just <span class="java-keyword">for</span> the index page, perhaps your favorites |
| def favoriteBooks = ...<p class="paragraph"/> // forward to the list view to show them |
| <span class="java-keyword">return</span> <span class="java-keyword">new</span> ModelAndView(<span class="java-quote">"/book/list"</span>, [ bookList : favoriteBooks ]) |
| }</pre></div><p class="paragraph"/>One thing to bear in mind is that certain variable names can not be used in your model: |
| <ul class="star"> |
| <li><code>attributes</code></li> |
| <li><code>application</code></li> |
| </ul><p class="paragraph"/>Currently, no error will be reported if you do use them, but this will hopefully change in a future version of Grails.<p class="paragraph"/><h4>Selecting the View</h4><p class="paragraph"/>In both of the previous two examples there was no code that specified which <a href="../guide/single.html#gsp" class="guide">view</a> to render. So how does Grails know which one to pick? The answer lies in the conventions. Grails will look for a view at the location <code>grails-app/views/book/show.gsp</code> for this <code>show</code> action:<p class="paragraph"/><div class="code"><pre>class BookController { |
| def show() { |
| [book: Book.get(params.id)] |
| } |
| }</pre></div><p class="paragraph"/>To render a different view, use the <a href="../ref/Controllers/render.html" class="controllers">render</a> method:<p class="paragraph"/><div class="code"><pre>def show() { |
| def map = [book: Book.get(params.id)] |
| render(view: <span class="java-quote">"display"</span>, model: map) |
| }</pre></div><p class="paragraph"/>In this case Grails will attempt to render a view at the location <code>grails-app/views/book/display.gsp</code>. Notice that Grails automatically qualifies the view location with the <code>book</code> directory of the <code>grails-app/views</code> directory. This is convenient, but to access shared views you need instead you can use an absolute path instead of a relative one:<p class="paragraph"/><div class="code"><pre>def show() { |
| def map = [book: Book.get(params.id)] |
| render(view: <span class="java-quote">"/shared/display"</span>, model: map) |
| }</pre></div><p class="paragraph"/>In this case Grails will attempt to render a view at the location <code>grails-app/views/shared/display.gsp</code>.<p class="paragraph"/>Grails also supports JSPs as views, so if a GSP isn't found in the expected location but a JSP is, it will be used instead. |
| <h4>Selecting Views For Namespaced Controllers</h4><p class="paragraph"/>If a controller defines a namespace for itself with the <a href="../guide/single.html#namespacedControllers" class="guide">namespace</a> property that will affect the root directory in which Grails will look for views which are specified with a relative path. The default root directory for views rendered by a namespaced controller is <code>grails-app/views/<namespace name>/<controller name>/</code>. If the view is not found in the namespaced directory then Grails will fallback to looking for the view in the non-namespaced directory.<p class="paragraph"/>See the example below.<p class="paragraph"/><div class="code"><pre>class ReportingController { |
| <span class="java-keyword">static</span> namespace = 'business'<p class="paragraph"/> def humanResources() { |
| // This will render grails-app/views/business/reporting/humanResources.gsp |
| // <span class="java-keyword">if</span> it exists.<p class="paragraph"/> // If grails-app/views/business/reporting/humanResources.gsp does not |
| // exist the fallback will be grails-app/views/reporting/humanResources.gsp.<p class="paragraph"/> // The namespaced GSP will take precedence over the non-namespaced GSP.<p class="paragraph"/> [numberOfEmployees: 9] |
| }<p class="paragraph"/> |
| def accountsReceivable() { |
| // This will render grails-app/views/business/reporting/accounting.gsp |
| // <span class="java-keyword">if</span> it exists.<p class="paragraph"/> // If grails-app/views/business/reporting/accounting.gsp does not |
| // exist the fallback will be grails-app/views/reporting/accounting.gsp.<p class="paragraph"/> // The namespaced GSP will take precedence over the non-namespaced GSP.<p class="paragraph"/> render view: 'numberCrunch', model: [numberOfEmployees: 13] |
| } |
| }</pre></div><p class="paragraph"/><h4>Rendering a Response</h4><p class="paragraph"/>Sometimes it's easier (for example with Ajax applications) to render snippets of text or code to the response directly from the controller. For this, the highly flexible <code>render</code> method can be used:<p class="paragraph"/><div class="code"><pre>render <span class="java-quote">"Hello World!"</span></pre></div><p class="paragraph"/>The above code writes the text "Hello World!" to the response. Other examples include:<p class="paragraph"/><div class="code"><pre>// write some markup |
| render { |
| <span class="java-keyword">for</span> (b in books) { |
| div(id: b.id, b.title) |
| } |
| }</pre></div><p class="paragraph"/><div class="code"><pre>// render a specific view |
| render(view: 'show')</pre></div><p class="paragraph"/><div class="code"><pre>// render a template <span class="java-keyword">for</span> each item in a collection |
| render(template: 'book_template', collection: Book.list())</pre></div><p class="paragraph"/><div class="code"><pre>// render some text with encoding and content type |
| render(text: <span class="java-quote">"<xml>some xml</xml>"</span>, contentType: <span class="java-quote">"text/xml"</span>, encoding: <span class="java-quote">"UTF-8"</span>)</pre></div><p class="paragraph"/>If you plan on using Groovy's <code>MarkupBuilder</code> to generate HTML for use with the <code>render</code> method be careful of naming clashes between HTML elements and Grails tags, for example:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> groovy.xml.MarkupBuilder |
| … |
| def login() { |
| def writer = <span class="java-keyword">new</span> StringWriter() |
| def builder = <span class="java-keyword">new</span> MarkupBuilder(writer) |
| builder.html { |
| head { |
| title 'Log in' |
| } |
| body { |
| h1 'Hello' |
| form { |
| } |
| } |
| }<p class="paragraph"/> def html = writer.toString() |
| render html |
| }</pre></div><p class="paragraph"/>This will actually <a href="../guide/single.html#tagsAsMethodCalls" class="guide">call the form tag</a> (which will return some text that will be ignored by the <code>MarkupBuilder</code>). To correctly output a <code><form></code> element, use the following:<p class="paragraph"/><div class="code"><pre>def login() { |
| // … |
| body { |
| h1 'Hello' |
| builder.form { |
| } |
| } |
| // … |
| }</pre></div> |
| |
| |
| <a name="7.1.4 Redirects and Chaining"><!-- Legacy link --></a> |
| <h2 id="redirectsAndChaining">7.1.4 Redirects and Chaining</h2> |
| <h4>Redirects</h4><p class="paragraph"/>Actions can be redirected using the <a href="../ref/Controllers/redirect.html" class="controllers">redirect</a> controller method:<p class="paragraph"/><div class="code"><pre>class OverviewController {<p class="paragraph"/> def login() {}<p class="paragraph"/> def find() { |
| <span class="java-keyword">if</span> (!session.user) |
| redirect(action: 'login') |
| <span class="java-keyword">return</span> |
| } |
| … |
| } |
| }</pre></div><p class="paragraph"/>Internally the <a href="../ref/Controllers/redirect.html" class="controllers">redirect</a> method uses the <a href="http://download.oracle.com/javaee/1.4/api/javax/servlet/http/HttpServletResponse.html" class="api">HttpServletResponse</a> object's <code>sendRedirect</code> method.<p class="paragraph"/>The <code>redirect</code> method expects one of: |
| <ul class="star"> |
| <li>Another closure within the same controller class:</li> |
| </ul><p class="paragraph"/><div class="code"><pre>// Call the login action within the same class |
| redirect(action: login)</pre></div> |
| <ul class="star"> |
| <li>The name of an action (and controller name if the redirect isn't to an action in the current controller):</li> |
| </ul><p class="paragraph"/><div class="code"><pre>// Also redirects to the index action in the home controller |
| redirect(controller: 'home', action: 'index')</pre></div> |
| <ul class="star"> |
| <li> A URI for a resource relative the application context path:</li> |
| </ul><p class="paragraph"/><div class="code"><pre>// Redirect to an explicit URI |
| redirect(uri: <span class="java-quote">"/login.html"</span>)</pre></div> |
| <ul class="star"> |
| <li>Or a full URL:</li> |
| </ul><p class="paragraph"/><div class="code"><pre>// Redirect to a URL |
| redirect(url: <span class="java-quote">"http://grails.org"</span>)</pre></div><p class="paragraph"/>Parameters can optionally be passed from one action to the next using the <code>params</code> argument of the method:<p class="paragraph"/><div class="code"><pre>redirect(action: 'myaction', params: [myparam: <span class="java-quote">"myvalue"</span>])</pre></div><p class="paragraph"/>These parameters are made available through the <a href="../ref/Controllers/params.html" class="controllers">params</a> dynamic property that accesses request parameters. If a parameter is specified with the same name as a request parameter, the request parameter is overridden and the controller parameter is used.<p class="paragraph"/>Since the <code>params</code> object is a Map, you can use it to pass the current request parameters from one action to the next:<p class="paragraph"/><div class="code"><pre>redirect(action: <span class="java-quote">"next"</span>, params: params)</pre></div><p class="paragraph"/>Finally, you can also include a fragment in the target URI:<p class="paragraph"/><div class="code"><pre>redirect(controller: <span class="java-quote">"test"</span>, action: <span class="java-quote">"show"</span>, fragment: <span class="java-quote">"profile"</span>)</pre></div><p class="paragraph"/>which will (depending on the URL mappings) redirect to something like "/myapp/test/show#profile".<p class="paragraph"/><h4>Chaining</h4><p class="paragraph"/>Actions can also be chained. Chaining allows the model to be retained from one action to the next. For example calling the <code>first</code> action in this action:<p class="paragraph"/><div class="code"><pre>class ExampleChainController {<p class="paragraph"/> def first() { |
| chain(action: second, model: [one: 1]) |
| }<p class="paragraph"/> def second () { |
| chain(action: third, model: [two: 2]) |
| }<p class="paragraph"/> def third() { |
| [three: 3]) |
| } |
| }</pre></div><p class="paragraph"/>results in the model:<p class="paragraph"/><div class="code"><pre>[one: 1, two: 2, three: 3]</pre></div><p class="paragraph"/>The model can be accessed in subsequent controller actions in the chain using the <code>chainModel</code> map. This dynamic property only exists in actions following the call to the <code>chain</code> method:<p class="paragraph"/><div class="code"><pre>class ChainController {<p class="paragraph"/> def nextInChain() { |
| def model = chainModel.myModel |
| … |
| } |
| }</pre></div><p class="paragraph"/>Like the <code>redirect</code> method you can also pass parameters to the <code>chain</code> method:<p class="paragraph"/><div class="code"><pre>chain(action: <span class="java-quote">"action1"</span>, model: [one: 1], params: [myparam: <span class="java-quote">"param1"</span>])</pre></div> |
| |
| |
| |
| <h2 id="controllerInterceptors">7.1.5 Controller Interceptors</h2> |
| Often it is useful to intercept processing based on either request, session or application state. This can be achieved with action interceptors. There are currently two types of interceptors: before and after.<p class="paragraph"/><blockquote class="note"> |
| If your interceptor is likely to apply to more than one controller, you are almost certainly better off writing a standalone <a href="../guide/single.html#interceptors" class="guide">Interceptor</a>. Standaline Interceptors can be applied to multiple controllers or URIs without the need to change the logic of each controller |
| </blockquote><p class="paragraph"/><h4>Before Interception</h4><p class="paragraph"/>The <code>beforeInterceptor</code> intercepts processing before the action is executed. If it returns <code>false</code> then the intercepted action will not be executed. The interceptor can be defined for all actions in a controller as follows:<p class="paragraph"/><div class="code"><pre>def beforeInterceptor = { |
| println <span class="java-quote">"Tracing action ${actionUri}"</span> |
| }</pre></div><p class="paragraph"/>The above is declared inside the body of the controller definition. It will be executed before all actions and does not interfere with processing. A common use case is very simplistic authentication:<p class="paragraph"/><div class="code"><pre>def beforeInterceptor = [action: <span class="java-keyword">this</span>.&auth, except: 'login']<p class="paragraph"/>// defined with <span class="java-keyword">private</span> scope, so it's not considered an action |
| <span class="java-keyword">private</span> auth() { |
| <span class="java-keyword">if</span> (!session.user) { |
| redirect(action: 'login') |
| <span class="java-keyword">return</span> <span class="java-keyword">false</span> |
| } |
| }<p class="paragraph"/>def login() { |
| // display login page |
| }</pre></div><p class="paragraph"/>The above code defines a method called <code>auth</code>. A private method is used so that it is not exposed as an action to the outside world. The <code>beforeInterceptor</code> then defines an interceptor that is used on all actions <em class="italic">except</em> the login action and it executes the <code>auth</code> method. The <code>auth</code> method is referenced using Groovy's method pointer syntax. Within the method it detects whether there is a user in the session, and if not it redirects to the <code>login</code> action and returns <code>false</code>, causing the intercepted action to not be processed.<p class="paragraph"/><h4>After Interception</h4><p class="paragraph"/>Use the <code>afterInterceptor</code> property to define an interceptor that is executed after an action:<p class="paragraph"/><div class="code"><pre>def afterInterceptor = { model -> |
| println <span class="java-quote">"Tracing action ${actionUri}"</span> |
| }</pre></div><p class="paragraph"/>The after interceptor takes the resulting model as an argument and can hence manipulate the model or response.<p class="paragraph"/>An after interceptor may also modify the Spring MVC <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/web/servlet/ModelAndView.html" class="api">ModelAndView</a> object prior to rendering. In this case, the above example becomes:<p class="paragraph"/><div class="code"><pre>def afterInterceptor = { model, modelAndView -> |
| println <span class="java-quote">"Current view is ${modelAndView.viewName}"</span> |
| <span class="java-keyword">if</span> (model.someVar) modelAndView.viewName = <span class="java-quote">"/mycontroller/someotherview"</span> |
| println <span class="java-quote">"View is now ${modelAndView.viewName}"</span> |
| }</pre></div><p class="paragraph"/>This allows the view to be changed based on the model returned by the current action. Note that the <code>modelAndView</code> may be <code>null</code> if the action being intercepted called <code>redirect</code> or <code>render</code>.<p class="paragraph"/><h4>Interception Conditions</h4><p class="paragraph"/>Rails users will be familiar with the authentication example and how the 'except' condition was used when executing the interceptor (interceptors are called 'filters' in Rails; this terminology conflicts with Servlet filter terminology in Java):<p class="paragraph"/><div class="code"><pre>def beforeInterceptor = [action: <span class="java-keyword">this</span>.&auth, except: 'login']</pre></div><p class="paragraph"/>This executes the interceptor for all actions except the specified action. A list of actions can also be defined as follows:<p class="paragraph"/><div class="code"><pre>def beforeInterceptor = [action: <span class="java-keyword">this</span>.&auth, except: ['login', 'register']]</pre></div><p class="paragraph"/>The other supported condition is 'only', this executes the interceptor for only the specified action(s):<p class="paragraph"/><div class="code"><pre>def beforeInterceptor = [action: <span class="java-keyword">this</span>.&auth, only: ['secure']]</pre></div> |
| |
| |
| <a name="7.1.6 Data Binding"><!-- Legacy link --></a> |
| <h2 id="dataBinding">7.1.6 Data Binding</h2> |
| Data binding is the act of "binding" incoming request parameters onto the properties of an object or an entire graph of objects. Data binding should deal with all necessary type conversion since request parameters, which are typically delivered by a form submission, are always strings whilst the properties of a Groovy or Java object may well not be.<p class="paragraph"/><h4>Map Based Binding</h4><p class="paragraph"/>The data binder is capable of converting and assigning values in a Map to properties of an object. The binder will associate entries in the Map to properties of the object using the keys in the Map that have values which correspond to property names on the object. The following code demonstrates the basics:<p class="paragraph"/><div class="code"><pre>// grails-app/domain/Person.groovy |
| class Person { |
| <span class="java-object">String</span> firstName |
| <span class="java-object">String</span> lastName |
| <span class="java-object">Integer</span> age |
| }</pre></div><p class="paragraph"/><div class="code"><pre>def bindingMap = [firstName: 'Peter', lastName: 'Gabriel', age: 63]<p class="paragraph"/>def person = <span class="java-keyword">new</span> Person(bindingMap)<p class="paragraph"/>assert person.firstName == 'Peter' |
| assert person.lastName == 'Gabriel' |
| assert person.age == 63</pre></div><p class="paragraph"/>To update properties of a domain object you may assign a Map to the <code>properties</code> property of the domain class:<p class="paragraph"/><div class="code"><pre>def bindingMap = [firstName: 'Peter', lastName: 'Gabriel', age: 63]<p class="paragraph"/>def person = Person.get(someId) |
| person.properties = bindingMap<p class="paragraph"/>assert person.firstName == 'Peter' |
| assert person.lastName == 'Gabriel' |
| assert person.age == 63</pre></div><p class="paragraph"/>The binder can populate a full graph of objects using Maps of Maps.<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> firstName |
| <span class="java-object">String</span> lastName |
| <span class="java-object">Integer</span> age |
| Address homeAddress |
| }<p class="paragraph"/>class Address { |
| <span class="java-object">String</span> county |
| <span class="java-object">String</span> country |
| }</pre></div><p class="paragraph"/><div class="code"><pre>def bindingMap = [firstName: 'Peter', lastName: 'Gabriel', age: 63, homeAddress: [county: 'Surrey', country: 'England'] ]<p class="paragraph"/>def person = <span class="java-keyword">new</span> Person(bindingMap)<p class="paragraph"/>assert person.firstName == 'Peter' |
| assert person.lastName == 'Gabriel' |
| assert person.age == 63 |
| assert person.homeAddress.county == 'Surrey' |
| assert person.homeAddress.country == 'England'</pre></div><p class="paragraph"/><h4>Binding To Collections And Maps</h4><p class="paragraph"/>The data binder can populate and update Collections and Maps. The following code shows a simple example of populating a <code>List</code> of objects in a domain class:<p class="paragraph"/><div class="code"><pre>class Band { |
| <span class="java-object">String</span> name |
| <span class="java-keyword">static</span> hasMany = [albums: Album] |
| List albums |
| }<p class="paragraph"/>class Album { |
| <span class="java-object">String</span> title |
| <span class="java-object">Integer</span> numberOfTracks |
| }</pre></div><p class="paragraph"/><div class="code"><pre>def bindingMap = [name: 'Genesis', |
| 'albums[0]': [title: 'Foxtrot', numberOfTracks: 6], |
| 'albums[1]': [title: 'Nursery Cryme', numberOfTracks: 7]]<p class="paragraph"/>def band = <span class="java-keyword">new</span> Band(bindingMap)<p class="paragraph"/>assert band.name == 'Genesis' |
| assert band.albums.size() == 2 |
| assert band.albums[0].title == 'Foxtrot' |
| assert band.albums[0].numberOfTracks == 6 |
| assert band.albums[1].title == 'Nursery Cryme' |
| assert band.albums[1].numberOfTracks == 7</pre></div><p class="paragraph"/>That code would work in the same way if <code>albums</code> were an array instead of a <code>List</code>.<p class="paragraph"/>Note that when binding to a <code>Set</code> the structure of the <code>Map</code> being bound to the <code>Set</code> is the same as that of a <code>Map</code> being bound to a <code>List</code> but since a <code>Set</code> is unordered, the indexes don't necessarily correspond to the order of elements in the <code>Set</code>. In the code example above, if <code>albums</code> were a <code>Set</code> instead of a <code>List</code>, the <code>bindingMap</code> could look exactly the same but 'Foxtrot' might be the first album in the <code>Set</code> or it might be the second. When updating existing elements in a <code>Set</code> the <code>Map</code> being assigned to the <code>Set</code> must have <code>id</code> elements in it which represent the element in the <code>Set</code> being updated, as in the following example:<p class="paragraph"/><div class="code"><pre>/* |
| * The value of the indexes 0 and 1 in albums[0] and albums[1] are arbitrary |
| * values that can be anything as <span class="java-object">long</span> as they are unique within the Map. |
| * They <span class="java-keyword">do</span> not correspond to the order of elements in albums because albums |
| * is a Set. |
| */ |
| def bindingMap = ['albums[0]': [id: 9, title: 'The Lamb Lies Down On Broadway'] |
| 'albums[1]': [id: 4, title: 'Selling England By The Pound']]<p class="paragraph"/>def band = Band.get(someBandId)<p class="paragraph"/>/* |
| * This will find the Album in albums that has an id of 9 and will set its title |
| * to 'The Lamb Lies Down On Broadway' and will find the Album in albums that has |
| * an id of 4 and set its title to 'Selling England By The Pound'. In both |
| * cases <span class="java-keyword">if</span> the Album cannot be found in albums then the album will be retrieved |
| * from the database by id, the Album will be added to albums and will be updated |
| * with the values described above. If a Album with the specified id cannot be |
| * found in the database, then a binding error will be created and associated |
| * with the band object. More on binding errors later. |
| */ |
| band.properties = bindingMap</pre></div><p class="paragraph"/>When binding to a <code>Map</code> the structure of the binding <code>Map</code> is the same as the structure of a <code>Map</code> used for binding to a <code>List</code> or a <code>Set</code> and the index inside of square brackets corresponds to the key in the <code>Map</code> being bound to. See the following code:<p class="paragraph"/><div class="code"><pre>class Album { |
| <span class="java-object">String</span> title |
| <span class="java-keyword">static</span> hasMany = [players: Player] |
| Map players |
| }<p class="paragraph"/>class Player { |
| <span class="java-object">String</span> name |
| }</pre></div><p class="paragraph"/><div class="code"><pre>def bindingMap = [title: 'The Lamb Lies Down On Broadway', |
| 'players[guitar]': [name: 'Steve Hackett'], |
| 'players[vocals]': [name: 'Peter Gabriel'], |
| 'players[keyboards]': [name: 'Tony Banks']]<p class="paragraph"/>def album = <span class="java-keyword">new</span> Album(bindingMap)<p class="paragraph"/>assert album.title == 'The Lamb Lies Down On Broadway' |
| assert album.players.size() == 3 |
| assert album.players.guitar.name == 'Steve Hackett' |
| assert album.players.vocals.name == 'Peter Gabriel' |
| assert album.players.keyboards.name == 'Tony Banks'</pre></div><p class="paragraph"/>When updating an existing <code>Map</code>, if the key specified in the binding <code>Map</code> does not exist in the <code>Map</code> being bound to then a new value will be created and added to the <code>Map</code> with the specified key as in the following example:<p class="paragraph"/> |
| <div class="code"><pre>def bindingMap = [title: 'The Lamb Lies Down On Broadway', |
| 'players[guitar]': [name: 'Steve Hackett'], |
| 'players[vocals]': [name: 'Peter Gabriel'] |
| 'players[keyboards]': [name: 'Tony Banks']]<p class="paragraph"/>def album = <span class="java-keyword">new</span> Album(bindingMap)<p class="paragraph"/>assert album.title == 'The Lamb Lies Down On Broadway' |
| assert album.players.size() == 3 |
| assert album.players.guitar == 'Steve Hackett' |
| assert album.players.vocals == 'Peter Gabriel' |
| assert album.players.keyboards == 'Tony Banks'<p class="paragraph"/>def updatedBindingMap = ['players[drums]': [name: 'Phil Collins'], |
| 'players[keyboards]': [name: 'Anthony George Banks']]<p class="paragraph"/>album.properties = updatedBindingMap<p class="paragraph"/>assert album.title == 'The Lamb Lies Down On Broadway' |
| assert album.players.size() == 4 |
| assert album.players.guitar.name == 'Steve Hackett' |
| assert album.players.vocals.name == 'Peter Gabriel' |
| assert album.players.keyboards.name == 'Anthony George Banks' |
| assert album.players.drums.name == 'Phil Collins'</pre></div><p class="paragraph"/><h4>Binding Request Data to the Model</h4><p class="paragraph"/>The <a href="../ref/Controllers/params.html" class="controllers">params</a> object that is available in a controller has special behavior that helps convert dotted request parameter names into nested Maps that the data binder can work with. For example, if a request includes request parameters named <code>person.homeAddress.country</code> and <code>person.homeAddress.city</code> with values 'USA' and 'St. Louis' respectively, <code>params</code> would include entries like these:<p class="paragraph"/><div class="code"><pre>[person: [homeAddress: [country: 'USA', city: 'St. Louis']]]</pre></div><p class="paragraph"/>There are two ways to bind request parameters onto the properties of a domain class. The first involves using a domain classes' Map constructor:<p class="paragraph"/><div class="code"><pre>def save() { |
| def b = <span class="java-keyword">new</span> Book(params) |
| b.save() |
| }</pre></div><p class="paragraph"/>The data binding happens within the code <code>new Book(params)</code>. By passing the <a href="../ref/Controllers/params.html" class="controllers">params</a> object to the domain class constructor Grails automatically recognizes that you are trying to bind from request parameters. So if we had an incoming request like:<p class="paragraph"/><div class="code"><pre>/book/save?title=The%20Stand&author=Stephen%20King</pre></div><p class="paragraph"/>Then the <code>title</code> and <code>author</code> request parameters would automatically be set on the domain class. You can use the <a href="../ref/Domain Classes/properties.html" class="domainClasses">properties</a> property to perform data binding onto an existing instance:<p class="paragraph"/><div class="code"><pre>def save() { |
| def b = Book.get(params.id) |
| b.properties = params |
| b.save() |
| }</pre></div><p class="paragraph"/>This has the same effect as using the implicit constructor.<p class="paragraph"/>When binding an empty String (a String with no characters in it, not even spaces), the data binder will convert the empty String to null. This simplifies the most common case where the intent is to treat an empty form field as having the value null since there isn't a way to actually submit a null as a request parameter. When this behavior is not desirable the application may assign the value directly.<p class="paragraph"/>The mass property binding mechanism will by default automatically trim all Strings at binding time. To disable this behavior set the <code>grails.databinding.trimStrings</code> property to false in <code>grails-app/conf/Config.groovy</code>.<p class="paragraph"/><div class="code"><pre>// the <span class="java-keyword">default</span> value is <span class="java-keyword">true</span> |
| grails.databinding.trimStrings = <span class="java-keyword">false</span><p class="paragraph"/>// ...</pre></div><p class="paragraph"/>The mass property binding mechanism will by default automatically convert all empty Strings to null at binding time. To disable this behavior set the <code>grails.databinding.convertEmptyStringsToNull</code> property to false in <code>grials-app/conf/Config.groovy</code>.<p class="paragraph"/><div class="code"><pre>// the <span class="java-keyword">default</span> value is <span class="java-keyword">true</span> |
| grails.databinding.convertEmptyStringsToNull = <span class="java-keyword">false</span><p class="paragraph"/>// ...</pre></div><p class="paragraph"/>The order of events is that the String trimming happens and then null conversion happens so if <code>trimStrings</code> is <code>true</code> and <code>convertEmptyStringsToNull</code> is <code>true</code>, not only will empty Strings be converted to null but also blank Strings. A blank String is any String such that the <code>trim()</code> method returns an empty String.<p class="paragraph"/><blockquote class="warning"> |
| These forms of data binding in Grails are very convenient, but also indiscriminate. In other words, they will bind <em class="italic">all</em> non-transient, typed instance properties of the target object, including ones that you may not want bound. Just because the form in your UI doesn't submit all the properties, an attacker can still send malign data via a raw HTTP request. Fortunately, Grails also makes it easy to protect against such attacks - see the section titled "Data Binding and Security concerns" for more information. |
| </blockquote><p class="paragraph"/><h4>Data binding and Single-ended Associations</h4><p class="paragraph"/>If you have a <code>one-to-one</code> or <code>many-to-one</code> association you can use Grails' data binding capability to update these relationships too. For example if you have an incoming request such as:<p class="paragraph"/><div class="code"><pre>/book/save?author.id=20</pre></div><p class="paragraph"/>Grails will automatically detect the <code>.id</code> suffix on the request parameter and look up the <code>Author</code> instance for the given id when doing data binding such as:<p class="paragraph"/><div class="code"><pre>def b = <span class="java-keyword">new</span> Book(params)</pre></div><p class="paragraph"/>An association property can be set to <code>null</code> by passing the literal <code>String</code> "null". For example:<p class="paragraph"/><div class="code"><pre>/book/save?author.id=<span class="java-keyword">null</span></pre></div><p class="paragraph"/><h4>Data Binding and Many-ended Associations</h4><p class="paragraph"/>If you have a one-to-many or many-to-many association there are different techniques for data binding depending of the association type.<p class="paragraph"/>If you have a <code>Set</code> based association (the default for a <code>hasMany</code>) then the simplest way to populate an association is to send a list of identifiers. For example consider the usage of <code><g:select></code> below:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:select name=<span class="xml-quote">"books"</span> |
| from=<span class="xml-quote">"${Book.list()}"</span> |
| size=<span class="xml-quote">"5"</span> multiple=<span class="xml-quote">"yes"</span> optionKey=<span class="xml-quote">"id"</span> |
| value=<span class="xml-quote">"${author?.books}"</span> /></span></pre></div><p class="paragraph"/>This produces a select box that lets you select multiple values. In this case if you submit the form Grails will automatically use the identifiers from the select box to populate the <code>books</code> association.<p class="paragraph"/>However, if you have a scenario where you want to update the properties of the associated objects the this technique won't work. Instead you use the subscript operator:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:textField name=<span class="xml-quote">"books[0].title"</span> value=<span class="xml-quote">"the Stand"</span> /></span> |
| <span class="xml-tag"><g:textField name=<span class="xml-quote">"books[1].title"</span> value=<span class="xml-quote">"the Shining"</span> /></span></pre></div><p class="paragraph"/>However, with <code>Set</code> based association it is critical that you render the mark-up in the same order that you plan to do the update in. This is because a <code>Set</code> has no concept of order, so although we're referring to <code>books0</code> and <code>books1</code> it is not guaranteed that the order of the association will be correct on the server side unless you apply some explicit sorting yourself.<p class="paragraph"/>This is not a problem if you use <code>List</code> based associations, since a <code>List</code> has a defined order and an index you can refer to. This is also true of <code>Map</code> based associations.<p class="paragraph"/>Note also that if the association you are binding to has a size of two and you refer to an element that is outside the size of association:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:textField name=<span class="xml-quote">"books[0].title"</span> value=<span class="xml-quote">"the Stand"</span> /></span> |
| <span class="xml-tag"><g:textField name=<span class="xml-quote">"books[1].title"</span> value=<span class="xml-quote">"the Shining"</span> /></span> |
| <span class="xml-tag"><g:textField name=<span class="xml-quote">"books[2].title"</span> value=<span class="xml-quote">"Red Madder"</span> /></span></pre></div><p class="paragraph"/>Then Grails will automatically create a new instance for you at the defined position.<p class="paragraph"/>You can bind existing instances of the associated type to a <code>List</code> using the same <code>.id</code> syntax as you would use with a single-ended association. For example:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:select name=<span class="xml-quote">"books[0].id"</span> from=<span class="xml-quote">"${bookList}"</span> |
| value=<span class="xml-quote">"${author?.books[0]?.id}"</span> /></span><p class="paragraph"/><span class="xml-tag"><g:select name=<span class="xml-quote">"books[1].id"</span> from=<span class="xml-quote">"${bookList}"</span> |
| value=<span class="xml-quote">"${author?.books[1]?.id}"</span> /></span><p class="paragraph"/><span class="xml-tag"><g:select name=<span class="xml-quote">"books[2].id"</span> from=<span class="xml-quote">"${bookList}"</span> |
| value=<span class="xml-quote">"${author?.books[2]?.id}"</span> /></span></pre></div><p class="paragraph"/>Would allow individual entries in the <code>books List</code> to be selected separately.<p class="paragraph"/>Entries at particular indexes can be removed in the same way too. For example:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:select name=<span class="xml-quote">"books[0].id"</span> |
| from=<span class="xml-quote">"${Book.list()}"</span> |
| value=<span class="xml-quote">"${author?.books[0]?.id}"</span> |
| noSelection=<span class="xml-quote">"['null': '']"</span>/></span></pre></div><p class="paragraph"/>Will render a select box that will remove the association at <code>books0</code> if the empty option is chosen.<p class="paragraph"/>Binding to a <code>Map</code> property works the same way except that the list index in the parameter name is replaced by the map key:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:select name=<span class="xml-quote">"images[cover].id"</span> |
| from=<span class="xml-quote">"${Image.list()}"</span> |
| value=<span class="xml-quote">"${book?.images[cover]?.id}"</span> |
| noSelection=<span class="xml-quote">"['null': '']"</span>/></span></pre></div><p class="paragraph"/>This would bind the selected image into the <code>Map</code> property <code>images</code> under a key of <code>"cover"</code>.<p class="paragraph"/>When binding to Maps, Arrays and Collections the data binder will automatically grow the size of the collections as necessary. The default limit to how large the binder will grow a collection is 256. If the data binder encounters an entry that requires the collection be grown beyond that limit, the entry is ignored. The limit may be configured by assigning a value to the <code>grails.databinding.autoGrowCollectionLimit</code> property in <code>Config.groovy</code>.<p class="paragraph"/><div class="code"><pre>// grails-app/conf/Config.groovy<p class="paragraph"/>// the <span class="java-keyword">default</span> value is 256 |
| grails.databinding.autoGrowCollectionLimit = 128<p class="paragraph"/>// ...</pre></div><p class="paragraph"/><h4>Data binding with Multiple domain classes</h4><p class="paragraph"/>It is possible to bind data to multiple domain objects from the <a href="../ref/Controllers/params.html" class="controllers">params</a> object.<p class="paragraph"/>For example so you have an incoming request to:<p class="paragraph"/><div class="code"><pre>/book/save?book.title=The%20Stand&author.name=Stephen%20King</pre></div><p class="paragraph"/>You'll notice the difference with the above request is that each parameter has a prefix such as <code>author.</code> or <code>book.</code> which is used to isolate which parameters belong to which type. Grails' <code>params</code> object is like a multi-dimensional hash and you can index into it to isolate only a subset of the parameters to bind.<p class="paragraph"/><div class="code"><pre>def b = <span class="java-keyword">new</span> Book(params.book)</pre></div><p class="paragraph"/>Notice how we use the prefix before the first dot of the <code>book.title</code> parameter to isolate only parameters below this level to bind. We could do the same with an <code>Author</code> domain class:<p class="paragraph"/><div class="code"><pre>def a = <span class="java-keyword">new</span> Author(params.author)</pre></div><p class="paragraph"/><h4>Data Binding and Action Arguments</h4><p class="paragraph"/>Controller action arguments are subject to request parameter data binding. There are 2 categories of controller action arguments. The first category is command objects. Complex types are treated as command objects. See the <a href="../guide/single.html#commandObjects" class="guide">Command Objects</a> section of the user guide for details. The other category is basic object types. Supported types are the 8 primitives, their corresponding type wrappers and <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html" class="api">java.lang.String</a>. The default behavior is to map request parameters to action arguments by name:<p class="paragraph"/><div class="code"><pre>class AccountingController {<p class="paragraph"/> // accountNumber will be initialized with the value of params.accountNumber |
| // accountType will be initialized with params.accountType |
| def displayInvoice(<span class="java-object">String</span> accountNumber, <span class="java-object">int</span> accountType) { |
| // … |
| } |
| }</pre></div><p class="paragraph"/>For primitive arguments and arguments which are instances of any of the primitive type wrapper classes a type conversion has to be carried out before the request parameter value can be bound to the action argument. The type conversion happens automatically. In a case like the example shown above, the <code>params.accountType</code> request parameter has to be converted to an <code>int</code>. If type conversion fails for any reason, the argument will have its default value per normal Java behavior (null for type wrapper references, false for booleans and zero for numbers) and a corresponding error will be added to the <code>errors</code> property of the defining controller.<p class="paragraph"/><div class="code"><pre>/accounting/displayInvoice?accountNumber=B59786&accountType=bogusValue</pre></div><p class="paragraph"/>Since "bogusValue" cannot be converted to type int, the value of accountType will be zero, the controller's <code>errors.hasErrors()</code> will be true, the controller's <code>errors.errorCount</code> will be equal to 1 and the controller's <code>errors.getFieldError('accountType')</code> will contain the corresponding error.<p class="paragraph"/>If the argument name does not match the name of the request parameter then the <code>@grails.web.RequestParameter</code> annotation may be applied to an argument to express the name of the request parameter which should be bound to that argument:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.web.RequestParameter<p class="paragraph"/>class AccountingController {<p class="paragraph"/> // mainAccountNumber will be initialized with the value of params.accountNumber |
| // accountType will be initialized with params.accountType |
| def displayInvoice(@RequestParameter('accountNumber') <span class="java-object">String</span> mainAccountNumber, <span class="java-object">int</span> accountType) { |
| // … |
| } |
| }</pre></div><p class="paragraph"/> |
| <h4>Data binding and type conversion errors</h4><p class="paragraph"/>Sometimes when performing data binding it is not possible to convert a particular String into a particular target type. This results in a type conversion error. Grails will retain type conversion errors inside the <a href="../ref/Domain Classes/errors.html" class="domainClasses">errors</a> property of a Grails domain class. For example:<p class="paragraph"/><div class="code"><pre>class Book { |
| … |
| URL publisherURL |
| }</pre></div><p class="paragraph"/>Here we have a domain class <code>Book</code> that uses the <code>java.net.URL</code> class to represent URLs. Given an incoming request such as:<p class="paragraph"/><div class="code"><pre>/book/save?publisherURL=a-bad-url</pre></div><p class="paragraph"/>it is not possible to bind the string <code>a-bad-url</code> to the <code>publisherURL</code> property as a type mismatch error occurs. You can check for these like this:<p class="paragraph"/><div class="code"><pre>def b = <span class="java-keyword">new</span> Book(params)<p class="paragraph"/><span class="java-keyword">if</span> (b.hasErrors()) { |
| println <span class="java-quote">"The value ${b.errors.getFieldError('publisherURL').rejectedValue}"</span> + |
| <span class="java-quote">" is not a valid URL!"</span> |
| }</pre></div><p class="paragraph"/>Although we have not yet covered error codes (for more information see the section on <a href="../guide/single.html#validation" class="guide">Validation</a>), for type conversion errors you would want a message from the <code>grails-app/i18n/messages.properties</code> file to use for the error. You can use a generic error message handler such as:<p class="paragraph"/><div class="code"><pre>typeMismatch.java.net.URL=The field {0} is not a valid URL</pre></div><p class="paragraph"/>Or a more specific one:<p class="paragraph"/><div class="code"><pre>typeMismatch.Book.publisherURL=The publisher URL you specified is not a valid URL</pre></div><p class="paragraph"/><h4>The BindUsing Annotation</h4><p class="paragraph"/>The <a href="http://grails.org/doc/3.0.x/api/org/grails/databinding/BindUsing.html" class="api">BindUsing</a> annotation may be used to define a custom binding mechanism for a particular field in a class. Any time data binding is being applied to the field the closure value of the annotation will be invoked with 2 arguments. The first argument is the object that data binding is being applied to and the second argument is <a href="http://grails.org/doc/3.0.x/api/org/grails/databinding/DataBindingSource.html" class="api">DataBindingSource</a> which is the data source for the data binding. The value returned from the closure will be bound to the property. The following example would result in the upper case version of the <code>name</code> value in the source being applied to the <code>name</code> field during data binding.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.grails.databinding.BindUsing<p class="paragraph"/>class SomeClass { |
| @BindUsing({obj, source -><p class="paragraph"/> //source is DataSourceBinding which is similar to a Map |
| //and defines getAt operation but source.name cannot be used here. |
| //In order to get name from source use getAt instead as shown below.<p class="paragraph"/> source['name']?.toUpperCase() |
| }) |
| <span class="java-object">String</span> name |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| Note that data binding is only possible when the name of the request parameter matches with the field name in the class. |
| Here, <code>name</code> from request parameters matches with <code>name</code> from <code>SomeClass</code>. |
| </blockquote><p class="paragraph"/>The <a href="http://grails.org/doc/3.0.x/api/org/grails/databinding/BindUsing.html" class="api">BindUsing</a> annotation may be used to define a custom binding mechanism for all of the fields on a particular class. When the annotation is applied to a class, the value assigned to the annotation should be a class which implements the <a href="http://grails.org/doc/3.0.x/api/org/grails/databinding/BindingHelper.html" class="api">BindingHelper</a> interface. An instance of that class will be used any time a value is bound to a property in the class that this annotation has been applied to.<p class="paragraph"/><div class="code"><pre>@BindUsing(SomeClassWhichImplementsBindingHelper) |
| class SomeClass { |
| <span class="java-object">String</span> someProperty |
| <span class="java-object">Integer</span> someOtherProperty |
| }</pre></div><p class="paragraph"/><h4>Custom Data Converters</h4><p class="paragraph"/>The binder will do a lot of type conversion automatically. Some applications may want to define their own mechanism for converting values and a simple way to do this is to write a class which implements <a href="http://grails.org/doc/3.0.x/api/org/grails/databinding/converters/ValueConverter.html" class="api">ValueConverter</a> and register an instance of that class as a bean in the Spring application context.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> com.myapp.converters<p class="paragraph"/><span class="java-keyword">import</span> org.grails.databinding.converters.ValueConverter<p class="paragraph"/>/** |
| * A custom converter which will convert <span class="java-object">String</span> of the |
| * form 'city:state' into an Address object. |
| */ |
| class AddressValueConverter <span class="java-keyword">implements</span> ValueConverter {<p class="paragraph"/> <span class="java-object">boolean</span> canConvert(value) { |
| value <span class="java-keyword">instanceof</span> <span class="java-object">String</span> |
| }<p class="paragraph"/> def convert(value) { |
| def pieces = value.split(':') |
| <span class="java-keyword">new</span> com.myapp.Address(city: pieces[0], state: pieces[1]) |
| }<p class="paragraph"/> <span class="java-object">Class</span><?> getTargetType() { |
| com.myapp.Address |
| } |
| }</pre></div><p class="paragraph"/>An instance of that class needs to be registered as a bean in the Spring application context. The bean name is not important. All beans that implemented ValueConverter will be automatically plugged in to the data binding process.<p class="paragraph"/><div class="code"><pre>// grails-app/conf/spring/resources.groovy<p class="paragraph"/>beans = {<p class="paragraph"/> addressConverter com.myapp.converters.AddressValueConverter<p class="paragraph"/> // ...<p class="paragraph"/>}</pre></div><p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> firstName |
| Address homeAddress |
| }<p class="paragraph"/>class Address { |
| <span class="java-object">String</span> city |
| <span class="java-object">String</span> state |
| }<p class="paragraph"/>def person = <span class="java-keyword">new</span> Person() |
| person.properties = [firstName: 'Jeff', homeAddress: <span class="java-quote">"O'Fallon:Missouri"</span>] |
| assert person.firstName == 'Jeff' |
| assert person.homeAddress.city = <span class="java-quote">"O'Fallon"</span> |
| assert person.homeAddress.state = 'Missouri'</pre></div><p class="paragraph"/><h4>Date Formats For Data Binding</h4><p class="paragraph"/>A custom date format may be specified to be used when binding a String to a Date value by applying the <a href="http://grails.org/doc/3.0.x/api/org/grails/databinding/BindingFormat.html" class="api">BindingFormat</a> annotation to a Date field.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.grails.databinding.BindingFormat<p class="paragraph"/>class Person { |
| @BindingFormat('MMddyyyy') |
| Date birthDate |
| }</pre></div><p class="paragraph"/>A global setting may be configured in <code>Config.groovy</code> to define date formats which will be used application wide when binding to Date.<p class="paragraph"/><div class="code"><pre>// grails-app/conf/Config.groovy<p class="paragraph"/>grails.databinding.dateFormats = ['MMddyyyy', 'yyyy-MM-dd HH:mm:ss.S', <span class="java-quote">"yyyy-MM-dd'T'hh:mm:ss'Z'"</span>]</pre></div><p class="paragraph"/>The formats specified in <code>grails.databinding.dateFormats</code> will be attempted in the order in which they are included in the List. If a property is marked with @BindingFormat, the @BindingFormat will take precedence over the values specified in <code>grails.databinding.dateFormats</code>.<p class="paragraph"/>The default formats that are used are "yyyy-MM-dd HH:mm:ss.S" and "yyyy-MM-dd'T'hh:mm:ss'Z'".<p class="paragraph"/><h4>Custom Formatted Converters</h4><p class="paragraph"/>You may supply your own handler for the <a href="http://grails.org/doc/3.0.x/api/org/grails/databinding/BindingFormat.html" class="api">BindingFormat</a> annotation by writing a class which implements the <a href="http://grails.org/doc/3.0.x/api/org/grails/databinding/converters/FormattedValueConverter.html" class="api">FormattedValueConverter</a> interface and registering an instance of that class as a bean in the Spring application context. Below is an example of a trivial custom String formatter that might convert the case of a String based on the value assigned to the BindingFormat annotation.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> com.myapp.converters<p class="paragraph"/><span class="java-keyword">import</span> org.grails.databinding.converters.FormattedValueConverter<p class="paragraph"/>class FormattedStringValueConverter <span class="java-keyword">implements</span> FormattedValueConverter { |
| def convert(value, <span class="java-object">String</span> format) { |
| <span class="java-keyword">if</span>('UPPERCASE' == format) { |
| value = value.toUpperCase() |
| } <span class="java-keyword">else</span> <span class="java-keyword">if</span>('LOWERCASE' == format) { |
| value = value.toLowerCase() |
| } |
| value |
| }<p class="paragraph"/> <span class="java-object">Class</span> getTargetType() { |
| // specifies the type to which <span class="java-keyword">this</span> converter may be applied |
| <span class="java-object">String</span> |
| } |
| }</pre></div><p class="paragraph"/>An instance of that class needs to be registered as a bean in the Spring application context. The bean name is not important. All beans that implemented FormattedValueConverter will be automatically plugged in to the data binding process.<p class="paragraph"/><div class="code"><pre>// grails-app/conf/spring/resources.groovy<p class="paragraph"/>beans = {<p class="paragraph"/> formattedStringConverter com.myapp.converters.FormattedStringValueConverter<p class="paragraph"/> // ...<p class="paragraph"/>}</pre></div><p class="paragraph"/>With that in place the <code>BindingFormat</code> annotation may be applied to String fields to inform the data binder to take advantage of the custom converter.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.grails.databinding.BindingFormat<p class="paragraph"/>class Person { |
| @BindingFormat('UPPERCASE') |
| <span class="java-object">String</span> someUpperCaseString<p class="paragraph"/> @BindingFormat('LOWERCASE') |
| <span class="java-object">String</span> someLowerCaseString<p class="paragraph"/> <span class="java-object">String</span> someOtherString |
| }</pre></div><p class="paragraph"/> |
| <h4>Localized Binding Formats</h4><p class="paragraph"/>The <code>BindingFormat</code> annotation supports localized format strings by using the optional <code>code</code> attribute. If a value is assigned to the code attribute that value will be used as the message code to retrieve the binding format string from the <code>messageSource</code> bean in the Spring application context and that lookup will be localized.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.grails.databinding.BindingFormat<p class="paragraph"/>class Person { |
| @BindingFormat(code='date.formats.birthdays') |
| Date birthDate |
| }</pre></div><p class="paragraph"/> |
| <div class="code"><pre># grails-app/conf/i18n/messages.properties |
| date.formats.birthdays=MMddyyyy</pre></div><p class="paragraph"/><div class="code"><pre># grails-app/conf/i18n/messages_es.properties |
| date.formats.birthdays=ddMMyyyy</pre></div><p class="paragraph"/><h4>Structured Data Binding Editors</h4><p class="paragraph"/>A structured data binding editor is a helper class which can bind structured request parameters to a property. The common use case for structured binding is binding to a <code>Date</code> object which might be constructed from several smaller pieces of information contained in several request parameters with names like <code>birthday_month</code>, <code>birthday_date</code> and <code>birthday_year</code>. The structured editor would retrieve all of those individual pieces of information and use them to construct a <code>Date</code>.<p class="paragraph"/>The framework provides a structured editor for binding to <code>Date</code> objects. An application may register its own structured editors for whatever types are appropriate. Consider the following classes:<p class="paragraph"/><div class="code"><pre>// src/groovy/databinding/Gadget.groovy |
| <span class="java-keyword">package</span> databinding<p class="paragraph"/>class Gadget { |
| Shape expandedShape |
| Shape compressedShape |
| }</pre></div><p class="paragraph"/><div class="code"><pre>// src/groovy/databinding/Shape.groovy |
| <span class="java-keyword">package</span> databinding<p class="paragraph"/>class Shape { |
| <span class="java-object">int</span> area |
| }</pre></div><p class="paragraph"/>A <code>Gadget</code> has 2 <code>Shape</code> fields. A <code>Shape</code> has an <code>area</code> property. It may be that the application wants to accept request parameters like <code>width</code> and <code>height</code> and use those to calculate the <code>area</code> of a <code>Shape</code> at binding time. A structured binding editor is well suited for that.<p class="paragraph"/>The way to register a structured editor with the data binding process is to add an instance of the <a href="http://grails.org/doc/3.0.x/api/org/grails/databinding/TypedStructuredBindingEditor.html" class="api">org.grails.databinding.TypedStructuredBindingEditor</a> interface to the Spring application context. The easiest way to implement the <code>TypedStructuredBindingEditor</code> interface is to extend the <a href="http://grails.org/doc/3.0.x/api/org/grails/databinding/converters/AbstractStructuredBindingEditor.html" class="api">org.grails.databinding.converters.AbstractStructuredBindingEditor</a> abstract class and override the <code>getPropertyValue</code> method as shown below:<p class="paragraph"/><div class="code"><pre>// src/groovy/databinding/converters/StructuredShapeEditor.groovy |
| <span class="java-keyword">package</span> databinding.converters<p class="paragraph"/><span class="java-keyword">import</span> databinding.Shape<p class="paragraph"/><span class="java-keyword">import</span> org.grails.databinding.converters.AbstractStructuredBindingEditor<p class="paragraph"/>class StructuredShapeEditor <span class="java-keyword">extends</span> AbstractStructuredBindingEditor<Shape> {<p class="paragraph"/> <span class="java-keyword">public</span> Shape getPropertyValue(Map values) { |
| // retrieve the individual values from the Map |
| def width = values.width as <span class="java-object">int</span> |
| def height = values.height as <span class="java-object">int</span><p class="paragraph"/> // use the values to calculate the area of the Shape |
| def area = width * height<p class="paragraph"/> // create and <span class="java-keyword">return</span> a Shape with the appropriate area |
| <span class="java-keyword">new</span> Shape(area: area) |
| } |
| }</pre></div><p class="paragraph"/>An instance of that class needs to be registered with the Spring application context:<p class="paragraph"/><div class="code"><pre>// grails-app/conf/spring/resources.groovy |
| beans = { |
| shapeEditor databinding.converters.StructuredShapeEditor<p class="paragraph"/> // … |
| }</pre></div><p class="paragraph"/>When the data binder binds to an instance of the <code>Gadget</code> class it will check to see if there are request parameters with names <code>compressedShape</code> and <code>expandedShape</code> which have a value of "struct" and if they do exist, that will trigger the use of the <code>StructuredShapeEditor</code>. The individual components of the structure need to have parameter names of the form propertyName_structuredElementName. In the case of the <code>Gadget</code> class above that would mean that the <code>compressedShape</code> request parameter should have a value of "struct" and the <code>compressedShape_width</code> and <code>compressedShape_height</code> parameters should have values which represent the width and the height of the compressed <code>Shape</code>. Similarly, the <code>expandedShape</code> request parameter should have a value of "struct" and the <code>expandedShape_width</code> and <code>expandedShape_height</code> parameters should have values which represent the width and the height of the expanded <code>Shape</code>.<p class="paragraph"/><div class="code"><pre>// grails-app/controllers/demo/DemoController.groovy |
| class DemoController {<p class="paragraph"/> def createGadget(Gadget gadget) { |
| /*<p class="paragraph"/> /demo/createGadget?expandedShape=struct&expandedShape_width=80&expandedShape_height=30 |
| &compressedShape=struct&compressedShape_width=10&compressedShape_height=3<p class="paragraph"/> */<p class="paragraph"/> // with the request parameters shown above gadget.expandedShape.area would be 2400 |
| // and gadget.compressedShape.area would be 30<p class="paragraph"/> // ...<p class="paragraph"/> } |
| }</pre></div><p class="paragraph"/>Typically the request parameters with "struct" as their value would be represented by hidden form fields.<p class="paragraph"/><h4>Data Binding Event Listeners</h4><p class="paragraph"/>The <a href="http://grails.org/doc/3.0.x/api/org/grails/databinding/events/DataBindingListener.html" class="api">DataBindingListener</a> interface provides a mechanism for listeners to be notified of data binding events. The interface looks like this:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> org.grails.databinding.events;<p class="paragraph"/><span class="java-keyword">import</span> org.grails.databinding.errors.BindingError;<p class="paragraph"/><span class="java-keyword">public</span> <span class="java-keyword">interface</span> DataBindingListener {<p class="paragraph"/> /** |
| * @<span class="java-keyword">return</span> <span class="java-keyword">true</span> <span class="java-keyword">if</span> the listener is interested in events <span class="java-keyword">for</span> the specified type. |
| */ |
| <span class="java-object">boolean</span> supports(<span class="java-object">Class</span><?> clazz);<p class="paragraph"/> /** |
| * Called when data binding is about to start. |
| * |
| * @param target The object data binding is being imposed upon |
| * @param errors the Spring Errors instance (a org.springframework.validation.BindingResult) |
| * @<span class="java-keyword">return</span> <span class="java-keyword">true</span> <span class="java-keyword">if</span> data binding should <span class="java-keyword">continue</span> |
| */ |
| <span class="java-object">Boolean</span> beforeBinding(<span class="java-object">Object</span> target, <span class="java-object">Object</span> errors);<p class="paragraph"/> /** |
| * Called when data binding is about to imposed on a property |
| * |
| * @param target The object data binding is being imposed upon |
| * @param propertyName The name of the property being bound to |
| * @param value The value of the property being bound |
| * @param errors the Spring Errors instance (a org.springframework.validation.BindingResult) |
| * @<span class="java-keyword">return</span> <span class="java-keyword">true</span> <span class="java-keyword">if</span> data binding should <span class="java-keyword">continue</span>, otherwise <span class="java-keyword">return</span> <span class="java-keyword">false</span> |
| */ |
| <span class="java-object">Boolean</span> beforeBinding(<span class="java-object">Object</span> target, <span class="java-object">String</span> propertyName, <span class="java-object">Object</span> value, <span class="java-object">Object</span> errors);<p class="paragraph"/> /** |
| * Called after data binding has been imposed on a property |
| * |
| * @param target The object data binding is being imposed upon |
| * @param propertyName The name of the property that was bound to |
| * @param errors the Spring Errors instance (a org.springframework.validation.BindingResult) |
| */ |
| void afterBinding(<span class="java-object">Object</span> target, <span class="java-object">String</span> propertyName, <span class="java-object">Object</span> errors);<p class="paragraph"/> /** |
| * Called after data binding has finished. |
| * |
| * @param target The object data binding is being imposed upon |
| * @param errors the Spring Errors instance (a org.springframework.validation.BindingResult) |
| */ |
| void afterBinding(<span class="java-object">Object</span> target, <span class="java-object">Object</span> errors);<p class="paragraph"/> /** |
| * Called when an error occurs binding to a property |
| * @param error encapsulates information about the binding error |
| * @param errors the Spring Errors instance (a org.springframework.validation.BindingResult) |
| * @see BindingError |
| */ |
| void bindingError(BindingError error, <span class="java-object">Object</span> errors); |
| }</pre></div><p class="paragraph"/>Any bean in the Spring application context which implements that interface will automatically be registered with the data binder. The <a href="http://grails.org/doc/3.0.x/api/org/grails/databinding/events/DataBindingListenerAdapter.html" class="api">DataBindingListenerAdapter</a> class implements the <code>DataBindingListener</code> interface and provides default implementations for all of the methods in the interface so this class is well suited for subclassing so your listener class only needs to provide implementations for the methods your listener is interested in.<p class="paragraph"/>The Grails data binder has limited support for the older <a href="http://grails.org/doc/3.0.x/api/org/codehaus/groovy/grails/web/binding/BindEventListener.html" class="api">BindEventListener</a> style listeners. <code>BindEventListener</code> looks like this:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> org.codehaus.groovy.grails.web.binding;<p class="paragraph"/><span class="java-keyword">import</span> org.springframework.beans.MutablePropertyValues; |
| <span class="java-keyword">import</span> org.springframework.beans.TypeConverter;<p class="paragraph"/><span class="java-keyword">public</span> <span class="java-keyword">interface</span> BindEventListener {<p class="paragraph"/> /** |
| * @param target The target to bind to |
| * @param source The source of the binding, typically a Map |
| * @param typeConverter The type converter to be used |
| */ |
| void doBind(<span class="java-object">Object</span> target, MutablePropertyValues source, TypeConverter typeConverter); |
| }</pre></div><p class="paragraph"/>Support for <code>BindEventListener</code> is disabled by default. To enable support assign a value of <code>true</code> to the <code>grails.databinding.enableSpringEventAdapter</code> property in <code>grails-app/conf/Config.groovy</code>.<p class="paragraph"/><div class="code"><pre>// grails-app/conf/Config.groovy |
| grails.databinding.enableSpringEventAdapter=<span class="java-keyword">true</span><p class="paragraph"/>...</pre></div><p class="paragraph"/>With <code>enableSpringEventAdapter</code> set to <code>true</code> instances of <code>BindEventListener</code> which are in the Spring application context will automatically be registered with the data binder. Notice that the <code>MutablePropertyValues</code> and <code>TypeConverter</code> arguments to the <code>doBind</code> method in <code>BindEventListener</code> are Spring specific classes and are not relevant to the current data binder. The event adapter will pass <code>null</code> values for those arguments. The only real value passed into the <code>doBind</code> method will be the object being bound to. This limited support is provided for backward compatibility and will be useful for a subset of scenarios. Developers are encouraged to migrate their <code>BindEventListener</code> beans to the newer <code>DataBindingListener</code> model.<p class="paragraph"/><h4>Using The Data Binder Directly</h4><p class="paragraph"/>There are situations where an application may want to use the data binder directly. For example, to do binding in a Service on some arbitrary object which is not a domain class. The following will not work because the <code>properties</code> property is read only.<p class="paragraph"/><div class="code"><pre>// src/groovy/bindingdemo/Widget.groovy |
| <span class="java-keyword">package</span> bindingdemo<p class="paragraph"/>class Widget { |
| <span class="java-object">String</span> name |
| <span class="java-object">Integer</span> size |
| }</pre></div><p class="paragraph"/><div class="code"><pre>// grails-app/services/bindingdemo/WidgetService.groovy |
| <span class="java-keyword">package</span> bindingdemo<p class="paragraph"/>class WidgetService {<p class="paragraph"/> def updateWidget(Widget widget, Map data) { |
| // <span class="java-keyword">this</span> will <span class="java-keyword">throw</span> an exception because |
| // properties is read-only |
| widget.properties = data |
| } |
| }</pre></div><p class="paragraph"/>An instance of the data binder is in the Spring application context with a bean name of <code>grailsWebDataBinder</code>. That bean implements the <a href="http://grails.org/doc/3.0.x/api/org/grails/databinding/DataBinder.html" class="api">DataBinder</a> interface. The following code demonstrates using the data binder directly.<p class="paragraph"/><div class="code"><pre>// grails-app/services/bindingdmeo/WidgetService |
| <span class="java-keyword">package</span> bindingdemo<p class="paragraph"/><span class="java-keyword">import</span> org.grails.databinding.SimpleMapDataBindingSource<p class="paragraph"/>class WidgetService {<p class="paragraph"/> // <span class="java-keyword">this</span> bean will be autowired into the service |
| def grailsWebDataBinder<p class="paragraph"/> def updateWidget(Widget widget, Map data) { |
| grailsWebDataBinder.bind widget, data as SimpleMapDataBindingSource |
| }<p class="paragraph"/>}</pre></div><p class="paragraph"/>See the <a href="http://grails.org/doc/3.0.x/api/org/grails/databinding/DataBinder.html" class="api">DataBinder</a> documentation for more information about overloaded versions |
| of the <code>bind</code> method.<p class="paragraph"/><h4>Data Binding and Security Concerns</h4><p class="paragraph"/>When batch updating properties from request parameters you need to be careful not to allow clients to bind malicious data to domain classes and be persisted in the database. You can limit what properties are bound to a given domain class using the subscript operator:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1)<p class="paragraph"/>p.properties['firstName','lastName'] = params</pre></div><p class="paragraph"/>In this case only the <code>firstName</code> and <code>lastName</code> properties will be bound.<p class="paragraph"/>Another way to do this is is to use <a href="../guide/single.html#commandObjects" class="guide">Command Objects</a> as the target of data binding instead of domain classes. Alternatively there is also the flexible <a href="../ref/Controllers/bindData.html" class="controllers">bindData</a> method.<p class="paragraph"/>The <code>bindData</code> method allows the same data binding capability, but to arbitrary objects:<p class="paragraph"/><div class="code"><pre>def p = <span class="java-keyword">new</span> Person() |
| bindData(p, params)</pre></div><p class="paragraph"/>The <code>bindData</code> method also lets you exclude certain parameters that you don't want updated:<p class="paragraph"/><div class="code"><pre>def p = <span class="java-keyword">new</span> Person() |
| bindData(p, params, [exclude: 'dateOfBirth'])</pre></div><p class="paragraph"/>Or include only certain properties:<p class="paragraph"/><div class="code"><pre>def p = <span class="java-keyword">new</span> Person() |
| bindData(p, params, [include: ['firstName', 'lastName']])</pre></div><p class="paragraph"/><blockquote class="note"> |
| Note that if an empty List is provided as a value for the <code>include</code> parameter then all fields will be subject to binding if they are not explicitly excluded. |
| </blockquote> |
| |
| |
| |
| <h2 id="xmlAndJSON">7.1.7 XML and JSON Responses</h2> |
| <h4>Using the render method to output XML</h4><p class="paragraph"/>Grails supports a few different ways to produce XML and JSON responses. The first is the <a href="../ref/Controllers/render.html" class="controllers">render</a> method.<p class="paragraph"/>The <code>render</code> method can be passed a block of code to do mark-up building in XML:<p class="paragraph"/><div class="code"><pre>def list() {<p class="paragraph"/> def results = Book.list()<p class="paragraph"/> render(contentType: <span class="java-quote">"text/xml"</span>) { |
| books { |
| <span class="java-keyword">for</span> (b in results) { |
| book(title: b.title) |
| } |
| } |
| } |
| }</pre></div><p class="paragraph"/>The result of this code would be something like:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><books></span> |
| <span class="xml-tag"><book title=<span class="xml-quote">"The Stand"</span> /></span> |
| <span class="xml-tag"><book title=<span class="xml-quote">"The Shining"</span> /></span> |
| <span class="xml-tag"></books></span></pre></div><p class="paragraph"/>Be careful to avoid naming conflicts when using mark-up building. For example this code would produce an error:<p class="paragraph"/><div class="code"><pre>def list() {<p class="paragraph"/> def books = Book.list() // naming conflict here<p class="paragraph"/> render(contentType: <span class="java-quote">"text/xml"</span>) { |
| books { |
| <span class="java-keyword">for</span> (b in results) { |
| book(title: b.title) |
| } |
| } |
| } |
| }</pre></div><p class="paragraph"/>This is because there is local variable <code>books</code> which Groovy attempts to invoke as a method.<p class="paragraph"/><h4>Using the render method to output JSON</h4><p class="paragraph"/>The <code>render</code> method can also be used to output JSON:<p class="paragraph"/><div class="code"><pre>def list() {<p class="paragraph"/> def results = Book.list()<p class="paragraph"/> render(contentType: <span class="java-quote">"application/json"</span>) { |
| books = array { |
| <span class="java-keyword">for</span> (b in results) { |
| book title: b.title |
| } |
| } |
| } |
| }</pre></div><p class="paragraph"/>In this case the result would be something along the lines of:<p class="paragraph"/><div class="code"><pre>[ |
| {<span class="java-quote">"title"</span>:<span class="java-quote">"The Stand"</span>}, |
| {<span class="java-quote">"title"</span>:<span class="java-quote">"The Shining"</span>} |
| ]</pre></div><p class="paragraph"/>The same dangers with naming conflicts described above for XML also apply to JSON building.<p class="paragraph"/><h4>Automatic XML Marshalling</h4><p class="paragraph"/>Grails also supports automatic marshalling of <a href="../guide/single.html#GORM" class="guide">domain classes</a> to XML using special converters.<p class="paragraph"/>To start off with, import the <code>grails.converters</code> package into your controller:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.converters.*</pre></div><p class="paragraph"/>Now you can use the following highly readable syntax to automatically convert domain classes to XML:<p class="paragraph"/><div class="code"><pre>render Book.list() as XML</pre></div><p class="paragraph"/>The resulting output would look something like the following::<p class="paragraph"/><div class="code"><pre><?xml version=<span class="java-quote">"1.0"</span> encoding=<span class="java-quote">"ISO-8859-1"</span>?> |
| <list> |
| <book id=<span class="java-quote">"1"</span>> |
| <author>Stephen King</author> |
| <title>The Stand</title> |
| </book> |
| <book id=<span class="java-quote">"2"</span>> |
| <author>Stephen King</author> |
| <title>The Shining</title> |
| </book> |
| </list></pre></div><p class="paragraph"/> |
| For more information on XML marshalling see the section on <a href="../guide/single.html#REST" class="guide">REST</a><p class="paragraph"/><h4>Automatic JSON Marshalling</h4><p class="paragraph"/>Grails also supports automatic marshalling to JSON using the same mechanism. Simply substitute <code>XML</code> with <code>JSON</code>:<p class="paragraph"/><div class="code"><pre>render Book.list() as JSON</pre></div><p class="paragraph"/>The resulting output would look something like the following:<p class="paragraph"/><div class="code"><pre>[ |
| {<span class="java-quote">"id"</span>:1, |
| <span class="java-quote">"class"</span>:<span class="java-quote">"Book"</span>, |
| <span class="java-quote">"author"</span>:<span class="java-quote">"Stephen King"</span>, |
| <span class="java-quote">"title"</span>:<span class="java-quote">"The Stand"</span>}, |
| {<span class="java-quote">"id"</span>:2, |
| <span class="java-quote">"class"</span>:<span class="java-quote">"Book"</span>, |
| <span class="java-quote">"author"</span>:<span class="java-quote">"Stephen King"</span>, |
| <span class="java-quote">"releaseDate"</span>:<span class="java-keyword">new</span> Date(1194127343161), |
| <span class="java-quote">"title"</span>:<span class="java-quote">"The Shining"</span>} |
| ]</pre></div> |
| |
| |
| <a name="7.1.8 More on JSONBuilder"><!-- Legacy link --></a> |
| <h2 id="moreOnJSONBuilder">7.1.8 More on JSONBuilder</h2> |
| The previous section on on XML and JSON responses covered simplistic examples of rendering XML and JSON responses. Whilst the XML builder used by Grails is the standard <a href="http://groovy.codehaus.org/Reading+XML+using+Groovy's+XmlSlurper" target="blank">XmlSlurper</a> found in Groovy, the JSON builder is a custom implementation specific to Grails.<p class="paragraph"/><h4>JSONBuilder and Grails versions</h4><p class="paragraph"/>JSONBuilder behaves different depending on the version of Grails you use. For version below 1.2 the deprecated <a href="http://grails.org/doc/3.0.x/api/grails/web/JSONBuilder.html" class="api">grails.web.JSONBuilder</a> class is used. This section covers the usage of the Grails 1.2 JSONBuilder<p class="paragraph"/>For backwards compatibility the old <code>JSONBuilder</code> class is used with the <code>render</code> method for older applications; to use the newer/better <code>JSONBuilder</code> class set the following in <code>Config.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.json.legacy.builder = <span class="java-keyword">false</span></pre></div><p class="paragraph"/><h4>Rendering Simple Objects</h4><p class="paragraph"/>To render a simple JSON object just set properties within the context of the Closure:<p class="paragraph"/><div class="code"><pre>render(contentType: <span class="java-quote">"application/json"</span>) { |
| hello = <span class="java-quote">"world"</span> |
| }</pre></div><p class="paragraph"/>The above will produce the JSON:<p class="paragraph"/><div class="code"><pre>{<span class="java-quote">"hello"</span>:<span class="java-quote">"world"</span>}</pre></div><p class="paragraph"/><h4>Rendering JSON Arrays</h4><p class="paragraph"/>To render a list of objects simple assign a list:<p class="paragraph"/><div class="code"><pre>render(contentType: <span class="java-quote">"application/json"</span>) { |
| categories = ['a', 'b', 'c'] |
| }</pre></div><p class="paragraph"/>This will produce:<p class="paragraph"/><div class="code"><pre>{<span class="java-quote">"categories"</span>:[<span class="java-quote">"a"</span>,<span class="java-quote">"b"</span>,<span class="java-quote">"c"</span>]}</pre></div><p class="paragraph"/>You can also render lists of complex objects, for example:<p class="paragraph"/><div class="code"><pre>render(contentType: <span class="java-quote">"application/json"</span>) { |
| categories = [ { a = <span class="java-quote">"A"</span> }, { b = <span class="java-quote">"B"</span> } ] |
| }</pre></div><p class="paragraph"/>This will produce:<p class="paragraph"/><div class="code"><pre>{<span class="java-quote">"categories"</span>:[ {<span class="java-quote">"a"</span>:<span class="java-quote">"A"</span>} , {<span class="java-quote">"b"</span>:<span class="java-quote">"B"</span>}] }</pre></div><p class="paragraph"/>Use the special <code>element</code> method to return a list as the root:<p class="paragraph"/><div class="code"><pre>render(contentType: <span class="java-quote">"application/json"</span>) { |
| element 1 |
| element 2 |
| element 3 |
| }</pre></div><p class="paragraph"/>The above code produces:<p class="paragraph"/><div class="code"><pre>[1,2,3]</pre></div><p class="paragraph"/><h4>Rendering Complex Objects</h4><p class="paragraph"/>Rendering complex objects can be done with Closures. For example:<p class="paragraph"/><div class="code"><pre>render(contentType: <span class="java-quote">"application/json"</span>) { |
| categories = ['a', 'b', 'c'] |
| title = <span class="java-quote">"Hello JSON"</span> |
| information = { |
| pages = 10 |
| } |
| }</pre></div><p class="paragraph"/>The above will produce the JSON:<p class="paragraph"/><div class="code"><pre>{<span class="java-quote">"categories"</span>:[<span class="java-quote">"a"</span>,<span class="java-quote">"b"</span>,<span class="java-quote">"c"</span>],<span class="java-quote">"title"</span>:<span class="java-quote">"Hello JSON"</span>,<span class="java-quote">"information"</span>:{<span class="java-quote">"pages"</span>:10}}</pre></div><p class="paragraph"/><h4>Arrays of Complex Objects</h4><p class="paragraph"/>As mentioned previously you can nest complex objects within arrays using Closures:<p class="paragraph"/><div class="code"><pre>render(contentType: <span class="java-quote">"application/json"</span>) { |
| categories = [ { a = <span class="java-quote">"A"</span> }, { b = <span class="java-quote">"B"</span> } ] |
| }</pre></div><p class="paragraph"/>You can use the <code>array</code> method to build them up dynamically:<p class="paragraph"/><div class="code"><pre>def results = Book.list() |
| render(contentType: <span class="java-quote">"application/json"</span>) { |
| books = array { |
| <span class="java-keyword">for</span> (b in results) { |
| book title: b.title |
| } |
| } |
| }</pre></div><p class="paragraph"/><h4>Direct JSONBuilder API Access</h4><p class="paragraph"/>If you don't have access to the <code>render</code> method, but still want to produce JSON you can use the API directly:<p class="paragraph"/><div class="code"><pre>def builder = <span class="java-keyword">new</span> JSONBuilder()<p class="paragraph"/>def result = builder.build { |
| categories = ['a', 'b', 'c'] |
| title = <span class="java-quote">"Hello JSON"</span> |
| information = { |
| pages = 10 |
| } |
| }<p class="paragraph"/>// prints the JSON text |
| println result.toString()<p class="paragraph"/>def sw = <span class="java-keyword">new</span> StringWriter() |
| result.render sw</pre></div> |
| |
| |
| <a name="7.1.9 Uploading Files"><!-- Legacy link --></a> |
| <h2 id="uploadingFiles">7.1.9 Uploading Files</h2> |
| <h4>Programmatic File Uploads</h4><p class="paragraph"/>Grails supports file uploads using Spring's <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/web/multipart/MultipartHttpServletRequest.html" class="api">MultipartHttpServletRequest</a> interface. The first step for file uploading is to create a multipart form like this:<p class="paragraph"/><div class="code"><pre>Upload Form: <span class="xml-tag"><br /></span> |
| <span class="xml-tag"><g:uploadForm action=<span class="xml-quote">"upload"</span>></span> |
| <span class="xml-tag"><input type=<span class="xml-quote">"file"</span> name=<span class="xml-quote">"myFile"</span> /></span> |
| <span class="xml-tag"><input type=<span class="xml-quote">"submit"</span> /></span> |
| <span class="xml-tag"></g:uploadForm></span></pre></div><p class="paragraph"/>The <code>uploadForm</code> tag conveniently adds the <code>enctype="multipart/form-data"</code> attribute to the standard <code><g:form></code> tag.<p class="paragraph"/>There are then a number of ways to handle the file upload. One is to work with the Spring <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/web/multipart/MultipartFile.html" class="api">MultipartFile</a> instance directly:<p class="paragraph"/><div class="code"><pre>def upload() { |
| def f = request.getFile('myFile') |
| <span class="java-keyword">if</span> (f.empty) { |
| flash.message = 'file cannot be empty' |
| render(view: 'uploadForm') |
| <span class="java-keyword">return</span> |
| }<p class="paragraph"/> f.transferTo(<span class="java-keyword">new</span> File('/some/local/dir/myfile.txt')) |
| response.sendError(200, 'Done') |
| }</pre></div><p class="paragraph"/>This is convenient for doing transfers to other destinations and manipulating the file directly as you can obtain an <code>InputStream</code> and so on with the <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/web/multipart/MultipartFile.html" class="api">MultipartFile</a> interface.<p class="paragraph"/><h4>File Uploads through Data Binding</h4><p class="paragraph"/>File uploads can also be performed using data binding. Consider this <code>Image</code> domain class:<p class="paragraph"/><div class="code"><pre>class Image { |
| <span class="java-object">byte</span>[] myFile<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| // Limit upload file size to 2MB |
| myFile maxSize: 1024 * 1024 * 2 |
| } |
| }</pre></div><p class="paragraph"/>If you create an image using the <code>params</code> object in the constructor as in the example below, Grails will automatically bind the file's contents as a <code>byte</code> to the <code>myFile</code> property:<p class="paragraph"/><div class="code"><pre>def img = <span class="java-keyword">new</span> Image(params)</pre></div><p class="paragraph"/>It's important that you set the <a href="../ref/Constraints/size.html" class="constraints">size</a> or <a href="../ref/Constraints/maxSize.html" class="constraints">maxSize</a> constraints, otherwise your database may be created with a small column size that can't handle reasonably sized files. For example, both H2 and MySQL default to a blob size of 255 bytes for <code>byte</code> properties.<p class="paragraph"/>It is also possible to set the contents of the file as a string by changing the type of the <code>myFile</code> property on the image to a String type:<p class="paragraph"/><div class="code"><pre>class Image { |
| <span class="java-object">String</span> myFile |
| }</pre></div> |
| |
| |
| <a name="7.1.10 Command Objects"><!-- Legacy link --></a> |
| <h2 id="commandObjects">7.1.10 Command Objects</h2> |
| Grails controllers support the concept of command objects. A command object is a class that is used in conjunction with <a href="../guide/single.html#dataBinding" class="guide">data binding</a>, usually to allow validation of data that may not fit into an existing domain class.<p class="paragraph"/><blockquote class="note"> |
| Note: A class is only considered to be a command object when it is used as a parameter of an action. |
| </blockquote><p class="paragraph"/><h4>Declaring Command Objects</h4><p class="paragraph"/>Command object classes are defined just like any other class.<p class="paragraph"/><div class="code"><pre>class LoginCommand <span class="java-keyword">implements</span> grails.validation.Validateable { |
| <span class="java-object">String</span> username |
| <span class="java-object">String</span> password<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| username(blank: <span class="java-keyword">false</span>, minSize: 6) |
| password(blank: <span class="java-keyword">false</span>, minSize: 6) |
| } |
| }</pre></div><p class="paragraph"/>In this example, the command object class implements the <code>Validateable</code> trait. The <code>Validateable</code> trait allows the definition of <a href="../guide/single.html#constraints" class="guide">constraints</a> just like in <a href="../guide/single.html#GORM" class="guide">domain classes</a>. If the command object is defined in the same source file as the controller that is using it, Grails will automatically make it <code>Validateable</code>. It is not required that command object classes be validateable.<p class="paragraph"/>By default, all <code>Validateable</code> object properties are <code>nullable: false</code> which matches the behavior of GORM domain objects. If you want a <code>Validateable</code> that has <code>nullable: true</code> properties by default, you can specify this by defining a <code>defaultNullable</code> method in the class:<p class="paragraph"/><div class="code"><pre>class AuthorSearchCommand <span class="java-keyword">implements</span> grails.validation.Validateable { |
| <span class="java-object">String</span> name |
| <span class="java-object">Integer</span> age<p class="paragraph"/> <span class="java-keyword">static</span> <span class="java-object">boolean</span> defaultNullable() { |
| <span class="java-keyword">true</span> |
| } |
| }</pre></div><p class="paragraph"/>In this example, both <code>name</code> and <code>age</code> will allow null values during validation.<p class="paragraph"/><h4>Using Command Objects</h4><p class="paragraph"/>To use command objects, controller actions may optionally specify any number of command object parameters. The parameter types must be supplied so that Grails knows what objects to create and initialize.<p class="paragraph"/>Before the controller action is executed Grails will automatically create an instance of the command object class and populate its properties by binding the request parameters. If the command object class is marked with <code>Validateable</code> then the command object will be validated. For example:<p class="paragraph"/><div class="code"><pre>class LoginController {<p class="paragraph"/> def login(LoginCommand cmd) { |
| <span class="java-keyword">if</span> (cmd.hasErrors()) { |
| redirect(action: 'loginForm') |
| <span class="java-keyword">return</span> |
| }<p class="paragraph"/> // work with the command object data |
| } |
| }</pre></div><p class="paragraph"/>If the command object's type is that of a domain class and there is an <code>id</code> request parameter then instead of invoking the domain class constructor to create a new instance a call will be made to the static <code>get</code> method on the domain class and the value of the <code>id</code> parameter will be passed as an argument. Whatever is returned from that call to <code>get</code> is what will be passed into the controller action. This means that if there is an <code>id</code> request parameter and no corresponding record is found in the database then the value of the command object will be <code>null</code>. If an error occurs retrieving the instance from the database then <code>null</code> will be passed as an argument to the controller action and an error will be added the controller's <code>errors</code> property. If the command object's type is a domain class and there is no <code>id</code> request parameter or there is an <code>id</code> request parameter and its value is empty then <code>null</code> will be passed into the controller action unless the HTTP request method is "POST", in which case a new instance of the domain class will be created by invoking the domain class constructor. For all of the cases where the domain class instance is non-null, data binding is only performed if the HTTP request method is "POST", "PUT" or "PATCH".<p class="paragraph"/><h4>Command Objects And Request Parameter Names</h4><p class="paragraph"/>Normally request parameter names will be mapped directly to property names in the command object. Nested parameter names may be used to bind down the object graph in an intuitive way. In the example below a request parameter named <code>name</code> will be bound to the <code>name</code> property of the <code>Person</code> instance and a request parameter named <code>address.city</code> will be bound to the <code>city</code> property of the <code>address</code> property in the <code>Person</code>.<p class="paragraph"/><div class="code"><pre>class StoreController { |
| def buy(Person buyer) { |
| // … |
| } |
| }<p class="paragraph"/>class Person { |
| <span class="java-object">String</span> name |
| Address address |
| }<p class="paragraph"/>class Address { |
| <span class="java-object">String</span> city |
| }</pre></div><p class="paragraph"/>A problem may arise if a controller action accepts multiple command objects which happen to contain the same property name. Consider the following example.<p class="paragraph"/><div class="code"><pre>class StoreController { |
| def buy(Person buyer, Product product) { |
| // … |
| } |
| }<p class="paragraph"/>class Person { |
| <span class="java-object">String</span> name |
| Address address |
| }<p class="paragraph"/>class Address { |
| <span class="java-object">String</span> city |
| }<p class="paragraph"/>class Product { |
| <span class="java-object">String</span> name |
| }</pre></div><p class="paragraph"/>If there is a request parameter named <code>name</code> it isn't clear if that should represent the name of the <code>Product</code> or the name of the <code>Person</code>. Another version of the problem can come up if a controller action accepts 2 command objects of the same type as shown below.<p class="paragraph"/><div class="code"><pre>class StoreController { |
| def buy(Person buyer, Person seller, Product product) { |
| // … |
| } |
| }<p class="paragraph"/>class Person { |
| <span class="java-object">String</span> name |
| Address address |
| }<p class="paragraph"/>class Address { |
| <span class="java-object">String</span> city |
| }<p class="paragraph"/>class Product { |
| <span class="java-object">String</span> name |
| }</pre></div><p class="paragraph"/>To help deal with this the framework imposes special rules for mapping parameter names to command object types. The command object data binding will treat all parameters that begin with the controller action parameter name as belonging to the corresponding command object. For example, the <code>product.name</code> request parameter will be bound to the <code>name</code> property in the <code>product</code> argument, the <code>buyer.name</code> request parameter will be bound to the <code>name</code> property in the <code>buyer</code> argument the <code>seller.address.city</code> request parameter will be bound to the <code>city</code> property of the <code>address</code> property of the <code>seller</code> argument, etc...<p class="paragraph"/><h4>Command Objects and Dependency Injection</h4><p class="paragraph"/>Command objects can participate in dependency injection. This is useful if your command object has some custom validation logic which uses a Grails <a href="../guide/single.html#services" class="guide">service</a>:<p class="paragraph"/><div class="code"><pre>class LoginCommand <span class="java-keyword">implements</span> grails.validation.Validateable {<p class="paragraph"/> def loginService<p class="paragraph"/> <span class="java-object">String</span> username |
| <span class="java-object">String</span> password<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| username validator: { val, obj -> |
| obj.loginService.canLogin(obj.username, obj.password) |
| } |
| } |
| }</pre></div><p class="paragraph"/>In this example the command object interacts with the <code>loginService</code> bean which is injected by name from the Spring <code>ApplicationContext</code>.<p class="paragraph"/><h4>Binding The Request Body To Command Objects</h4><p class="paragraph"/>When a request is made to a controller action which accepts a command object and the request contains a body, Grails will attempt to parse the body of the request based on the request content type and use the body to do data binding on the command object. See the following example.<p class="paragraph"/><div class="code"><pre>// grails-app/controllers/bindingdemo/DemoController.groovy |
| <span class="java-keyword">package</span> bindingdemo<p class="paragraph"/>class DemoController {<p class="paragraph"/> def createWidget(Widget w) { |
| render <span class="java-quote">"Name: ${w?.name}, Size: ${w?.size}"</span> |
| } |
| }<p class="paragraph"/>class Widget { |
| <span class="java-object">String</span> name |
| <span class="java-object">Integer</span> size |
| }</pre></div><p class="paragraph"/><div class="code"><pre>$ curl -H <span class="java-quote">"Content-Type: application/json"</span> -d '{<span class="java-quote">"name"</span>:<span class="java-quote">"Some Widget"</span>,<span class="java-quote">"size"</span>:<span class="java-quote">"42"</span>}' localhost:8080/myapp/demo/createWidget |
| Name: Some Widget, Size: 42 |
| ~ $ |
| $ curl -H <span class="java-quote">"Content-Type: application/xml"</span> -d '<widget><name>Some Other Widget</name><size>2112</size></widget>' localhost:8080/bodybind/demo/createWidget |
| Name: Some Other Widget, Size: 2112 |
| ~ $</pre></div><p class="paragraph"/>Note that the body of the request is being parsed to make that work. Any attempt to read the body of the request after that will fail since the corresponding input stream will be empty. The controller action can either use a command object or it can parse the body of the request on its own (either directly, or by referring to something like request.JSON), but cannot do both.<p class="paragraph"/><div class="code"><pre>// grails-app/controllers/bindingdemo/DemoController.groovy |
| <span class="java-keyword">package</span> bindingdemo<p class="paragraph"/>class DemoController {<p class="paragraph"/> def createWidget(Widget w) { |
| // <span class="java-keyword">this</span> will fail because it requires reading the body, |
| // which has already been read. |
| def json = request.JSON<p class="paragraph"/> // ...<p class="paragraph"/> } |
| }</pre></div> |
| |
| |
| <a name="7.1.11 Handling Duplicate Form Submissions"><!-- Legacy link --></a> |
| <h2 id="formtokens">7.1.11 Handling Duplicate Form Submissions</h2> |
| Grails has built-in support for handling duplicate form submissions using the "Synchronizer Token Pattern". To get started you define a token on the <a href="../ref/Tags/form.html" class="tags">form</a> tag:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:form useToken=<span class="xml-quote">"true"</span> ...></span></pre></div><p class="paragraph"/>Then in your controller code you can use the <a href="../ref/Controllers/withForm.html" class="controllers">withForm</a> method to handle valid and invalid requests:<p class="paragraph"/><div class="code"><pre>withForm { |
| // good request |
| }.invalidToken { |
| // bad request |
| }</pre></div><p class="paragraph"/>If you only provide the <a href="../ref/Controllers/withForm.html" class="controllers">withForm</a> method and not the chained <code>invalidToken</code> method then by default Grails will store the invalid token in a <code>flash.invalidToken</code> variable and redirect the request back to the original page. This can then be checked in the view:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:if test=<span class="xml-quote">"${flash.invalidToken}"</span>></span> |
| Don't click the button twice! |
| <span class="xml-tag"></g:if></span></pre></div><p class="paragraph"/><blockquote class="warning"> |
| The <a href="../ref/Controllers/withForm.html" class="controllers">withForm</a> tag makes use of the <a href="../ref/Controllers/session.html" class="controllers">session</a> and hence requires session affinity or clustered sessions if used in a cluster. |
| </blockquote> |
| |
| |
| <a name="7.1.12 Simple Type Converters"><!-- Legacy link --></a> |
| <h2 id="typeConverters">7.1.12 Simple Type Converters</h2> |
| <h3>Type Conversion Methods</h3><p class="paragraph"/>If you prefer to avoid the overhead of <a href="../guide/single.html#dataBinding" class="guide">Data Binding</a> and simply want to convert incoming parameters (typically Strings) into another more appropriate type the <a href="../ref/Controllers/params.html" class="controllers">params</a> object has a number of convenience methods for each type:<p class="paragraph"/><div class="code"><pre>def total = params.<span class="java-object">int</span>('total')</pre></div><p class="paragraph"/>The above example uses the <code>int</code> method, and there are also methods for <code>boolean</code>, <code>long</code>, <code>char</code>, <code>short</code> and so on. Each of these methods is null-safe and safe from any parsing errors, so you don't have to perform any additional checks on the parameters.<p class="paragraph"/>Each of the conversion methods allows a default value to be passed as an optional second argument. The default value will be returned if a corresponding entry cannot be found in the map or if an error occurs during the conversion. Example:<p class="paragraph"/><div class="code"><pre>def total = params.<span class="java-object">int</span>('total', 42)</pre></div><p class="paragraph"/>These same type conversion methods are also available on the <code>attrs</code> parameter of GSP tags.<p class="paragraph"/><h3>Handling Multi Parameters</h3><p class="paragraph"/>A common use case is dealing with multiple request parameters of the same name. For example you could get a query string such as <code>?name=Bob&name=Judy</code>.<p class="paragraph"/>In this case dealing with one parameter and dealing with many has different semantics since Groovy's iteration mechanics for <code>String</code> iterate over each character. To avoid this problem the <a href="../ref/Controllers/params.html" class="controllers">params</a> object provides a <code>list</code> method that always returns a list:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">for</span> (name in params.list('name')) { |
| println name |
| }</pre></div> |
| |
| |
| |
| <h2 id="controllerExceptionHandling">7.1.13 Declarative Controller Exception Handling</h2> |
| Grails controllers support a simple mechanism for declarative exception handling. If a controller declares a method that accepts a single argument and the argument type is <code>java.lang.Exception</code> or some subclass of <code>java.lang.Exception</code>, that method will be invoked any time an action in that controller throws an exception of that type. See the following example.<p class="paragraph"/><div class="code"><pre>// grails-app/controllers/demo/DemoController.groovy |
| <span class="java-keyword">package</span> demo<p class="paragraph"/>class DemoController {<p class="paragraph"/> def someAction() { |
| // <span class="java-keyword">do</span> some work |
| }<p class="paragraph"/> def handleSQLException(SQLException e) { |
| render 'A SQLException Was Handled' |
| }<p class="paragraph"/> def handleBatchUpdateException(BatchUpdateException e) { |
| redirect controller: 'logging', action: 'batchProblem' |
| }<p class="paragraph"/> def handleNumberFormatException(NumberFormatException nfe) { |
| [problemDescription: 'A <span class="java-object">Number</span> Was Invalid'] |
| } |
| }</pre></div><p class="paragraph"/> |
| That controller will behave as if it were written something like this...<p class="paragraph"/> |
| <div class="code"><pre>// grails-app/controllers/demo/DemoController.groovy |
| <span class="java-keyword">package</span> demo<p class="paragraph"/>class DemoController {<p class="paragraph"/> def someAction() { |
| <span class="java-keyword">try</span> { |
| // <span class="java-keyword">do</span> some work |
| } <span class="java-keyword">catch</span> (BatchUpdateException e) { |
| <span class="java-keyword">return</span> handleBatchUpdateException(e) |
| } <span class="java-keyword">catch</span> (SQLException e) { |
| <span class="java-keyword">return</span> handleSQLException(e) |
| } <span class="java-keyword">catch</span> (NumberFormatException e) { |
| <span class="java-keyword">return</span> handleNumberFormatException(e) |
| } |
| }<p class="paragraph"/> def handleSQLException(SQLException e) { |
| render 'A SQLException Was Handled' |
| }<p class="paragraph"/> def handleBatchUpdateException(BatchUpdateException e) { |
| redirect controller: 'logging', action: 'batchProblem' |
| }<p class="paragraph"/> def handleNumberFormatException(NumberFormatException nfe) { |
| [problemDescription: 'A <span class="java-object">Number</span> Was Invalid'] |
| } |
| }</pre></div><p class="paragraph"/>The exception handler method names can be any valid method name. The name is not what makes the method an exception handler, the <code>Exception</code> argument type is the important part.<p class="paragraph"/>The exception handler methods can do anything that a controller action can do including invoking <code>render</code>, <code>redirect</code>, returning a model, etc.<p class="paragraph"/>One way to share exception handler methods across multiple controllers is to use inheritance. Exception handler methods are inherited into subclasses so an application could define the exception handlers in an abstract class that multiple controllers extend from. Another way to share exception handler methods across multiple controllers is to use a trait, as shown below...<p class="paragraph"/><div class="code"><pre>// src/groovy/com/demo/DatabaseExceptionHandler.groovy |
| <span class="java-keyword">package</span> com.demo<p class="paragraph"/>trait DatabaseExceptionHandler { |
| def handleSQLException(SQLException e) { |
| // handle SQLException |
| }<p class="paragraph"/> def handleBatchUpdateException(BatchUpdateException e) { |
| // handle BatchUpdateException |
| } |
| }</pre></div><p class="paragraph"/><div class="code"><pre>// grails-app/controllers/com/demo/DemoController.groovy |
| <span class="java-keyword">package</span> com.demo<p class="paragraph"/>class DemoController <span class="java-keyword">implements</span> DatabaseExceptionHandler {<p class="paragraph"/> // all of the exception handler methods defined |
| // in DatabaseExceptionHandler will be added to |
| // <span class="java-keyword">this</span> class at compile time |
| }</pre></div><p class="paragraph"/>Exception handler methods must be present at compile time. Specifically, exception handler methods which are runtime metaprogrammed onto a controller class are not supported. |
| |
| |
| <a name="7.2 Groovy Server Pages"><!-- Legacy link --></a> |
| <h2 id="gsp">7.2 Groovy Server Pages</h2> |
| Groovy Servers Pages (or GSP for short) is Grails' view technology. It is designed to be familiar for users of technologies such as ASP and JSP, but to be far more flexible and intuitive.<p class="paragraph"/>GSPs live in the <code>grails-app/views</code> directory and are typically rendered automatically (by convention) or with the <a href="../ref/Controllers/render.html" class="controllers">render</a> method such as:<p class="paragraph"/><div class="code"><pre>render(view: <span class="java-quote">"index"</span>)</pre></div><p class="paragraph"/>A GSP is typically a mix of mark-up and GSP tags which aid in view rendering.<p class="paragraph"/><blockquote class="note"> |
| Although it is possible to have Groovy logic embedded in your GSP and doing this will be covered in this document, the practice is strongly discouraged. Mixing mark-up and code is a <strong class="bold">bad</strong> thing and most GSP pages contain no code and needn't do so. |
| </blockquote><p class="paragraph"/>A GSP typically has a "model" which is a set of variables that are used for view rendering. The model is passed to the GSP view from a controller. For example consider the following controller action:<p class="paragraph"/><div class="code"><pre>def show() { |
| [book: Book.get(params.id)] |
| }</pre></div><p class="paragraph"/>This action will look up a <code>Book</code> instance and create a model that contains a key called <code>book</code>. This key can then be referenced within the GSP view using the name <code>book</code>:<p class="paragraph"/><div class="code"><pre>${book.title}</pre></div><p class="paragraph"/><blockquote class="warning"> |
| Embedding data received from user input has the risk of making your application vulnerable to an Cross Site Scripting (XSS) attack. Please read the documentation on <a href="../guide/single.html#xssPrevention" class="guide">XSS prevention</a> for information on how to prevent XSS attacks. |
| </blockquote> |
| |
| |
| <a name="7.2.1 GSP Basics"><!-- Legacy link --></a> |
| <h2 id="GSPBasics">7.2.1 GSP Basics</h2> |
| In the next view sections we'll go through the basics of GSP and what is available to you. First off let's cover some basic syntax that users of JSP and ASP should be familiar with.<p class="paragraph"/>GSP supports the usage of <code><% %></code> scriptlet blocks to embed Groovy code (again this is discouraged):<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><html></span> |
| <span class="xml-tag"><body></span> |
| <span class="xml-tag"><% out << <span class="xml-quote">"Hello GSP!"</span> %></span> |
| <span class="xml-tag"></body></span> |
| <span class="xml-tag"></html></span></pre></div><p class="paragraph"/>You can also use the <code><%= %></code> syntax to output values:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><html></span> |
| <span class="xml-tag"><body></span> |
| <span class="xml-tag"><%=<span class="xml-quote">"Hello GSP!"</span> %></span> |
| <span class="xml-tag"></body></span> |
| <span class="xml-tag"></html></span></pre></div><p class="paragraph"/>GSP also supports JSP-style server-side comments (which are not rendered in the HTML response) as the following example demonstrates:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><html></span> |
| <span class="xml-tag"><body></span> |
| <span class="xml-tag"><%-- This is my comment --%></span> |
| <span class="xml-tag"><%=<span class="xml-quote">"Hello GSP!"</span> %></span> |
| <span class="xml-tag"></body></span> |
| <span class="xml-tag"></html></span></pre></div><p class="paragraph"/><blockquote class="warning"> |
| Embedding data received from user input has the risk of making your application vulnerable to an Cross Site Scripting (XSS) attack. Please read the documentation on <a href="../guide/single.html#xssPrevention" class="guide">XSS prevention</a> for information on how to prevent XSS attacks. |
| </blockquote> |
| |
| |
| <a name="6.6.3 Variables and Scopes"><!-- Legacy link --></a> |
| <h2 id="variablesAndScopes">7.2.1.1 Variables and Scopes</h2> |
| Within the <code><% %></code> brackets you can declare variables:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><% now = new Date() %></span></pre></div><p class="paragraph"/>and then access those variables later in the page:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><%=now%></span></pre></div><p class="paragraph"/>Within the scope of a GSP there are a number of pre-defined variables, including: |
| <ul class="star"> |
| <li><code>application</code> - The <a href="http://download.oracle.com/javaee/1.4/api/javax/servlet/ServletContext.html" class="api">javax.servlet.ServletContext</a> instance</li> |
| <li><code>applicationContext</code> The Spring <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/context/ApplicationContext.html" class="api">ApplicationContext</a> instance</li> |
| <li><code>flash</code> - The <a href="../ref/Controllers/flash.html" class="controllers">flash</a> object</li> |
| <li><code>grailsApplication</code> - The <a href="http://grails.org/doc/3.0.x/api/grails/core/GrailsApplication.html" class="api">GrailsApplication</a> instance</li> |
| <li><code>out</code> - The response writer for writing to the output stream</li> |
| <li><code>params</code> - The <a href="../ref/Controllers/params.html" class="controllers">params</a> object for retrieving request parameters</li> |
| <li><code>request</code> - The <a href="http://download.oracle.com/javaee/1.4/api/javax/servlet/http/HttpServletRequest.html" class="api">HttpServletRequest</a> instance</li> |
| <li><code>response</code> - The <a href="http://download.oracle.com/javaee/1.4/api/javax/servlet/http/HttpServletResponse.html" class="api">HttpServletResponse</a> instance</li> |
| <li><code>session</code> - The <a href="http://download.oracle.com/javaee/1.4/api/javax/servlet/http/HttpSession.html" class="api">HttpSession</a> instance</li> |
| <li><code>webRequest</code> - The <a href="http://grails.org/doc/3.0.x/api/org/grails/web/servlet/mvc/GrailsWebRequest.html" class="api">GrailsWebRequest</a> instance</li> |
| </ul><p class="paragraph"/> |
| |
| <a name="7.2.2.2 Logic and Iteration"><!-- Legacy link --></a> |
| <h2 id="logicAndIteration">7.2.1.2 Logic and Iteration</h2> |
| Using the <code><% %></code> syntax you can embed loops and so on using this syntax:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><html></span> |
| <span class="xml-tag"><body></span> |
| <span class="xml-tag"><% [1,2,3,4].each { num -></span> %> |
| <span class="xml-tag"><p></span><span class="xml-tag"><%=<span class="xml-quote">"Hello ${num}!"</span> %></span><span class="xml-tag"></p></span> |
| <span class="xml-tag"><%}%></span> |
| <span class="xml-tag"></body></span> |
| <span class="xml-tag"></html></span></pre></div><p class="paragraph"/>As well as logical branching:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><html></span> |
| <span class="xml-tag"><body></span> |
| <span class="xml-tag"><% if (params.hello == 'true')%></span> |
| <span class="xml-tag"><%=<span class="xml-quote">"Hello!"</span>%></span> |
| <span class="xml-tag"><% else %></span> |
| <span class="xml-tag"><%=<span class="xml-quote">"Goodbye!"</span>%></span> |
| <span class="xml-tag"></body></span> |
| <span class="xml-tag"></html></span></pre></div> |
| |
| |
| <a name="7.2.1.3 Page Directives"><!-- Legacy link --></a> |
| <h2 id="pageDirectives">7.2.1.3 Page Directives</h2> |
| GSP also supports a few JSP-style page directives.<p class="paragraph"/>The import directive lets you import classes into the page. However, it is rarely needed due to Groovy's default imports and <a href="../guide/single.html#tags" class="guide">GSP Tags</a>:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><%@ page import=<span class="xml-quote">"java.awt.*"</span> %></span></pre></div><p class="paragraph"/>GSP also supports the contentType directive:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><%@ page contentType=<span class="xml-quote">"application/json"</span> %></span></pre></div><p class="paragraph"/>The contentType directive allows using GSP to render other formats. |
| |
| |
| <a name="7.2.1.4 Expressions"><!-- Legacy link --></a> |
| <h2 id="expressions">7.2.1.4 Expressions</h2> |
| In GSP the <code><%= %></code> syntax introduced earlier is rarely used due to the support for GSP expressions. A GSP expression is similar to a JSP EL expression or a Groovy GString and takes the form <code>${expr}</code>:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><html></span> |
| <span class="xml-tag"><body></span> |
| Hello ${params.name} |
| <span class="xml-tag"></body></span> |
| <span class="xml-tag"></html></span></pre></div><p class="paragraph"/>However, unlike JSP EL you can have any Groovy expression within the <code>${..}</code> block.<p class="paragraph"/><blockquote class="warning"> |
| Embedding data received from user input has the risk of making your application vulnerable to an Cross Site Scripting (XSS) attack. Please read the documentation on <a href="../guide/single.html#xssPrevention" class="guide">XSS prevention</a> for information on how to prevent XSS attacks. |
| </blockquote> |
| |
| |
| <a name="7.2.2 GSP Tags"><!-- Legacy link --></a> |
| <h2 id="tags">7.2.2 GSP Tags</h2> |
| Now that the less attractive JSP heritage has been set aside, the following sections cover GSP's built-in tags, which are the preferred way to define GSP pages.<p class="paragraph"/><blockquote class="note"> |
| The section on <a href="../guide/single.html#taglibs" class="guide">Tag Libraries</a> covers how to add your own custom tag libraries. |
| </blockquote><p class="paragraph"/>All built-in GSP tags start with the prefix <code>g:</code>. Unlike JSP, you don't specify any tag library imports. If a tag starts with <code>g:</code> it is automatically assumed to be a GSP tag. An example GSP tag would look like:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:example /></span></pre></div><p class="paragraph"/>GSP tags can also have a body such as:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:example></span> |
| Hello world |
| <span class="xml-tag"></g:example></span></pre></div><p class="paragraph"/>Expressions can be passed into GSP tag attributes, if an expression is not used it will be assumed to be a String value:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:example attr=<span class="xml-quote">"${new Date()}"</span>></span> |
| Hello world |
| <span class="xml-tag"></g:example></span></pre></div><p class="paragraph"/>Maps can also be passed into GSP tag attributes, which are often used for a named parameter style syntax:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:example attr=<span class="xml-quote">"${new Date()}"</span> attr2=<span class="xml-quote">"[one:1, two:2, three:3]"</span>></span> |
| Hello world |
| <span class="xml-tag"></g:example></span></pre></div><p class="paragraph"/>Note that within the values of attributes you must use single quotes for Strings:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:example attr=<span class="xml-quote">"${new Date()}"</span> attr2=<span class="xml-quote">"[one:'one', two:'two']"</span>></span> |
| Hello world |
| <span class="xml-tag"></g:example></span></pre></div><p class="paragraph"/>With the basic syntax out the way, the next sections look at the tags that are built into Grails by default. |
| |
| |
| |
| <h2 id="tagVariablesAndScopes">7.2.2.1 Variables and Scopes</h2> |
| Variables can be defined within a GSP using the <a href="../ref/Tags/set.html" class="tags">set</a> tag:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:set var=<span class="xml-quote">"now"</span> value=<span class="xml-quote">"${new Date()}"</span> /></span></pre></div><p class="paragraph"/>Here we assign a variable called <code>now</code> to the result of a GSP expression (which simply constructs a new <code>java.util.Date</code> instance). You can also use the body of the <code><g:set></code> tag to define a variable:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:set var=<span class="xml-quote">"myHTML"</span>></span> |
| Some re-usable code on: ${new Date()} |
| <span class="xml-tag"></g:set></span></pre></div><p class="paragraph"/>The assigned value can also be a bean from the applicationContext:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:set var=<span class="xml-quote">"bookService"</span> bean=<span class="xml-quote">"bookService"</span> /></span></pre></div><p class="paragraph"/>Variables can also be placed in one of the following scopes: |
| <ul class="star"> |
| <li><code>page</code> - Scoped to the current page (default)</li> |
| <li><code>request</code> - Scoped to the current request</li> |
| <li><code>flash</code> - Placed within <a href="../ref/Controllers/flash.html" class="controllers">flash</a> scope and hence available for the next request</li> |
| <li><code>session</code> - Scoped for the user session</li> |
| <li><code>application</code> - Application-wide scope.</li> |
| </ul><p class="paragraph"/>To specify the scope, use the <code>scope</code> attribute:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:set var=<span class="xml-quote">"now"</span> value=<span class="xml-quote">"${new Date()}"</span> scope=<span class="xml-quote">"request"</span> /></span></pre></div> |
| |
| |
| |
| <h2 id="tagLogicAndIteration">7.2.2.2 Logic and Iteration</h2> |
| GSP also supports logical and iterative tags out of the box. For logic there are <a href="../ref/Tags/if.html" class="tags">if</a>, <a href="../ref/Tags/else.html" class="tags">else</a> and <a href="../ref/Tags/elseif.html" class="tags">elseif</a> tags for use with branching:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:if test=<span class="xml-quote">"${session.role == 'admin'}"</span>></span> |
| <span class="xml-tag"><%-- show administrative functions --%></span> |
| <span class="xml-tag"></g:if></span> |
| <span class="xml-tag"><g:else></span> |
| <span class="xml-tag"><%-- show basic functions --%></span> |
| <span class="xml-tag"></g:else></span></pre></div><p class="paragraph"/>Use the <a href="../ref/Tags/each.html" class="tags">each</a> and <a href="../ref/Tags/while.html" class="tags">while</a> tags for iteration:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:each in=<span class="xml-quote">"${[1,2,3]}"</span> var=<span class="xml-quote">"num"</span>></span> |
| <span class="xml-tag"><p></span>Number ${num}<span class="xml-tag"></p></span> |
| <span class="xml-tag"></g:each></span><p class="paragraph"/><span class="xml-tag"><g:set var=<span class="xml-quote">"num"</span> value=<span class="xml-quote">"${1}"</span> /></span> |
| <span class="xml-tag"><g:while test=<span class="xml-quote">"${num < 5 }"</span>></span> |
| <span class="xml-tag"><p></span>Number ${num++}<span class="xml-tag"></p></span> |
| <span class="xml-tag"></g:while></span></pre></div> |
| |
| |
| <a name="7.2.2.3 Search and Filtering"><!-- Legacy link --></a> |
| <h2 id="searchAndFiltering">7.2.2.3 Search and Filtering</h2> |
| If you have collections of objects you often need to sort and filter them. Use the <a href="../ref/Tags/findAll.html" class="tags">findAll</a> and <a href="../ref/Tags/grep.html" class="tags">grep</a> tags for these tasks:<p class="paragraph"/><div class="code"><pre>Stephen King's Books: |
| <span class="xml-tag"><g:findAll in=<span class="xml-quote">"${books}"</span> expr=<span class="xml-quote">"it.author == 'Stephen King'"</span>></span> |
| <span class="xml-tag"><p></span>Title: ${it.title}<span class="xml-tag"></p></span> |
| <span class="xml-tag"></g:findAll></span></pre></div><p class="paragraph"/>The <code>expr</code> attribute contains a Groovy expression that can be used as a filter. The <a href="../ref/Tags/grep.html" class="tags">grep</a> tag does a similar job, for example filtering by class:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:grep in=<span class="xml-quote">"${books}"</span> filter=<span class="xml-quote">"NonFictionBooks.class"</span>></span> |
| <span class="xml-tag"><p></span>Title: ${it.title}<span class="xml-tag"></p></span> |
| <span class="xml-tag"></g:grep></span></pre></div><p class="paragraph"/>Or using a regular expression:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:grep in=<span class="xml-quote">"${books.title}"</span> filter=<span class="xml-quote">"~/.*?Groovy.*?/"</span>></span> |
| <span class="xml-tag"><p></span>Title: ${it}<span class="xml-tag"></p></span> |
| <span class="xml-tag"></g:grep></span></pre></div><p class="paragraph"/>The above example is also interesting due to its usage of GPath. GPath is an XPath-like language in Groovy. The <code>books</code> variable is a collection of <code>Book</code> instances. Since each <code>Book</code> has a <code>title</code>, you can obtain a list of Book titles using the expression <code>books.title</code>. Groovy will auto-magically iterate the collection, obtain each title, and return a new list! |
| |
| |
| <a name="7.2.2.4 Links and Resources"><!-- Legacy link --></a> |
| <h2 id="linksAndResources">7.2.2.4 Links and Resources</h2> |
| GSP also features tags to help you manage linking to controllers and actions. The <a href="../ref/Tags/link.html" class="tags">link</a> tag lets you specify controller and action name pairing and it will automatically work out the link based on the <a href="../guide/single.html#urlmappings" class="guide">URL Mappings</a>, even if you change them! For example:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:link action=<span class="xml-quote">"show"</span> id=<span class="xml-quote">"1"</span>></span>Book 1<span class="xml-tag"></g:link></span><p class="paragraph"/><span class="xml-tag"><g:link action=<span class="xml-quote">"show"</span> id=<span class="xml-quote">"${currentBook.id}"</span>></span>${currentBook.name}<span class="xml-tag"></g:link></span><p class="paragraph"/><span class="xml-tag"><g:link controller=<span class="xml-quote">"book"</span>></span>Book Home<span class="xml-tag"></g:link></span><p class="paragraph"/><span class="xml-tag"><g:link controller=<span class="xml-quote">"book"</span> action=<span class="xml-quote">"list"</span>></span>Book List<span class="xml-tag"></g:link></span><p class="paragraph"/><span class="xml-tag"><g:link url=<span class="xml-quote">"[action: 'list', controller: 'book']"</span>></span>Book List<span class="xml-tag"></g:link></span><p class="paragraph"/><span class="xml-tag"><g:link params=<span class="xml-quote">"[sort: 'title', order: 'asc', author: currentBook.author]"</span> |
| action=<span class="xml-quote">"list"</span>></span>Book List<span class="xml-tag"></g:link></span></pre></div> |
| |
| |
| <a name="7.2.2.5 Forms and Fields"><!-- Legacy link --></a> |
| <h2 id="formsAndFields">7.2.2.5 Forms and Fields</h2> |
| <h4>Form Basics</h4><p class="paragraph"/>GSP supports many different tags for working with HTML forms and fields, the most basic of which is the <a href="../ref/Tags/form.html" class="tags">form</a> tag. This is a controller/action aware version of the regular HTML form tag. The <code>url</code> attribute lets you specify which controller and action to map to:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:form name=<span class="xml-quote">"myForm"</span> url=<span class="xml-quote">"[controller:'book',action:'list']"</span>></span>...<span class="xml-tag"></g:form></span></pre></div><p class="paragraph"/>In this case we create a form called <code>myForm</code> that submits to the <code>BookController</code>'s <code>list</code> action. Beyond that all of the usual HTML attributes apply.<p class="paragraph"/><h4>Form Fields</h4><p class="paragraph"/>In addition to easy construction of forms, GSP supports custom tags for dealing with different types of fields, including: |
| <ul class="star"> |
| <li><a href="../ref/Tags/textField.html" class="tags">textField</a> - For input fields of type 'text'</li> |
| <li><a href="../ref/Tags/passwordField.html" class="tags">passwordField</a> - For input fields of type 'password'</li> |
| <li><a href="../ref/Tags/checkBox.html" class="tags">checkBox</a> - For input fields of type 'checkbox'</li> |
| <li><a href="../ref/Tags/radio.html" class="tags">radio</a> - For input fields of type 'radio'</li> |
| <li><a href="../ref/Tags/hiddenField.html" class="tags">hiddenField</a> - For input fields of type 'hidden'</li> |
| <li><a href="../ref/Tags/select.html" class="tags">select</a> - For dealing with HTML select boxes</li> |
| </ul><p class="paragraph"/>Each of these allows GSP expressions for the value:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:textField name=<span class="xml-quote">"myField"</span> value=<span class="xml-quote">"${myValue}"</span> /></span></pre></div><p class="paragraph"/>GSP also contains extended helper versions of the above tags such as <a href="../ref/Tags/radioGroup.html" class="tags">radioGroup</a> (for creating groups of <a href="../ref/Tags/radio.html" class="tags">radio</a> tags), <a href="../ref/Tags/localeSelect.html" class="tags">localeSelect</a>, <a href="../ref/Tags/currencySelect.html" class="tags">currencySelect</a> and <a href="../ref/Tags/timeZoneSelect.html" class="tags">timeZoneSelect</a> (for selecting locales, currencies and time zones respectively).<p class="paragraph"/><h4>Multiple Submit Buttons</h4><p class="paragraph"/>The age old problem of dealing with multiple submit buttons is also handled elegantly with Grails using the <a href="../ref/Tags/actionSubmit.html" class="tags">actionSubmit</a> tag. It is just like a regular submit, but lets you specify an alternative action to submit to:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:actionSubmit value=<span class="xml-quote">"Some update label"</span> action=<span class="xml-quote">"update"</span> /></span></pre></div> |
| |
| |
| <a name="7.2.2.6 Tags as Method Calls"><!-- Legacy link --></a> |
| <h2 id="tagsAsMethodCalls">7.2.2.6 Tags as Method Calls</h2> |
| One major different between GSP tags and other tagging technologies is that GSP tags can be called as either regular tags or as method calls from <a href="../guide/single.html#controllers" class="guide">controllers</a>, <a href="../guide/single.html#taglibs" class="guide">tag libraries</a> or GSP views.<p class="paragraph"/><h4>Tags as method calls from GSPs</h4><p class="paragraph"/>Tags return their results as a String-like object (a <code>StreamCharBuffer</code> which has all of the same methods as String) instead of writing directly to the response when called as methods. For example:<p class="paragraph"/><div class="code"><pre>Static Resource: ${createLinkTo(dir: <span class="xml-quote">"images"</span>, file: <span class="xml-quote">"logo.jpg"</span>)}</pre></div><p class="paragraph"/>This is particularly useful for using a tag within an attribute:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><img src=<span class="xml-quote">"${createLinkTo(dir: 'images', file: 'logo.jpg')}"</span> /></span></pre></div><p class="paragraph"/>In view technologies that don't support this feature you have to nest tags within tags, which becomes messy quickly and often has an adverse effect of WYSIWYG tools such as Dreamweaver that attempt to render the mark-up as it is not well-formed:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><img src=<span class="xml-quote">"<g:createLinkTo dir="</span>images<span class="xml-quote">" file="</span>logo.jpg<span class="xml-quote">" /></span>"</span> /></pre></div><p class="paragraph"/><h4>Tags as method calls from Controllers and Tag Libraries</h4><p class="paragraph"/>You can also invoke tags from controllers and tag libraries. Tags within the default <code>g:</code> <a href="../guide/single.html#namespaces" class="guide">namespace</a> can be invoked without the prefix and a <code>StreamCharBuffer</code> result is returned:<p class="paragraph"/><div class="code"><pre>def imageLocation = createLinkTo(dir:<span class="java-quote">"images"</span>, file:<span class="java-quote">"logo.jpg"</span>).toString()</pre></div><p class="paragraph"/>Prefix the namespace to avoid naming conflicts:<p class="paragraph"/><div class="code"><pre>def imageLocation = g.createLinkTo(dir:<span class="java-quote">"images"</span>, file:<span class="java-quote">"logo.jpg"</span>).toString()</pre></div><p class="paragraph"/>For tags that use a <a href="../guide/single.html#namespaces" class="guide">custom namespace</a>, use that prefix for the method call. For example (from the <a href="http://grails.org/plugin/fckeditor" target="blank">FCK Editor plugin</a>):<p class="paragraph"/><div class="code"><pre>def editor = fckeditor.editor(name: <span class="java-quote">"text"</span>, width: <span class="java-quote">"100%"</span>, height: <span class="java-quote">"400"</span>)</pre></div> |
| |
| |
| <a name="7.2.3 Views and Templates"><!-- Legacy link --></a> |
| <h2 id="viewsAndTemplates">7.2.3 Views and Templates</h2> |
| Grails also has the concept of templates. These are useful for partitioning your views into maintainable chunks, and combined with <a href="../guide/single.html#layouts" class="guide">Layouts</a> provide a highly re-usable mechanism for structured views.<p class="paragraph"/><h4>Template Basics</h4><p class="paragraph"/>Grails uses the convention of placing an underscore before the name of a view to identify it as a template. For example, you might have a template that renders Books located at <code>grails-app/views/book/_bookTemplate.gsp</code>:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><div class=<span class="xml-quote">"book"</span> id=<span class="xml-quote">"${book?.id}"</span>></span> |
| <span class="xml-tag"><div></span>Title: ${book?.title}<span class="xml-tag"></div></span> |
| <span class="xml-tag"><div></span>Author: ${book?.author?.name}<span class="xml-tag"></div></span> |
| <span class="xml-tag"></div></span></pre></div><p class="paragraph"/>Use the <a href="../ref/Tags/render.html" class="tags">render</a> tag to render this template from one of the views in <code>grails-app/views/book</code>:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:render template=<span class="xml-quote">"bookTemplate"</span> model=<span class="xml-quote">"[book: myBook]"</span> /></span></pre></div><p class="paragraph"/>Notice how we pass into a model to use using the <code>model</code> attribute of the <code>render</code> tag. If you have multiple <code>Book</code> instances you can also render the template for each <code>Book</code> using the render tag with a <code>collection</code> attribute:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:render template=<span class="xml-quote">"bookTemplate"</span> var=<span class="xml-quote">"book"</span> collection=<span class="xml-quote">"${bookList}"</span> /></span></pre></div><p class="paragraph"/><h4>Shared Templates</h4><p class="paragraph"/>In the previous example we had a template that was specific to the <code>BookController</code> and its views at <code>grails-app/views/book</code>. However, you may want to share templates across your application.<p class="paragraph"/>In this case you can place them in the root views directory at grails-app/views or any subdirectory below that location, and then with the template attribute use an absolute location starting with <code>/</code> instead of a relative location. For example if you had a template called <code>grails-app/views/shared/_mySharedTemplate.gsp</code>, you would reference it as:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:render template=<span class="xml-quote">"/shared/mySharedTemplate"</span> /></span></pre></div><p class="paragraph"/>You can also use this technique to reference templates in any directory from any view or controller:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:render template=<span class="xml-quote">"/book/bookTemplate"</span> model=<span class="xml-quote">"[book: myBook]"</span> /></span></pre></div><p class="paragraph"/><h4>The Template Namespace</h4><p class="paragraph"/>Since templates are used so frequently there is template namespace, called <code>tmpl</code>, available that makes using templates easier. Consider for example the following usage pattern:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:render template=<span class="xml-quote">"bookTemplate"</span> model=<span class="xml-quote">"[book:myBook]"</span> /></span></pre></div><p class="paragraph"/>This can be expressed with the <code>tmpl</code> namespace as follows:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><tmpl:bookTemplate book=<span class="xml-quote">"${myBook}"</span> /></span></pre></div><p class="paragraph"/><h4>Templates in Controllers and Tag Libraries</h4><p class="paragraph"/>You can also render templates from controllers using the <a href="../ref/Controllers/render.html" class="controllers">render</a> controller method. This is useful for JavaScript heavy applications where you generate small HTML or data responses to partially update the current page instead of performing new request:<p class="paragraph"/><div class="code"><pre>def bookData() { |
| def b = Book.get(params.id) |
| render(template:<span class="java-quote">"bookTemplate"</span>, model:[book:b]) |
| }</pre></div><p class="paragraph"/>The <a href="../ref/Controllers/render.html" class="controllers">render</a> controller method writes directly to the response, which is the most common behaviour. To instead obtain the result of template as a String you can use the <a href="../ref/Tags/render.html" class="tags">render</a> tag:<p class="paragraph"/><div class="code"><pre>def bookData() { |
| def b = Book.get(params.id) |
| <span class="java-object">String</span> content = g.render(template:<span class="java-quote">"bookTemplate"</span>, model:[book:b]) |
| render content |
| }</pre></div><p class="paragraph"/>Notice the usage of the <code>g</code> namespace which tells Grails we want to use the <a href="../guide/single.html#tagsAsMethodCalls" class="guide">tag as method call</a> instead of the <a href="../ref/Controllers/render.html" class="controllers">render</a> method. |
| |
| |
| <a name="7.2.4 Layouts with Sitemesh"><!-- Legacy link --></a> |
| <h2 id="layouts">7.2.4 Layouts with Sitemesh</h2> |
| <h4>Creating Layouts</h4><p class="paragraph"/>Grails leverages <a href="http://www.opensymphony.com/sitemesh/" target="blank">Sitemesh</a>, a decorator engine, to support view layouts. Layouts are located in the <code>grails-app/views/layouts</code> directory. A typical layout can be seen below:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><html></span> |
| <span class="xml-tag"><head></span> |
| <span class="xml-tag"><title></span><span class="xml-tag"><g:layoutTitle default=<span class="xml-quote">"An example decorator"</span> /></span><span class="xml-tag"></title></span> |
| <span class="xml-tag"><g:layoutHead /></span> |
| <span class="xml-tag"></head></span> |
| <span class="xml-tag"><body onload=<span class="xml-quote">"${pageProperty(name:'body.onload')}"</span>></span> |
| <span class="xml-tag"><div class=<span class="xml-quote">"menu"</span>></span><span class="xml-comment"><!--my common menu goes here--></span><span class="xml-tag"></menu></span> |
| <span class="xml-tag"><div class=<span class="xml-quote">"body"</span>></span> |
| <span class="xml-tag"><g:layoutBody /></span> |
| <span class="xml-tag"></div></span> |
| <span class="xml-tag"></div></span> |
| <span class="xml-tag"></body></span> |
| <span class="xml-tag"></html></span></pre></div><p class="paragraph"/>The key elements are the <a href="../ref/Tags/layoutHead.html" class="tags">layoutHead</a>, <a href="../ref/Tags/layoutTitle.html" class="tags">layoutTitle</a> and <a href="../ref/Tags/layoutBody.html" class="tags">layoutBody</a> tag invocations: |
| <ul class="star"> |
| <li><code>layoutTitle</code> - outputs the target page's title</li> |
| <li><code>layoutHead</code> - outputs the target page's head tag contents</li> |
| <li><code>layoutBody</code> - outputs the target page's body tag contents</li> |
| </ul><p class="paragraph"/>The previous example also demonstrates the <a href="../ref/Tags/pageProperty.html" class="tags">pageProperty</a> tag which can be used to inspect and return aspects of the target page.<p class="paragraph"/><h4>Triggering Layouts</h4><p class="paragraph"/>There are a few ways to trigger a layout. The simplest is to add a meta tag to the view:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><html></span> |
| <span class="xml-tag"><head></span> |
| <span class="xml-tag"><title></span>An Example Page<span class="xml-tag"></title></span> |
| <span class="xml-tag"><meta name=<span class="xml-quote">"layout"</span> content=<span class="xml-quote">"main"</span> /></span> |
| <span class="xml-tag"></head></span> |
| <span class="xml-tag"><body></span>This is my content!<span class="xml-tag"></body></span> |
| <span class="xml-tag"></html></span></pre></div><p class="paragraph"/>In this case a layout called <code>grails-app/views/layouts/main.gsp</code> will be used to layout the page. If we were to use the layout from the previous section the output would resemble this:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><html></span> |
| <span class="xml-tag"><head></span> |
| <span class="xml-tag"><title></span>An Example Page<span class="xml-tag"></title></span> |
| <span class="xml-tag"></head></span> |
| <span class="xml-tag"><body onload=<span class="xml-quote">""</span>></span> |
| <span class="xml-tag"><div class=<span class="xml-quote">"menu"</span>></span><span class="xml-comment"><!--my common menu goes here--></span><span class="xml-tag"></div></span> |
| <span class="xml-tag"><div class=<span class="xml-quote">"body"</span>></span> |
| This is my content! |
| <span class="xml-tag"></div></span> |
| <span class="xml-tag"></body></span> |
| <span class="xml-tag"></html></span></pre></div><p class="paragraph"/><h4>Specifying A Layout In A Controller</h4><p class="paragraph"/>Another way to specify a layout is to specify the name of the layout by assigning a value to the "layout" property in a controller. For example, if you have a controller such as:<p class="paragraph"/><div class="code"><pre>class BookController { |
| <span class="java-keyword">static</span> layout = 'customer'<p class="paragraph"/> def list() { … } |
| }</pre></div><p class="paragraph"/>You can create a layout called <code>grails-app/views/layouts/customer.gsp</code> which will be applied to all views that the <code>BookController</code> delegates to. The value of the "layout" property may contain a directory structure relative to the <code>grails-app/views/layouts/</code> directory. For example:<p class="paragraph"/><div class="code"><pre>class BookController { |
| <span class="java-keyword">static</span> layout = 'custom/customer'<p class="paragraph"/> def list() { … } |
| }</pre></div><p class="paragraph"/>Views rendered from that controller would be decorated with the <code>grails-app/views/layouts/custom/customer.gsp</code> template.<p class="paragraph"/><h4>Layout by Convention</h4><p class="paragraph"/>Another way to associate layouts is to use "layout by convention". For example, if you have this controller:<p class="paragraph"/><div class="code"><pre>class BookController { |
| def list() { … } |
| }</pre></div><p class="paragraph"/>You can create a layout called <code>grails-app/views/layouts/book.gsp</code>, which will be applied to all views that the <code>BookController</code> delegates to.<p class="paragraph"/>Alternatively, you can create a layout called <code>grails-app/views/layouts/book/list.gsp</code> which will only be applied to the <code>list</code> action within the <code>BookController</code>.<p class="paragraph"/>If you have both the above mentioned layouts in place the layout specific to the action will take precedence when the list action is executed.<p class="paragraph"/>If a layout may not be located using any of those conventions, the convention of last resort is to look for the application default layout which |
| is <code>grails-app/views/layouts/application.gsp</code>. The name of the application default layout may be changed by defining a property |
| in <code>grails-app/conf/Config.groovy</code> as follows:<p class="paragraph"/><div class="code"><pre>grails.sitemesh.<span class="java-keyword">default</span>.layout = 'myLayoutName'</pre></div><p class="paragraph"/>With that property in place, the application default layout will be <code>grails-app/views/layouts/myLayoutName.gsp</code>.<p class="paragraph"/><h4>Inline Layouts</h4><p class="paragraph"/>Grails' also supports Sitemesh's concept of inline layouts with the <a href="../ref/Tags/applyLayout.html" class="tags">applyLayout</a> tag. This can be used to apply a layout to a template, URL or arbitrary section of content. This lets you even further modularize your view structure by "decorating" your template includes.<p class="paragraph"/>Some examples of usage can be seen below:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:applyLayout name=<span class="xml-quote">"myLayout"</span> template=<span class="xml-quote">"bookTemplate"</span> collection=<span class="xml-quote">"${books}"</span> /></span><p class="paragraph"/><span class="xml-tag"><g:applyLayout name=<span class="xml-quote">"myLayout"</span> url=<span class="xml-quote">"http://www.google.com"</span> /></span><p class="paragraph"/><span class="xml-tag"><g:applyLayout name=<span class="xml-quote">"myLayout"</span>></span> |
| The content to apply a layout to |
| <span class="xml-tag"></g:applyLayout></span></pre></div><p class="paragraph"/><h4>Server-Side Includes</h4><p class="paragraph"/>While the <a href="../ref/Tags/applyLayout.html" class="tags">applyLayout</a> tag is useful for applying layouts to external content, if you simply want to include external content in the current page you use the <a href="../ref/Tags/include.html" class="tags">include</a> tag:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:include controller=<span class="xml-quote">"book"</span> action=<span class="xml-quote">"list"</span> /></span></pre></div><p class="paragraph"/>You can even combine the <a href="../ref/Tags/include.html" class="tags">include</a> tag and the <a href="../ref/Tags/applyLayout.html" class="tags">applyLayout</a> tag for added flexibility:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:applyLayout name=<span class="xml-quote">"myLayout"</span>></span> |
| <span class="xml-tag"><g:include controller=<span class="xml-quote">"book"</span> action=<span class="xml-quote">"list"</span> /></span> |
| <span class="xml-tag"></g:applyLayout></span></pre></div><p class="paragraph"/>Finally, you can also call the <a href="../ref/Tags/include.html" class="tags">include</a> tag from a controller or tag library as a method:<p class="paragraph"/><div class="code"><pre>def content = include(controller:<span class="java-quote">"book"</span>, action:<span class="java-quote">"list"</span>)</pre></div><p class="paragraph"/>The resulting content will be provided via the return value of the <a href="../ref/Tags/include.html" class="tags">include</a> tag. |
| |
| |
| <a name="7.2.5 Static Resources"><!-- Legacy link --></a> |
| <h2 id="resources">7.2.5 Static Resources</h2> |
| Grails 2.0 integrates with the <a href="http://grails.org/plugin/asset-pipeline" target="blank">Asset Pipeline plugin</a> to provide sophisticated static asset management. This plugin is installed by default in new Grails applications.<p class="paragraph"/>The basic way to include a link to a static asset in your application is to use the <a href="../ref/Tags/resource.html" class="tags">resource</a> tag. This simple approach creates a URI pointing to the file.<p class="paragraph"/>However modern applications with dependencies on multiple JavaScript and CSS libraries and frameworks (as well as dependencies on multiple Grails plugins) require something more powerful.<p class="paragraph"/>The issues that the Asset-Pipeline plugin tackles are: |
| <ul class="star"> |
| <li>Reduced Dependence - The plugin has compression, minification, and cache-digests built in.</li> |
| <li>Easy Debugging - Makes for easy debugging by keeping files separate in development mode.</li> |
| <li>Asset Bundling using require <a href="http://bertramdev.github.io/asset-pipeline/guide/usage.html#directives" target="blank">directives</a>.</li> |
| <li>Web application performance tuning is difficult.</li> |
| <li>The need for a standard way to expose static assets in plugins and applications.</li> |
| <li>The need for extensible processing to make languages like LESS or Coffee first class citizens.</li> |
| </ul><p class="paragraph"/>The asset-pipeline allows you to define your javascript or css requirements right at the top of the file and they get compiled on War creation.<p class="paragraph"/>Take a look at the <a href="http://bertramdev.github.io/asset-pipeline" target="blank">documentation</a> for the asset-pipeline to get started. |
| |
| |
| <a name="7.2.6 Sitemesh Content Blocks"><!-- Legacy link --></a> |
| <h2 id="sitemeshContentBlocks">7.2.6 Sitemesh Content Blocks</h2> |
| Although it is useful to decorate an entire page sometimes you may find the need to decorate independent sections of your site. To do this you can use content blocks. To get started, partition the page to be decorated using the <code><content></code> tag:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><content tag=<span class="xml-quote">"navbar"</span>></span> |
| … draw the navbar here… |
| <span class="xml-tag"></content></span><p class="paragraph"/><span class="xml-tag"><content tag=<span class="xml-quote">"header"</span>></span> |
| … draw the header here… |
| <span class="xml-tag"></content></span><p class="paragraph"/><span class="xml-tag"><content tag=<span class="xml-quote">"footer"</span>></span> |
| … draw the footer here… |
| <span class="xml-tag"></content></span><p class="paragraph"/><span class="xml-tag"><content tag=<span class="xml-quote">"body"</span>></span> |
| … draw the body here… |
| <span class="xml-tag"></content></span></pre></div><p class="paragraph"/>Then within the layout you can reference these components and apply individual layouts to each:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><html></span> |
| <span class="xml-tag"><body></span> |
| <span class="xml-tag"><div id=<span class="xml-quote">"header"</span>></span> |
| <span class="xml-tag"><g:applyLayout name=<span class="xml-quote">"headerLayout"</span>></span> |
| <span class="xml-tag"><g:pageProperty name=<span class="xml-quote">"page.header"</span> /></span> |
| <span class="xml-tag"></g:applyLayout></span> |
| <span class="xml-tag"></div></span> |
| <span class="xml-tag"><div id=<span class="xml-quote">"nav"</span>></span> |
| <span class="xml-tag"><g:applyLayout name=<span class="xml-quote">"navLayout"</span>></span> |
| <span class="xml-tag"><g:pageProperty name=<span class="xml-quote">"page.navbar"</span> /></span> |
| <span class="xml-tag"></g:applyLayout></span> |
| <span class="xml-tag"></div></span> |
| <span class="xml-tag"><div id=<span class="xml-quote">"body"</span>></span> |
| <span class="xml-tag"><g:applyLayout name=<span class="xml-quote">"bodyLayout"</span>></span> |
| <span class="xml-tag"><g:pageProperty name=<span class="xml-quote">"page.body"</span> /></span> |
| <span class="xml-tag"></g:applyLayout></span> |
| <span class="xml-tag"></div></span> |
| <span class="xml-tag"><div id=<span class="xml-quote">"footer"</span>></span> |
| <span class="xml-tag"><g:applyLayout name=<span class="xml-quote">"footerLayout"</span>></span> |
| <span class="xml-tag"><g:pageProperty name=<span class="xml-quote">"page.footer"</span> /></span> |
| <span class="xml-tag"></g:applyLayout></span> |
| <span class="xml-tag"></div></span> |
| <span class="xml-tag"></body></span> |
| <span class="xml-tag"></html></span></pre></div> |
| |
| |
| <a name="7.2.7 Making Changes to a Deployed Application"><!-- Legacy link --></a> |
| <h2 id="makingChangesToADeployedApplication">7.2.7 Making Changes to a Deployed Application</h2> |
| One of the main issues with deploying a Grails application (or typically any servlet-based one) is that any change to the views requires that you redeploy your whole application. If all you want to do is fix a typo on a page, or change an image link, it can seem like a lot of unnecessary work. For such simple requirements, Grails does have a solution: the <code>grails.gsp.view.dir</code> configuration setting.<p class="paragraph"/>How does this work? The first step is to decide where the GSP files should go. Let's say we want to keep them unpacked in a <code>/var/www/grails/my-app</code> directory. We add these two lines to <code>grails-app/conf/Config.groovy</code> : |
| <div class="code"><pre>grails.gsp.enable.reload = <span class="java-keyword">true</span> |
| grails.gsp.view.dir = <span class="java-quote">"/<span class="java-keyword">var</span>/www/grails/my-app/"</span></pre></div> |
| The first line tells Grails that modified GSP files should be reloaded at runtime. If you don't have this setting, you can make as many changes as you like but they won't be reflected in the running application until you restart. The second line tells Grails where to load the views and layouts from.<p class="paragraph"/><blockquote class="note"> |
| The trailing slash on the <code>grails.gsp.view.dir</code> value is important! Without it, Grails will look for views in the parent directory. |
| </blockquote><p class="paragraph"/>Setting "grails.gsp.view.dir" is optional. If it's not specified, you can update files directly to the application server's deployed war directory. Depending on the application server, these files might get overwritten when the server is restarted. Most application servers support "exploded war deployment" which is recommended in this case.<p class="paragraph"/>With those settings in place, all you need to do is copy the views from your web application to the external directory. On a Unix-like system, this would look something like this: |
| <div class="code"><pre>mkdir -p /<span class="java-keyword">var</span>/www/grails/my-app/grails-app/views |
| cp -R grails-app/views/* /<span class="java-keyword">var</span>/www/grails/my-app/grails-app/views</pre></div> |
| The key point here is that you must retain the view directory structure, including the <code>grails-app/views</code> bit. So you end up with the path <code>/var/www/grails/my-app/grails-app/views/...</code> .<p class="paragraph"/>One thing to bear in mind with this technique is that every time you modify a GSP, it uses up permgen space. So at some point you will eventually hit "out of permgen space" errors unless you restart the server. So this technique is not recommended for frequent or large changes to the views.<p class="paragraph"/>There are also some System properties to control GSP reloading: |
| <table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th><strong class="bold">Name</strong></th><th><strong class="bold">Description</strong></th><th><strong class="bold">Default</strong></th></tr><tr class="table-odd"><td>grails.gsp.enable.reload</td><td>alternative system property for enabling the GSP reload mode without changing Config.groovy</td><td> </td></tr><tr class="table-even"><td>grails.gsp.reload.interval</td><td>interval between checking the lastmodified time of the gsp source file, unit is milliseconds</td><td>5000</td></tr><tr class="table-odd"><td>grails.gsp.reload.granularity</td><td>the number of milliseconds leeway to give before deciding a file is out of date. this is needed because different roundings usually cause a 1000ms difference in lastmodified times</td><td>1000</td></tr></table><p class="paragraph"/>GSP reloading is supported for precompiled GSPs since Grails 1.3.5 . |
| |
| |
| <a name="7.2.8 GSP Debugging"><!-- Legacy link --></a> |
| <h2 id="GSPDebugging">7.2.8 GSP Debugging</h2> |
| <h4>Viewing the generated source code</h4> |
| <ul class="star"> |
| <li>Adding "?showSource=true" or "&showSource=true" to the url shows the generated Groovy source code for the view instead of rendering it. It won't show the source code of included templates. This only works in development mode</li> |
| <li>The saving of all generated source code can be activated by setting the property "grails.views.gsp.keepgenerateddir" (in Config.groovy) . It must point to a directory that exists and is writable.</li> |
| <li>During "grails war" gsp pre-compilation, the generated source code is stored in grails.project.work.dir/gspcompile (usually in ~/.grails/(grails_version)/projects/(project name)/gspcompile).</li> |
| </ul><p class="paragraph"/><h4>Debugging GSP code with a debugger</h4> |
| <ul class="star"> |
| <li>See <a href="http://contraptionsforprogramming.blogspot.com/2010/08/debuggable-gsps-in-springsource-tool.html" target="blank">Debugging GSP in STS</a></li> |
| </ul><p class="paragraph"/><h4>Viewing information about templates used to render a single url</h4><p class="paragraph"/>GSP templates are reused in large web applications by using the <code>g:render</code> taglib. Several small templates can be used to render a single page. |
| It might be hard to find out what GSP template actually renders the html seen in the result. |
| The debug templates -feature adds html comments to the output. The comments contain debug information about gsp templates used to render the page.<p class="paragraph"/>Usage is simple: append "?debugTemplates" or "&debugTemplates" to the url and view the source of the result in your browser. |
| "debugTemplates" is restricted to development mode. It won't work in production.<p class="paragraph"/>Here is an example of comments added by debugTemplates : |
| <div class="code"><pre><!-- GSP #2 START template: /home/.../views/_carousel.gsp |
| precompiled: <span class="java-keyword">false</span> lastmodified: … --> |
| . |
| . |
| . |
| <!-- GSP #2 END template: /home/.../views/_carousel.gsp |
| rendering time: 115 ms --></pre></div><p class="paragraph"/>Each comment block has a unique id so that you can find the start & end of each template call. |
| |
| |
| <a name="7.3 Tag Libraries"><!-- Legacy link --></a> |
| <h2 id="taglibs">7.3 Tag Libraries</h2> |
| Like <a href="http://www.oracle.com/technetwork/java/javaee/jsp/index.html" target="blank">Java Server Pages</a> (JSP), GSP supports the concept of custom tag libraries. Unlike JSP, Grails' tag library mechanism is simple, elegant and completely reloadable at runtime.<p class="paragraph"/>Quite simply, to create a tag library create a Groovy class that ends with the convention <code>TagLib</code> and place it within the <code>grails-app/taglib</code> directory:<p class="paragraph"/><div class="code"><pre>class SimpleTagLib {<p class="paragraph"/>}</pre></div><p class="paragraph"/>Now to create a tag create a Closure property that takes two arguments: the tag attributes and the body content:<p class="paragraph"/><div class="code"><pre>class SimpleTagLib { |
| def simple = { attrs, body -><p class="paragraph"/> } |
| }</pre></div><p class="paragraph"/>The <code>attrs</code> argument is a Map of the attributes of the tag, whilst the <code>body</code> argument is a Closure that returns the body content when invoked:<p class="paragraph"/><div class="code"><pre>class SimpleTagLib { |
| def emoticon = { attrs, body -> |
| out << body() << (attrs.happy == '<span class="java-keyword">true</span>' ? <span class="java-quote">" :-)"</span> : <span class="java-quote">" :-("</span>) |
| } |
| }</pre></div><p class="paragraph"/>As demonstrated above there is an implicit <code>out</code> variable that refers to the output <code>Writer</code> which you can use to append content to the response. Then you can reference the tag inside your GSP; no imports are necessary:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:emoticon happy=<span class="xml-quote">"true"</span>></span>Hi John<span class="xml-tag"></g:emoticon></span></pre></div><p class="paragraph"/><blockquote class="note"> |
| To help IDEs like Spring Tool Suite (STS) and others autocomplete tag attributes, you should add Javadoc comments to your tag closures with <code>@attr</code> descriptions. Since taglibs use Groovy code it can be difficult to reliably detect all usable attributes.<p class="paragraph"/>For example:<p class="paragraph"/><div class="code"><pre>class SimpleTagLib {<p class="paragraph"/> /** |
| * Renders the body with an emoticon. |
| * |
| * @attr happy whether to show a happy emoticon ('<span class="java-keyword">true</span>') or |
| * a sad emoticon ('<span class="java-keyword">false</span>') |
| */ |
| def emoticon = { attrs, body -> |
| out << body() << (attrs.happy == '<span class="java-keyword">true</span>' ? <span class="java-quote">" :-)"</span> : <span class="java-quote">" :-("</span>) |
| } |
| }</pre></div><p class="paragraph"/>and any mandatory attributes should include the REQUIRED keyword, e.g.<p class="paragraph"/><div class="code"><pre>class SimpleTagLib {<p class="paragraph"/> /** |
| * Creates a <span class="java-keyword">new</span> password field. |
| * |
| * @attr name REQUIRED the field name |
| * @attr value the field value |
| */ |
| def passwordField = { attrs -> |
| attrs.type = <span class="java-quote">"password"</span> |
| attrs.tagName = <span class="java-quote">"passwordField"</span> |
| fieldImpl(out, attrs) |
| } |
| }</pre></div> |
| </blockquote> |
| |
| |
| |
| <h2 id="taglibVariablesAndScopes">7.3.1 Variables and Scopes</h2> |
| Within the scope of a tag library there are a number of pre-defined variables including: |
| <ul class="star"> |
| <li><code>actionName</code> - The currently executing action name</li> |
| <li><code>controllerName</code> - The currently executing controller name</li> |
| <li><code>flash</code> - The <a href="../ref/Controllers/flash.html" class="controllers">flash</a> object</li> |
| <li><code>grailsApplication</code> - The <a href="http://grails.org/doc/3.0.x/api/grails/core/GrailsApplication.html" class="api">GrailsApplication</a> instance</li> |
| <li><code>out</code> - The response writer for writing to the output stream</li> |
| <li><code>pageScope</code> - A reference to the <a href="../ref/Tag Libraries/pageScope.html" class="tagLibraries">pageScope</a> object used for GSP rendering (i.e. the binding)</li> |
| <li><code>params</code> - The <a href="../ref/Controllers/params.html" class="controllers">params</a> object for retrieving request parameters</li> |
| <li><code>pluginContextPath</code> - The context path to the plugin that contains the tag library</li> |
| <li><code>request</code> - The <a href="http://download.oracle.com/javaee/1.4/api/javax/servlet/http/HttpServletRequest.html" class="api">HttpServletRequest</a> instance</li> |
| <li><code>response</code> - The <a href="http://download.oracle.com/javaee/1.4/api/javax/servlet/http/HttpServletResponse.html" class="api">HttpServletResponse</a> instance</li> |
| <li><code>servletContext</code> - The <a href="http://download.oracle.com/javaee/1.4/api/javax/servlet/ServletContext.html" class="api">javax.servlet.ServletContext</a> instance</li> |
| <li><code>session</code> - The <a href="http://download.oracle.com/javaee/1.4/api/javax/servlet/http/HttpSession.html" class="api">HttpSession</a> instance</li> |
| </ul><p class="paragraph"/> |
| |
| <a name="7.3.2 Simple Tags"><!-- Legacy link --></a> |
| <h2 id="simpleTags">7.3.2 Simple Tags</h2> |
| As demonstrated in the previous example it is easy to write simple tags that have no body and just output content. Another example is a <code>dateFormat</code> style tag:<p class="paragraph"/><div class="code"><pre>def dateFormat = { attrs, body -> |
| out << <span class="java-keyword">new</span> java.text.SimpleDateFormat(attrs.format).format(attrs.date) |
| }</pre></div><p class="paragraph"/>The above uses Java's <code>SimpleDateFormat</code> class to format a date and then write it to the response. The tag can then be used within a GSP as follows:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:dateFormat format=<span class="xml-quote">"dd-MM-yyyy"</span> date=<span class="xml-quote">"${new Date()}"</span> /></span></pre></div><p class="paragraph"/>With simple tags sometimes you need to write HTML mark-up to the response. One approach would be to embed the content directly:<p class="paragraph"/><div class="code"><pre>def formatBook = { attrs, body -> |
| out << <span class="java-quote">"<div id="${attrs.book.id}">"</span> |
| out << <span class="java-quote">"Title : ${attrs.book.title}"</span> |
| out << <span class="java-quote">"</div>"</span> |
| }</pre></div><p class="paragraph"/>Although this approach may be tempting it is not very clean. A better approach would be to reuse the <a href="../ref/Tags/render.html" class="tags">render</a> tag:<p class="paragraph"/><div class="code"><pre>def formatBook = { attrs, body -> |
| out << render(template: <span class="java-quote">"bookTemplate"</span>, model: [book: attrs.book]) |
| }</pre></div><p class="paragraph"/>And then have a separate GSP template that does the actual rendering. |
| |
| |
| <a name="7.3.3 Logical Tags"><!-- Legacy link --></a> |
| <h2 id="logicalTags">7.3.3 Logical Tags</h2> |
| You can also create logical tags where the body of the tag is only output once a set of conditions have been met. An example of this may be a set of security tags:<p class="paragraph"/><div class="code"><pre>def isAdmin = { attrs, body -> |
| def user = attrs.user |
| <span class="java-keyword">if</span> (user && checkUserPrivs(user)) { |
| out << body() |
| } |
| }</pre></div><p class="paragraph"/>The tag above checks if the user is an administrator and only outputs the body content if he/she has the correct set of access privileges:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:isAdmin user=<span class="xml-quote">"${myUser}"</span>></span> |
| // some restricted content |
| <span class="xml-tag"></g:isAdmin></span></pre></div> |
| |
| |
| <a name="7.3.4 Iterative Tags"><!-- Legacy link --></a> |
| <h2 id="iterativeTags">7.3.4 Iterative Tags</h2> |
| Iterative tags are easy too, since you can invoke the body multiple times:<p class="paragraph"/><div class="code"><pre>def repeat = { attrs, body -> |
| attrs.times?.toInteger()?.times { num -> |
| out << body(num) |
| } |
| }</pre></div><p class="paragraph"/>In this example we check for a <code>times</code> attribute and if it exists convert it to a number, then use Groovy's <code>times</code> method to iterate the specified number of times:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:repeat times=<span class="xml-quote">"3"</span>></span> |
| <span class="xml-tag"><p></span>Repeat this 3 times! Current repeat = ${it}<span class="xml-tag"></p></span> |
| <span class="xml-tag"></g:repeat></span></pre></div><p class="paragraph"/>Notice how in this example we use the implicit <code>it</code> variable to refer to the current number. This works because when we invoked the body we passed in the current value inside the iteration:<p class="paragraph"/><div class="code"><pre>out << body(num)</pre></div><p class="paragraph"/>That value is then passed as the default variable <code>it</code> to the tag. However, if you have nested tags this can lead to conflicts, so you should instead name the variables that the body uses:<p class="paragraph"/><div class="code"><pre>def repeat = { attrs, body -> |
| def <span class="java-keyword">var</span> = attrs.<span class="java-keyword">var</span> ?: <span class="java-quote">"num"</span> |
| attrs.times?.toInteger()?.times { num -> |
| out << body((<span class="java-keyword">var</span>):num) |
| } |
| }</pre></div><p class="paragraph"/>Here we check if there is a <code>var</code> attribute and if there is use that as the name to pass into the body invocation on this line:<p class="paragraph"/><div class="code"><pre>out << body((<span class="java-keyword">var</span>):num)</pre></div><p class="paragraph"/><blockquote class="note"> |
| Note the usage of the parenthesis around the variable name. If you omit these Groovy assumes you are using a String key and not referring to the variable itself. |
| </blockquote><p class="paragraph"/>Now we can change the usage of the tag as follows:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:repeat times=<span class="xml-quote">"3"</span> var=<span class="xml-quote">"j"</span>></span> |
| <span class="xml-tag"><p></span>Repeat this 3 times! Current repeat = ${j}<span class="xml-tag"></p></span> |
| <span class="xml-tag"></g:repeat></span></pre></div><p class="paragraph"/>Notice how we use the <code>var</code> attribute to define the name of the variable <code>j</code> and then we are able to reference that variable within the body of the tag. |
| |
| |
| <a name="7.3.5 Tag Namespaces"><!-- Legacy link --></a> |
| <h2 id="namespaces">7.3.5 Tag Namespaces</h2> |
| By default, tags are added to the default Grails namespace and are used with the <code>g:</code> prefix in GSP pages. However, you can specify a different namespace by adding a static property to your <code>TagLib</code> class:<p class="paragraph"/><div class="code"><pre>class SimpleTagLib { |
| <span class="java-keyword">static</span> namespace = <span class="java-quote">"my"</span><p class="paragraph"/> def example = { attrs -> |
| … |
| } |
| }</pre></div><p class="paragraph"/>Here we have specified a <code>namespace</code> of <code>my</code> and hence the tags in this tag lib must then be referenced from GSP pages like this:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><my:example name=<span class="xml-quote">"..."</span> /></span></pre></div><p class="paragraph"/>where the prefix is the same as the value of the static <code>namespace</code> property. Namespaces are particularly useful for plugins.<p class="paragraph"/>Tags within namespaces can be invoked as methods using the namespace as a prefix to the method call:<p class="paragraph"/><div class="code"><pre>out << my.example(name:<span class="java-quote">"foo"</span>)</pre></div><p class="paragraph"/>This works from GSP, controllers or tag libraries |
| |
| |
| <a name="7.3.6 Using JSP Tag Libraries"><!-- Legacy link --></a> |
| <h2 id="usingJSPTagLibraries">7.3.6 Using JSP Tag Libraries</h2> |
| In addition to the simplified tag library mechanism provided by GSP, you can also use JSP tags from GSP. To do so simply declare the JSP to use with the <code>taglib</code> directive:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><%@ taglib prefix=<span class="xml-quote">"fmt"</span> uri=<span class="xml-quote">"http://java.sun.com/jsp/jstl/fmt"</span> %></span></pre></div><p class="paragraph"/>Besides this you have to configure Grails to scan for the JSP tld files. |
| This is configured with the <code>grails.gsp.tldScanPattern</code> setting. It accepts a comma separated String value. Spring's PathMatchingResourcePatternResolver is used to resolve the patterns.<p class="paragraph"/>For example you could scan for all available tld files by adding this to Config.groovy: |
| <div class="code"><pre>grails.gsp.tldScanPattern='classpath*:/META-INF/*.tld,/WEB-INF/tld/*.tld'</pre></div><p class="paragraph"/>JSTL standard library is no more added as a dependency by default. In case you are using JSTL, you should also add these dependencies to BuildConfig.groovy: |
| <div class="code"><pre>runtime 'javax.servlet:jstl:1.1.2' |
| runtime 'taglibs:standard:1.1.2'</pre></div><p class="paragraph"/>Then you can use JSP tags like any other tag:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><fmt:formatNumber value=<span class="xml-quote">"${10}"</span> pattern=<span class="xml-quote">".00"</span>/></span></pre></div><p class="paragraph"/>With the added bonus that you can invoke JSP tags like methods:<p class="paragraph"/><div class="code"><pre>${fmt.formatNumber(value:10, pattern:<span class="java-quote">".00"</span>)}</pre></div> |
| |
| <a name="7.3.7 Tag return value"><!-- Legacy link --></a> |
| <h2 id="tagReturnValue">7.3.7 Tag return value</h2> |
| A taglib can be used in a GSP as an ordinary tag or it might be used as a function in other taglibs or GSP expressions.<p class="paragraph"/>Internally Grails intercepts calls to taglib closures. |
| The "out" that is available in a taglib is mapped to a <code>java.io.Writer</code> implementation that writes to a buffer |
| that "captures" the output of the taglib call. This buffer is the return value of a tag library call when it's |
| used as a function.<p class="paragraph"/>If the tag is listed in the library's static <code>returnObjectForTags</code> array, then its return value will written to |
| the output when it's used as a normal tag. The return value of the tag lib closure will be returned as-is |
| if it's used as a function in GSP expressions or other taglibs.<p class="paragraph"/>If the tag is not included in the returnObjectForTags array, then its return value will be discarded. |
| Using "out" to write output in returnObjectForTags is not supported.<p class="paragraph"/>Example: |
| <div class="code"><pre>class ObjectReturningTagLib { |
| <span class="java-keyword">static</span> namespace = <span class="java-quote">"cms"</span> |
| <span class="java-keyword">static</span> returnObjectForTags = ['content']<p class="paragraph"/> def content = { attrs, body -> |
| CmsContent.findByCode(attrs.code)?.content |
| } |
| }</pre></div><p class="paragraph"/>Given this example cmd.content(code:'something') call in another taglib or GSP expression would return the value "CmsContent.content" directly to the caller without |
| wrapping the return value in a buffer. It might be worth doing so also because of performance optimization reasons. There is no need to wrap the |
| tag return value in an output buffer in such cases. |
| |
| <a name="7.4 URL Mappings"><!-- Legacy link --></a> |
| <h2 id="urlmappings">7.4 URL Mappings</h2> |
| Throughout the documentation so far the convention used for URLs has been the default of <code>/controller/action/id</code>. However, this convention is not hard wired into Grails and is in fact controlled by a URL Mappings class located at <code>grails-app/conf/UrlMappings.groovy</code>.<p class="paragraph"/>The <code>UrlMappings</code> class contains a single property called <code>mappings</code> that has been assigned a block of code:<p class="paragraph"/><div class="code"><pre>class UrlMappings { |
| <span class="java-keyword">static</span> mappings = { |
| } |
| }</pre></div><p class="paragraph"/> |
| |
| <a name="7.4.1 Mapping to Controllers and Actions"><!-- Legacy link --></a> |
| <h2 id="mappingToControllersAndActions">7.4.1 Mapping to Controllers and Actions</h2> |
| To create a simple mapping simply use a relative URL as the method name and specify named parameters for the controller and action to map to:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/product"</span>(controller: <span class="java-quote">"product"</span>, action: <span class="java-quote">"list"</span>)</pre></div><p class="paragraph"/>In this case we've mapped the URL <code>/product</code> to the <code>list</code> action of the <code>ProductController</code>. Omit the action definition to map to the default action of the controller:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/product"</span>(controller: <span class="java-quote">"product"</span>)</pre></div><p class="paragraph"/>An alternative syntax is to assign the controller and action to use within a block passed to the method:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/product"</span> { |
| controller = <span class="java-quote">"product"</span> |
| action = <span class="java-quote">"list"</span> |
| }</pre></div><p class="paragraph"/>Which syntax you use is largely dependent on personal preference.<p class="paragraph"/>If you have mappings that all fall under a particular path you can group mappings with the <code>group</code> method:<p class="paragraph"/><div class="code"><pre>group <span class="java-quote">"/product"</span>, { |
| <span class="java-quote">"/apple"</span>(controller:<span class="java-quote">"product"</span>, id:<span class="java-quote">"apple"</span>) |
| <span class="java-quote">"/htc"</span>(controller:<span class="java-quote">"product"</span>, id:<span class="java-quote">"htc"</span>) |
| }</pre></div><p class="paragraph"/>To rewrite one URI onto another explicit URI (rather than a controller/action pair) do something like this:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/hello"</span>(uri: <span class="java-quote">"/hello.dispatch"</span>)</pre></div><p class="paragraph"/>Rewriting specific URIs is often useful when integrating with other frameworks. |
| |
| |
| <a name="7.4.3 Mapping to REST resources"><!-- Legacy link --></a> |
| <h2 id="restfulMappings">7.4.2 Mapping to REST resources</h2> |
| Since Grails 2.3, it possible to create RESTful URL mappings that map onto controllers by convention. The syntax to do so is as follows:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/books"</span>(resources:'book')</pre></div><p class="paragraph"/>You define a base URI and the name of the controller to map to using the <code>resources</code> parameter. The above mapping will result in the following URLs:<p class="paragraph"/> |
| <table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>HTTP Method</th><th>URI</th><th>Grails Action</th></tr><tr class="table-odd"><td>GET</td><td>/books</td><td>index</td></tr><tr class="table-even"><td>GET</td><td>/books/create</td><td>create</td></tr><tr class="table-odd"><td>POST</td><td>/books</td><td>save</td></tr><tr class="table-even"><td>GET</td><td>/books/${id}</td><td>show</td></tr><tr class="table-odd"><td>GET</td><td>/books/${id}/edit</td><td>edit</td></tr><tr class="table-even"><td>PUT</td><td>/books/${id}</td><td>update</td></tr><tr class="table-odd"><td>DELETE</td><td>/books/${id}</td><td>delete</td></tr></table><p class="paragraph"/>If you wish to include or exclude any of the generated URL mappings you can do so with the <code>includes</code> or <code>excludes</code> parameter, which accepts the name of the Grails action to include or exclude:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/books"</span>(resources:'book', excludes:['delete', 'update'])<p class="paragraph"/>or<p class="paragraph"/><span class="java-quote">"/books"</span>(resources:'book', includes:['index', 'show'])</pre></div><p class="paragraph"/><h4>Single resources</h4><p class="paragraph"/>A single resource is a resource for which there is only one (possibly per user) in the system. You can create a single resource using the <code>resource</code> parameter (as oppose to <code>resources</code>):<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/book"</span>(resource:'book')</pre></div><p class="paragraph"/>This results in the following URL mappings:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>HTTP Method</th><th>URI</th><th>Grails Action</th></tr><tr class="table-odd"><td>GET</td><td>/book/create</td><td>create</td></tr><tr class="table-even"><td>POST</td><td>/book</td><td>save</td></tr><tr class="table-odd"><td>GET</td><td>/book</td><td>show</td></tr><tr class="table-even"><td>GET</td><td>/book/edit</td><td>edit</td></tr><tr class="table-odd"><td>PUT</td><td>/book</td><td>update</td></tr><tr class="table-even"><td>DELETE</td><td>/book</td><td>delete</td></tr></table><p class="paragraph"/>The main difference is that the id is not included in the URL mapping.<p class="paragraph"/><h4>Nested Resources</h4><p class="paragraph"/>You can nest resource mappings to generate child resources. For example:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/books"</span>(resources:'book') { |
| <span class="java-quote">"/authors"</span>(resources:<span class="java-quote">"author"</span>) |
| }</pre></div><p class="paragraph"/>The above will result in the following URL mappings:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>HTTP Method</th><th>URL</th><th>Grails Action</th></tr><tr class="table-odd"><td>GET</td><td>/books/${bookId}/authors</td><td>index</td></tr><tr class="table-even"><td>GET</td><td>/books/${bookId}/authors/create</td><td>create</td></tr><tr class="table-odd"><td>POST</td><td>/books/${bookId}/authors</td><td>save</td></tr><tr class="table-even"><td>GET</td><td>/books/${bookId}/authors/${id}</td><td>show</td></tr><tr class="table-odd"><td>GET</td><td>/books/${bookId}/authors/edit/${id}</td><td>edit</td></tr><tr class="table-even"><td>PUT</td><td>/books/${bookId}/authors/${id}</td><td>update</td></tr><tr class="table-odd"><td>DELETE</td><td>/books/${bookId}/authors/${id}</td><td>delete</td></tr></table><p class="paragraph"/>You can also nest regular URL mappings within a resource mapping:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/books"</span>(resources: <span class="java-quote">"book"</span>) { |
| <span class="java-quote">"/publisher"</span>(controller:<span class="java-quote">"publisher"</span>) |
| }</pre></div><p class="paragraph"/>This will result in the following URL being available:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>HTTP Method</th><th>URL</th><th>Grails Action</th></tr><tr class="table-odd"><td>GET</td><td>/books/1/publisher</td><td>index</td></tr></table><p class="paragraph"/><h4>Linking to RESTful Mappings</h4><p class="paragraph"/>You can link to any URL mapping created with the <code>g:link</code> tag provided by Grails simply by referencing the controller and action to link to:<p class="paragraph"/><div class="code"><pre><g:link controller=<span class="java-quote">"book"</span> action=<span class="java-quote">"index"</span>>My Link</g:link></pre></div><p class="paragraph"/>As a convenience you can also pass a domain instance to the <code>resource</code> attribute of the <code>link</code> tag:<p class="paragraph"/><div class="code"><pre><g:link resource=<span class="java-quote">"${book}"</span>>My Link</g:link></pre></div><p class="paragraph"/>This will automatically produce the correct link (in this case "/books/1" for an id of "1").<p class="paragraph"/> |
| The case of nested resources is a little different as they typically required two identifiers (the id of the resource and the one it is nested within). For example given the nested resources:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/books"</span>(resources:'book') { |
| <span class="java-quote">"/authors"</span>(resources:<span class="java-quote">"author"</span>) |
| }</pre></div><p class="paragraph"/>If you wished to link to the <code>show</code> action of the <code>author</code> controller, you would write:<p class="paragraph"/><div class="code"><pre>// Results in /books/1/authors/2 |
| <g:link controller=<span class="java-quote">"author"</span> action=<span class="java-quote">"show"</span> method=<span class="java-quote">"GET"</span> params=<span class="java-quote">"[bookId:1]"</span> id=<span class="java-quote">"2"</span>>The Author</g:link></pre></div><p class="paragraph"/>However, to make this more concise there is a <code>resource</code> attribute to the link tag which can be used instead:<p class="paragraph"/><div class="code"><pre>// Results in /books/1/authors/2 |
| <g:link resource=<span class="java-quote">"book/author"</span> action=<span class="java-quote">"show"</span> bookId=<span class="java-quote">"1"</span> id=<span class="java-quote">"2"</span>>My Link</g:link></pre></div><p class="paragraph"/>The resource attribute accepts a path to the resource separated by a slash (in this case "book/author"). The attributes of the tag can be used to specify the necessary <code>bookId</code> parameter. |
| |
| |
| <a name="7.4.2 Redirects In URL Mappings"><!-- Legacy link --></a> |
| <h2 id="redirectMappings">7.4.3 Redirects In URL Mappings</h2> |
| Since Grails 2.3, it is possible to define URL mappings which specify a redirect. |
| When a URL mapping specifies a redirect, any time that mapping matches an incoming |
| request, a redirect is initiated with information provided by the mapping.<p class="paragraph"/>When a URL mapping specifies a redirect the mapping must either supply a String |
| representing a URI to redirect to or must provide a Map representing the target |
| of the redirect. That Map is structured just like the Map that may be passed |
| as an argument to the <code>redirect</code> method in a controller.<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/viewBooks"</span>(redirect: '/books/list') |
| <span class="java-quote">"/viewAuthors"</span>(redirect: [controller: 'author', action: 'list']) |
| <span class="java-quote">"/viewPublishers"</span>(redirect: [controller: 'publisher', action: 'list', permanent: <span class="java-keyword">true</span>])</pre></div><p class="paragraph"/>Request parameters that were part of the original request will be included in the redirect. |
| |
| |
| <a name="7.4.4 Embedded Variables"><!-- Legacy link --></a> |
| <h2 id="embeddedVariables">7.4.4 Embedded Variables</h2> |
| <h4>Simple Variables</h4><p class="paragraph"/>The previous section demonstrated how to map simple URLs with concrete "tokens". In URL mapping speak tokens are the sequence of characters between each slash, '/'. A concrete token is one which is well defined such as as <code>/product</code>. However, in many circumstances you don't know what the value of a particular token will be until runtime. In this case you can use variable placeholders within the URL for example:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/product/$id"</span>(controller: <span class="java-quote">"product"</span>) |
| }</pre></div><p class="paragraph"/>In this case by embedding a $id variable as the second token Grails will automatically map the second token into a parameter (available via the <a href="../ref/Controllers/params.html" class="controllers">params</a> object) called <code>id</code>. For example given the URL <code>/product/MacBook</code>, the following code will render "MacBook" to the response:<p class="paragraph"/><div class="code"><pre>class ProductController { |
| def index() { render params.id } |
| }</pre></div><p class="paragraph"/>You can of course construct more complex examples of mappings. For example the traditional blog URL format could be mapped as follows:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/$blog/$year/$month/$day/$id"</span>(controller: <span class="java-quote">"blog"</span>, action: <span class="java-quote">"show"</span>) |
| }</pre></div><p class="paragraph"/>The above mapping would let you do things like:<p class="paragraph"/><div class="code"><pre>/graemerocher/2007/01/10/my_funky_blog_entry</pre></div><p class="paragraph"/>The individual tokens in the URL would again be mapped into the <a href="../ref/Controllers/params.html" class="controllers">params</a> object with values available for <code>year</code>, <code>month</code>, <code>day</code>, <code>id</code> and so on.<p class="paragraph"/><h4>Dynamic Controller and Action Names</h4><p class="paragraph"/>Variables can also be used to dynamically construct the controller and action name. In fact the default Grails URL mappings use this technique:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/$controller/$action?/$id?"</span>() |
| }</pre></div><p class="paragraph"/>Here the name of the controller, action and id are implicitly obtained from the variables <code>controller</code>, <code>action</code> and <code>id</code> embedded within the URL.<p class="paragraph"/>You can also resolve the controller name and action name to execute dynamically using a closure:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/$controller"</span> { |
| action = { params.goHere } |
| } |
| }</pre></div><p class="paragraph"/><h4>Optional Variables</h4><p class="paragraph"/>Another characteristic of the default mapping is the ability to append a ? at the end of a variable to make it an optional token. In a further example this technique could be applied to the blog URL mapping to have more flexible linking:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/$blog/$year?/$month?/$day?/$id?"</span>(controller:<span class="java-quote">"blog"</span>, action:<span class="java-quote">"show"</span>) |
| }</pre></div><p class="paragraph"/>With this mapping all of these URLs would match with only the relevant parameters being populated in the <a href="../ref/Controllers/params.html" class="controllers">params</a> object:<p class="paragraph"/><pre class="bq"><code> |
| /graemerocher/2007/01/10/my_funky_blog_entry |
| /graemerocher/2007/01/10 |
| /graemerocher/2007/01 |
| /graemerocher/2007 |
| /graemerocher</code></pre><p class="paragraph"/><h4>Optional File Extensions</h4><p class="paragraph"/>If you wish to capture the extension of a particular path, then a special case mapping exists:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/$controller/$action?/$id?(.$format)?"</span>()</pre></div><p class="paragraph"/>By adding the <code>(.$format)?</code> mapping you can access the file extension using the <code>response.format</code> property in a controller:<p class="paragraph"/><div class="code"><pre>def index() { |
| render <span class="java-quote">"extension is ${response.format}"</span> |
| }</pre></div><p class="paragraph"/><h4>Arbitrary Variables</h4><p class="paragraph"/>You can also pass arbitrary parameters from the URL mapping into the controller by just setting them in the block passed to the mapping:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/holiday/win"</span> { |
| id = <span class="java-quote">"Marrakech"</span> |
| year = 2007 |
| }</pre></div><p class="paragraph"/>This variables will be available within the <a href="../ref/Controllers/params.html" class="controllers">params</a> object passed to the controller.<p class="paragraph"/><h4>Dynamically Resolved Variables</h4><p class="paragraph"/>The hard coded arbitrary variables are useful, but sometimes you need to calculate the name of the variable based on runtime factors. This is also possible by assigning a block to the variable name:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/holiday/win"</span> { |
| id = { params.id } |
| isEligible = { session.user != <span class="java-keyword">null</span> } // must be logged in |
| }</pre></div><p class="paragraph"/>In the above case the code within the blocks is resolved when the URL is actually matched and hence can be used in combination with all sorts of logic. |
| |
| |
| <a name="7.4.5 Mapping to Views"><!-- Legacy link --></a> |
| <h2 id="mappingToViews">7.4.5 Mapping to Views</h2> |
| You can resolve a URL to a view without a controller or action involved. For example to map the root URL <code>/</code> to a GSP at the location <code>grails-app/views/index.gsp</code> you could use:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/"</span>(view: <span class="java-quote">"/index"</span>) // map the root URL |
| }</pre></div><p class="paragraph"/>Alternatively if you need a view that is specific to a given controller you could use:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/help"</span>(controller: <span class="java-quote">"site"</span>, view: <span class="java-quote">"help"</span>) // to a view <span class="java-keyword">for</span> a controller |
| }</pre></div> |
| |
| |
| <a name="7.4.6 Mapping to Response Codes"><!-- Legacy link --></a> |
| <h2 id="mappingToResponseCodes">7.4.6 Mapping to Response Codes</h2> |
| Grails also lets you map HTTP response codes to controllers, actions or views. Just use a method name that matches the response code you are interested in:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"403"</span>(controller: <span class="java-quote">"errors"</span>, action: <span class="java-quote">"forbidden"</span>) |
| <span class="java-quote">"404"</span>(controller: <span class="java-quote">"errors"</span>, action: <span class="java-quote">"notFound"</span>) |
| <span class="java-quote">"500"</span>(controller: <span class="java-quote">"errors"</span>, action: <span class="java-quote">"serverError"</span>) |
| }</pre></div><p class="paragraph"/>Or you can specify custom error pages:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"403"</span>(view: <span class="java-quote">"/errors/forbidden"</span>) |
| <span class="java-quote">"404"</span>(view: <span class="java-quote">"/errors/notFound"</span>) |
| <span class="java-quote">"500"</span>(view: <span class="java-quote">"/errors/serverError"</span>) |
| }</pre></div><p class="paragraph"/><h4>Declarative Error Handling</h4><p class="paragraph"/>In addition you can configure handlers for individual exceptions:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"403"</span>(view: <span class="java-quote">"/errors/forbidden"</span>) |
| <span class="java-quote">"404"</span>(view: <span class="java-quote">"/errors/notFound"</span>) |
| <span class="java-quote">"500"</span>(controller: <span class="java-quote">"errors"</span>, action: <span class="java-quote">"illegalArgument"</span>, |
| exception: IllegalArgumentException) |
| <span class="java-quote">"500"</span>(controller: <span class="java-quote">"errors"</span>, action: <span class="java-quote">"nullPointer"</span>, |
| exception: NullPointerException) |
| <span class="java-quote">"500"</span>(controller: <span class="java-quote">"errors"</span>, action: <span class="java-quote">"customException"</span>, |
| exception: MyException) |
| <span class="java-quote">"500"</span>(view: <span class="java-quote">"/errors/serverError"</span>) |
| }</pre></div><p class="paragraph"/>With this configuration, an <code>IllegalArgumentException</code> will be handled by the <code>illegalArgument</code> action in <code>ErrorsController</code>, a <code>NullPointerException</code> will be handled by the <code>nullPointer</code> action, and a <code>MyException</code> will be handled by the <code>customException</code> action. Other exceptions will be handled by the catch-all rule and use the <code>/errors/serverError</code> view.<p class="paragraph"/>You can access the exception from your custom error handing view or controller action using the request's <code>exception</code> attribute like so:<p class="paragraph"/><div class="code"><pre>class ErrorController { |
| def handleError() { |
| def exception = request.exception |
| // perform desired processing to handle the exception |
| } |
| }</pre></div><p class="paragraph"/><blockquote class="warning"> |
| If your error-handling controller action throws an exception as well, you'll end up with a <code>StackOverflowException</code>. |
| </blockquote> |
| |
| |
| <a name="7.4.7 Mapping to HTTP methods"><!-- Legacy link --></a> |
| <h2 id="mappingHTTP">7.4.7 Mapping to HTTP methods</h2> |
| URL mappings can also be configured to map based on the HTTP method (GET, POST, PUT or DELETE). This is very useful for RESTful APIs and for restricting mappings based on HTTP method.<p class="paragraph"/>As an example the following mappings provide a RESTful API URL mappings for the <code>ProductController</code>:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/product/$id"</span>(controller:<span class="java-quote">"product"</span>, action: <span class="java-quote">"update"</span>, method: <span class="java-quote">"PUT"</span>) |
| }</pre></div> |
| |
| <a name="7.4.8 Mapping Wildcards"><!-- Legacy link --></a> |
| <h2 id="mappingWildcards">7.4.8 Mapping Wildcards</h2> |
| Grails' URL mappings mechanism also supports wildcard mappings. For example consider the following mapping:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/images/*.jpg"</span>(controller: <span class="java-quote">"image"</span>) |
| }</pre></div><p class="paragraph"/>This mapping will match all paths to images such as <code>/image/logo.jpg</code>. Of course you can achieve the same effect with a variable:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/images/$name.jpg"</span>(controller: <span class="java-quote">"image"</span>) |
| }</pre></div><p class="paragraph"/>However, you can also use double wildcards to match more than one level below:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/images/**.jpg"</span>(controller: <span class="java-quote">"image"</span>) |
| }</pre></div><p class="paragraph"/>In this cases the mapping will match <code>/image/logo.jpg</code> as well as <code>/image/other/logo.jpg</code>. Even better you can use a double wildcard variable:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| // will match /image/logo.jpg and /image/other/logo.jpg |
| <span class="java-quote">"/images/$name**.jpg"</span>(controller: <span class="java-quote">"image"</span>) |
| }</pre></div><p class="paragraph"/>In this case it will store the path matched by the wildcard inside a <code>name</code> parameter obtainable from the <a href="../ref/Controllers/params.html" class="controllers">params</a> object:<p class="paragraph"/><div class="code"><pre>def name = params.name |
| println name // prints <span class="java-quote">"logo"</span> or <span class="java-quote">"other/logo"</span></pre></div><p class="paragraph"/>If you use wildcard URL mappings then you may want to exclude certain URIs from Grails' URL mapping process. To do this you can provide an <code>excludes</code> setting inside the <code>UrlMappings.groovy</code> class:<p class="paragraph"/><div class="code"><pre>class UrlMappings { |
| <span class="java-keyword">static</span> excludes = [<span class="java-quote">"/images/*"</span>, <span class="java-quote">"/css/*"</span>] |
| <span class="java-keyword">static</span> mappings = { |
| … |
| } |
| }</pre></div><p class="paragraph"/>In this case Grails won't attempt to match any URIs that start with <code>/images</code> or <code>/css</code>. |
| |
| |
| <a name="7.4.9 Automatic Link Re-Writing"><!-- Legacy link --></a> |
| <h2 id="automaticLinkRewriting">7.4.9 Automatic Link Re-Writing</h2> |
| Another great feature of URL mappings is that they automatically customize the behaviour of the <a href="../ref/Tags/link.html" class="tags">link</a> tag so that changing the mappings don't require you to go and change all of your links.<p class="paragraph"/>This is done through a URL re-writing technique that reverse engineers the links from the URL mappings. So given a mapping such as the blog one from an earlier section:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/$blog/$year?/$month?/$day?/$id?"</span>(controller:<span class="java-quote">"blog"</span>, action:<span class="java-quote">"show"</span>) |
| }</pre></div><p class="paragraph"/>If you use the link tag as follows:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:link controller=<span class="xml-quote">"blog"</span> action=<span class="xml-quote">"show"</span> |
| params=<span class="xml-quote">"[blog:'fred', year:2007]"</span>></span> |
| My Blog |
| <span class="xml-tag"></g:link></span><p class="paragraph"/><span class="xml-tag"><g:link controller=<span class="xml-quote">"blog"</span> action=<span class="xml-quote">"show"</span> |
| params=<span class="xml-quote">"[blog:'fred', year:2007, month:10]"</span>></span> |
| My Blog - October 2007 Posts |
| <span class="xml-tag"></g:link></span></pre></div><p class="paragraph"/>Grails will automatically re-write the URL in the correct format:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><a href=<span class="xml-quote">"/fred/2007"</span>></span>My Blog<span class="xml-tag"></a></span> |
| <span class="xml-tag"><a href=<span class="xml-quote">"/fred/2007/10"</span>></span>My Blog - October 2007 Posts<span class="xml-tag"></a></span></pre></div> |
| |
| |
| <a name="7.4.10 Applying Constraints"><!-- Legacy link --></a> |
| <h2 id="applyingConstraints">7.4.10 Applying Constraints</h2> |
| URL Mappings also support Grails' unified <a href="../guide/single.html#constraints" class="guide">validation constraints</a> mechanism, which lets you further "constrain" how a URL is matched. For example, if we revisit the blog sample code from earlier, the mapping currently looks like this:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/$blog/$year?/$month?/$day?/$id?"</span>(controller:<span class="java-quote">"blog"</span>, action:<span class="java-quote">"show"</span>) |
| }</pre></div><p class="paragraph"/>This allows URLs such as:<p class="paragraph"/><div class="code"><pre>/graemerocher/2007/01/10/my_funky_blog_entry</pre></div><p class="paragraph"/>However, it would also allow:<p class="paragraph"/><div class="code"><pre>/graemerocher/not_a_year/not_a_month/not_a_day/my_funky_blog_entry</pre></div><p class="paragraph"/>This is problematic as it forces you to do some clever parsing in the controller code. Luckily, URL Mappings can be constrained to further validate the URL tokens:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/$blog/$year?/$month?/$day?/$id?"</span> { |
| controller = <span class="java-quote">"blog"</span> |
| action = <span class="java-quote">"show"</span> |
| constraints { |
| year(matches:/\d{4}/) |
| month(matches:/\d{2}/) |
| day(matches:/\d{2}/) |
| } |
| }</pre></div><p class="paragraph"/>In this case the constraints ensure that the <code>year</code>, <code>month</code> and <code>day</code> parameters match a particular valid pattern thus relieving you of that burden later on. |
| |
| <a name="7.4.11 Named URL Mappings"><!-- Legacy link --></a> |
| <h2 id="namedMappings">7.4.11 Named URL Mappings</h2> |
| URL Mappings also support named mappings, that is mappings which have a name associated with them. The name may be used to refer to a specific mapping when links are generated.<p class="paragraph"/>The syntax for defining a named mapping is as follows:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| name <mapping name>: <url pattern> { |
| // … |
| } |
| }</pre></div><p class="paragraph"/>For example:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| name personList: <span class="java-quote">"/showPeople"</span> { |
| controller = 'person' |
| action = 'list' |
| } |
| name accountDetails: <span class="java-quote">"/details/$acctNumber"</span> { |
| controller = 'product' |
| action = 'accountDetails' |
| } |
| }</pre></div><p class="paragraph"/>The mapping may be referenced in a link tag in a GSP.<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:link mapping=<span class="xml-quote">"personList"</span>></span>List People<span class="xml-tag"></g:link></span></pre></div><p class="paragraph"/>That would result in:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><a href=<span class="xml-quote">"/showPeople"</span>></span>List People<span class="xml-tag"></a></span></pre></div><p class="paragraph"/>Parameters may be specified using the params attribute.<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:link mapping=<span class="xml-quote">"accountDetails"</span> params=<span class="xml-quote">"[acctNumber:'8675309']"</span>></span> |
| Show Account |
| <span class="xml-tag"></g:link></span></pre></div><p class="paragraph"/>That would result in:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><a href=<span class="xml-quote">"/details/8675309"</span>></span>Show Account<span class="xml-tag"></a></span></pre></div><p class="paragraph"/>Alternatively you may reference a named mapping using the link namespace.<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><link:personList></span>List People<span class="xml-tag"></link:personList></span></pre></div><p class="paragraph"/>That would result in:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><a href=<span class="xml-quote">"/showPeople"</span>></span>List People<span class="xml-tag"></a></span></pre></div><p class="paragraph"/>The link namespace approach allows parameters to be specified as attributes.<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><link:accountDetails acctNumber=<span class="xml-quote">"8675309"</span>></span>Show Account<span class="xml-tag"></link:accountDetails></span></pre></div><p class="paragraph"/>That would result in:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><a href=<span class="xml-quote">"/details/8675309"</span>></span>Show Account<span class="xml-tag"></a></span></pre></div><p class="paragraph"/>To specify attributes that should be applied to the generated <code>href</code>, specify a <code>Map</code> value to the <code>attrs</code> attribute. These attributes will be applied directly to the href, not passed through to be used as request parameters.<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><link:accountDetails attrs=<span class="xml-quote">"[class: 'fancy']"</span> acctNumber=<span class="xml-quote">"8675309"</span>></span> |
| Show Account |
| <span class="xml-tag"></link:accountDetails></span></pre></div><p class="paragraph"/>That would result in:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><a href=<span class="xml-quote">"/details/8675309"</span> class=<span class="xml-quote">"fancy"</span>></span>Show Account<span class="xml-tag"></a></span></pre></div> |
| |
| |
| |
| <h2 id="customizingUrlFormat">7.4.12 Customizing URL Formats</h2> |
| The default URL Mapping mechanism supports camel case names in the URLs. The default URL for accessing an action named <code>addNumbers</code> in a controller named <code>MathHelperController</code> would be something like <code>/mathHelper/addNumbers</code>. Grails allows for the customization of this pattern and provides an implementation which replaces the camel case convention with a hyphenated convention that would support URLs like <code>/math-helper/add-numbers</code>. To enable hyphenated URLs assign a value of "hyphenated" to the <code>grails.web.url.converter</code> property in <code>grails-app/conf/Config.groovy</code>.<p class="paragraph"/><div class="code"><pre>// grails-app/conf/Config.groovy<p class="paragraph"/>grails.web.url.converter = 'hyphenated'</pre></div><p class="paragraph"/>Arbitrary strategies may be plugged in by providing a class which implements the <a href="http://grails.org/doc/3.0.x/api/grails/web/UrlConverter.html" class="api">UrlConverter</a> interface and adding an instance of that class to the Spring application context with the bean name of <code>grails.web.UrlConverter.BEAN_NAME</code>. If Grails finds a bean in the context with that name, it will be used as the default converter and there is no need to assign a value to the <code>grails.web.url.converter</code> config property.<p class="paragraph"/><div class="code"><pre>// src/groovy/com/myapplication/MyUrlConverterImpl.groovy<p class="paragraph"/><span class="java-keyword">package</span> com.myapplication<p class="paragraph"/>class MyUrlConverterImpl <span class="java-keyword">implements</span> grails.web.UrlConverter {<p class="paragraph"/> <span class="java-object">String</span> toUrlElement(<span class="java-object">String</span> propertyOrClassName) { |
| // <span class="java-keyword">return</span> some representation of a property or class name that should be used in URLs… |
| } |
| }</pre></div><p class="paragraph"/><div class="code"><pre>// grails-app/conf/spring/resources.groovy<p class="paragraph"/>beans = { |
| <span class="java-quote">"${grails.web.UrlConverter.BEAN_NAME}"</span>(com.myapplication.MyUrlConverterImpl) |
| }</pre></div> |
| |
| |
| |
| <h2 id="namespacedControllers">7.4.13 Namespaced Controllers</h2> |
| If an application defines multiple controllers with the same name |
| in different packages, the controllers must be defined in a |
| namespace. The way to define a namespace for a controller is to |
| define a static property named <code>namespace</code> in the controller and |
| assign a String to the property that represents the namespace.<p class="paragraph"/><div class="code"><pre>// grails-app/controllers/com/app/reporting/AdminController.groovy |
| <span class="java-keyword">package</span> com.app.reporting<p class="paragraph"/>class AdminController {<p class="paragraph"/> <span class="java-keyword">static</span> namespace = 'reports'<p class="paragraph"/> // … |
| }</pre></div><p class="paragraph"/><div class="code"><pre>// grails-app/controllers/com/app/security/AdminController.groovy |
| <span class="java-keyword">package</span> com.app.security<p class="paragraph"/>class AdminController {<p class="paragraph"/> <span class="java-keyword">static</span> namespace = 'users'<p class="paragraph"/> // … |
| }</pre></div><p class="paragraph"/>When defining url mappings which should be associated with a namespaced |
| controller, the <code>namespace</code> variable needs to be part of the URL mapping.<p class="paragraph"/><div class="code"><pre>// grails-app/conf/UrlMappings.groovy |
| class UrlMappings {<p class="paragraph"/> <span class="java-keyword">static</span> mappings = { |
| '/userAdmin' { |
| controller = 'admin' |
| namespace = 'users' |
| }<p class="paragraph"/> '/reportAdmin' { |
| controller = 'admin' |
| namespace = 'reports' |
| }<p class="paragraph"/> <span class="java-quote">"/$namespace/$controller/$action?"</span>() |
| } |
| }</pre></div><p class="paragraph"/>Reverse URL mappings also require that the <code>namespace</code> be specified.<p class="paragraph"/><div class="code"><pre><g:link controller=<span class="java-quote">"admin"</span> namespace=<span class="java-quote">"reports"</span>>Click For Report Admin</g:link> |
| <g:link controller=<span class="java-quote">"admin"</span> namespace=<span class="java-quote">"users"</span>>Click For User Admin</g:link></pre></div><p class="paragraph"/>When resolving a URL mapping (forward or reverse) to a namespaced controller, |
| a mapping will only match if the <code>namespace</code> has been provided. If |
| the application provides several controllers with the same name in different |
| packages, at most 1 of them may be defined without a <code>namespace</code> property. If |
| there are multiple controllers with the same name that do not define a |
| <code>namespace</code> property, the framework will not know how to distinguish between |
| them for forward or reverse mapping resolutions.<p class="paragraph"/>It is allowed for an application to use a plugin which provides a controller |
| with the same name as a controller provided by the application and for neither |
| of the controllers to define a <code>namespace</code> property as long as the |
| controllers are in separate packages. For example, an application |
| may include a controller named <code>com.accounting.ReportingController</code> |
| and the application may use a plugin which provides a controller |
| named <code>com.humanresources.ReportingController</code>. The only issue |
| with that is the URL mapping for the controller provided by the |
| plugin needs to be explicit in specifying that the mapping applies |
| to the <code>ReportingController</code> which is provided by the plugin.<p class="paragraph"/>See the following example.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/accountingReports"</span> { |
| controller = <span class="java-quote">"reporting"</span> |
| } |
| <span class="java-quote">"/humanResourceReports"</span> { |
| controller = <span class="java-quote">"reporting"</span> |
| plugin = <span class="java-quote">"humanResources"</span> |
| } |
| }</pre></div><p class="paragraph"/>With that mapping in place, a request to <code>/accountingReports</code> will |
| be handled by the <code>ReportingController</code> which is defined in the |
| application. A request to <code>/humanResourceReports</code> will be handled |
| by the <code>ReportingController</code> which is provided by the <code>humanResources</code> |
| plugin.<p class="paragraph"/>There could be any number of <code>ReportingController</code> controllers provided |
| by any number of plugins but no plugin may provide more than one |
| <code>ReportingController</code> even if they are defined in separate packages.<p class="paragraph"/>Assigning a value to the <code>plugin</code> variable in the mapping is only |
| required if there are multiple controllers with the same name |
| available at runtime provided by the application and/or plugins. |
| If the <code>humanResources</code> plugin provides a <code>ReportingController</code> and |
| there is no other <code>ReportingController</code> available at runtime, the |
| following mapping would work.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/humanResourceReports"</span> { |
| controller = <span class="java-quote">"reporting"</span> |
| } |
| }</pre></div><p class="paragraph"/>It is best practice to be explicit about the fact that the controller |
| is being provided by a plugin.<p class="paragraph"/> |
| |
| |
| <a name="7.1.5 Controller Interceptors"><!-- Legacy link --></a> |
| <h2 id="interceptors">7.5 Interceptors</h2> |
| Although Grails <a href="../guide/single.html#controllers" class="guide">controllers</a> support fine grained interceptors, these are only really useful when applied to a few controllers and become difficult to manage with larger applications.<p class="paragraph"/>To solve this you can create standalone Interceptors using the <a href="../ref/Command Line/create-interceptor.html" class="commandLine">create-interceptor</a> command:<p class="paragraph"/> <div class="code"><pre>$ grails create-interceptor MyInterceptor</pre></div><p class="paragraph"/>The above command will create an Interceptor in the <code>grails-app/controllers</code> directory with the following default contents:<p class="paragraph"/><div class="code"><pre>class MyInterceptor {<p class="paragraph"/> <span class="java-object">boolean</span> before() { <span class="java-keyword">true</span> }<p class="paragraph"/> <span class="java-object">boolean</span> after() { <span class="java-keyword">true</span> }<p class="paragraph"/> void afterView() { |
| // no-op |
| }<p class="paragraph"/>}</pre></div><p class="paragraph"/><h4>Interceptors vs Filters</h4><p class="paragraph"/>In versions of Grails prior to Grails 3.0, Grails supported the notion of filters. These are still supported for backwards compatibility but are considered deprecated.<p class="paragraph"/>The new interceptors concept in Grails 3.0 is superior in a number of ways, most significantly interceptors can using Groovy's <code>CompileStatic</code> annotation to optimize performance (something which is often critical as interceptors can be executed for every request.) |
| |
| |
| |
| <h2 id="definingInterceptors">7.5.1 Defining Interceptors</h2> |
| By default interceptors will match the controller name they apply to be convention. For example if you have an interceptor called <code>BookInterceptor</code> then all requests the actions of the <code>BookController</code> will trigger the interceptor.<p class="paragraph"/>An <code>Interceptor</code> implements the <a href="http://grails.org/doc/3.0.x/api/grails/artefact/Interceptor.html" class="api">Interceptor</a> trait and provides 3 methods that can be used to intercept requests:<p class="paragraph"/><div class="code"><pre>/** |
| * Executed before a matched action |
| * |
| * @<span class="java-keyword">return</span> Whether the action should <span class="java-keyword">continue</span> and execute |
| */ |
| <span class="java-object">boolean</span> before() { <span class="java-keyword">true</span> }<p class="paragraph"/> /** |
| * Executed after the action executes but prior to view rendering |
| * |
| * @<span class="java-keyword">return</span> True <span class="java-keyword">if</span> view rendering should <span class="java-keyword">continue</span>, <span class="java-keyword">false</span> otherwise |
| */ |
| <span class="java-object">boolean</span> after() { <span class="java-keyword">true</span> }<p class="paragraph"/> /** |
| * Executed after view rendering completes |
| */ |
| void afterView() {}</pre></div><p class="paragraph"/>As described above the <code>before</code> method is executed prior to an action and can cancel the execution of the action by returning <code>false</code>.<p class="paragraph"/>The <code>after</code> method is executed after an action executes and can halt view rendering if it returns false. The <code>after</code> method can also modify the view or model using the <code>view</code> and <code>model</code> properties respectively:<p class="paragraph"/><p class="paragraph"/><div class="code"><pre><span class="java-object">boolean</span> after() { |
| model.foo = <span class="java-quote">"bar"</span> // add a <span class="java-keyword">new</span> model attribute called 'foo' |
| view = 'alternate' // render a different view called 'alternate' |
| <span class="java-keyword">true</span> |
| }</pre></div><p class="paragraph"/>The <code>afterView</code> method is executed after view rendering completes and if an exception occurs, the exception is available using the <code>throwable</code> property of the <a href="http://grails.org/doc/3.0.x/api/grails/artefact/Interceptor.html" class="api">Interceptor</a> trait. |
| |
| |
| |
| <h2 id="interceptorMatching">7.5.2 Matching Requests with Inteceptors</h2> |
| As mention in the previous section, by default an interceptor will match only requests to the associated controller by convention. However you can configure the interceptor to match any request using the <code>match</code> or <code>matchAll</code> methods defined in the <a href="http://grails.org/doc/3.0.x/api/grails/artefact/Interceptor.html" class="api">Interceptor API</a>.<p class="paragraph"/>The matching methods return a <a href="http://grails.org/doc/3.0.x/api/grails/interceptors/Matcher.html" class="api">Matcher</a> instance which can be used to configure how the interceptor matches the request.<p class="paragraph"/>For example the following interceptor will match all requests except those to the <code>login</code> controller:<p class="paragraph"/><div class="code"><pre>class AuthInterceptor { |
| AuthInterceptor() { |
| matchAll() |
| .excludes(controller:<span class="java-quote">"login"</span>) |
| }<p class="paragraph"/> <span class="java-object">boolean</span> before() { |
| // perform authentication |
| } |
| }</pre></div><p class="paragraph"/>You can also perform matching using named argument:<p class="paragraph"/> |
| <div class="code"><pre>class LoggingInterceptor { |
| LoggingInterceptor() { |
| match(controller:<span class="java-quote">"book"</span>, action:<span class="java-quote">"show"</span>) // using strings |
| match(controller: ~/(author|publisher)/) // using regex |
| }<p class="paragraph"/> <span class="java-object">boolean</span> before() { |
| … |
| } |
| }</pre></div><p class="paragraph"/>All named arguments accept either a String or a Regex expression. The possible named arguments are: |
| <ul class="star"> |
| <li><code>namespace</code> - The namespace of the controller</li> |
| <li><code>controller</code> - The name of the controller</li> |
| <li><code>action</code> - The name of the action</li> |
| <li><code>method</code> - The HTTP method</li> |
| <li><code>uri</code> - The URI of the request (cannot be used in combination with other arguments)</li> |
| </ul><p class="paragraph"/> |
| |
| |
| <h2 id="interceptorOrdering">7.5.3 Ordering Interceptor Execution</h2> |
| Interceptors can be ordered by defining an <code>order</code> property that defines a priority.<p class="paragraph"/>For example:<p class="paragraph"/><div class="code"><pre>class AuthInterceptor {<p class="paragraph"/> <span class="java-object">int</span> order = HIGHEST_PRECEDENCE<p class="paragraph"/> … |
| }</pre></div><p class="paragraph"/>The default value of the <code>order</code> property is 0.<p class="paragraph"/>The values <code>HIGHEST_PRECEDENCE</code> and <code>LOWEST_PRECEDENCE</code> can be used to define filters that should should run first or last respectively.<p class="paragraph"/>Note that if you write an interceptor that is to be used by others it is better increment or decrement the <code>HIGHEST_PRECEDENCE</code> and <code>LOWEST_PRECEDENCE</code> to allow other interceptors to be inserted before or after the interceptor you are authoring:<p class="paragraph"/><div class="code"><pre><span class="java-object">int</span> order = HIGHEST_PRECEDENCE + 50<p class="paragraph"/>// or<p class="paragraph"/><span class="java-object">int</span> order = LOWEST_PRECEDENCE - 50</pre></div><p class="paragraph"/>To find out the computed order of interceptors you can add a debug logger to <code>logback.groovy</code> as follows:<p class="paragraph"/><div class="code"><pre>logger 'grails.artefact.Interceptor', DEBUG, ['STDOUT'], <span class="java-keyword">false</span></pre></div><p class="paragraph"/>You can override any interceptors default order by using bean override configuration in <code>grails-app/conf/application.yml</code>:<p class="paragraph"/><div class="code"><pre>beans: |
| authInterceptor: |
| order: 50</pre></div><p class="paragraph"/>Or in <code>grails-app/conf/application.groovy</code>:<p class="paragraph"/><div class="code"><pre>beans { |
| authInterceptor { |
| order = 50 |
| } |
| }</pre></div><p class="paragraph"/>Thus giving you complete control over interceptor execution order. |
| |
| |
| <a name="7.8 Content Negotiation"><!-- Legacy link --></a> |
| <h2 id="contentNegotiation">7.6 Content Negotiation</h2> |
| Grails has built in support for <a href="http://en.wikipedia.org/wiki/Content_negotiation" target="blank">Content negotiation</a> using either the HTTP <code>Accept</code> header, an explicit format request parameter or the extension of a mapped URI.<p class="paragraph"/><h4>Configuring Mime Types</h4><p class="paragraph"/>Before you can start dealing with content negotiation you need to tell Grails what content types you wish to support. By default Grails comes configured with a number of different content types within <code>grails-app/conf/Config.groovy</code> using the <code>grails.mime.types</code> setting:<p class="paragraph"/><div class="code"><pre>grails.mime.types = [ // the first one is the <span class="java-keyword">default</span> format |
| all: '*/*', // 'all' maps to '*' or the first available format in withFormat |
| atom: 'application/atom+xml', |
| css: 'text/css', |
| csv: 'text/csv', |
| form: 'application/x-www-form-urlencoded', |
| html: ['text/html','application/xhtml+xml'], |
| js: 'text/javascript', |
| json: ['application/json', 'text/json'], |
| multipartForm: 'multipart/form-data', |
| rss: 'application/rss+xml', |
| text: 'text/plain', |
| hal: ['application/hal+json','application/hal+xml'], |
| xml: ['text/xml', 'application/xml'] |
| ]</pre></div><p class="paragraph"/>The above bit of configuration allows Grails to detect to format of a request containing either the 'text/xml' or 'application/xml' media types as simply 'xml'. You can add your own types by simply adding new entries into the map. |
| The first one is the default format.<p class="paragraph"/><h4>Content Negotiation using the format parameter</h4><p class="paragraph"/>Let's say a controller action can return a resource in a variety of formats: HTML, XML, and JSON. What format will the client get? The easiest and most reliable way for the client to control this is through a <code>format</code> URL parameter.<p class="paragraph"/>So if you, as a browser or some other client, want a resource as XML, you can use a URL like this:<p class="paragraph"/><div class="code"><pre>http://my.domain.org/books?format=xml</pre></div><p class="paragraph"/>The result of this on the server side is a <code>format</code> property on the <code>response</code> object with the value <code>xml</code> . You could code your controller action to return XML based on this property, but you can also make use of the controller-specific <code>withFormat()</code> method:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.converters.JSON |
| <span class="java-keyword">import</span> grails.converters.XML<p class="paragraph"/>class BookController {<p class="paragraph"/> def list() { |
| def books = Book.list()<p class="paragraph"/> withFormat { |
| html bookList: books |
| json { render books as JSON } |
| xml { render books as XML } |
| '*' { render books as JSON } |
| } |
| } |
| }</pre></div><p class="paragraph"/>In this example, Grails will only execute the block inside <code>withFormat()</code> that matches the requested content type. So if the preferred format is <code>html</code> then Grails will execute the <code>html()</code> call only. Each 'block' can either be a map model for the corresponding view (as we are doing for 'html' in the above example) or a closure. The closure can contain any standard action code, for example it can return a model or render content directly.<p class="paragraph"/>When no format matches explicitly, a <code><strong class="bold"></code> (wildcard) block can be used to handle all other formats.<p class="paragraph"/>There is a special format, "all", that is handled differently from the explicit formats. If "all" is specified (normally this happens through the Accept header - see below), then the first block of <code>withFormat()</code> is executed when there isn't a <code></strong></code> (wildcard) block available.<p class="paragraph"/>You should not add an explicit "all" block. In this example, a format of "all" will trigger the <code>html</code> handler (<code>html</code> is the first block and there is no <code>*</code> block). |
| <div class="code"><pre>withFormat { |
| html bookList: books |
| json { render books as JSON } |
| xml { render books as XML } |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| When using <a href="../ref/Controllers/withFormat.html" class="controllers">withFormat</a> make sure it is the last call in your controller action as the return value of the <code>withFormat</code> method is used by the action to dictate what happens next. |
| </blockquote><p class="paragraph"/><h4>Using the Accept header</h4><p class="paragraph"/>Every incoming HTTP request has a special <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html" target="blank">Accept</a> header that defines what media types (or mime types) a client can "accept". In older browsers this is typically:<p class="paragraph"/><div class="code"><pre>*/*</pre></div><p class="paragraph"/>which simply means anything. However, newer browsers send more interesting values such as this one sent by Firefox:<p class="paragraph"/><div class="code"><pre>text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8, image/png, */*;q=0.5</pre></div><p class="paragraph"/>This particular accept header is unhelpful because it indicates that XML is the preferred response format whereas the user is really expecting HTML. That's why Grails ignores the accept header by default for browsers. However, non-browser clients are typically more specific in their requirements and can send accept headers such as<p class="paragraph"/><div class="code"><pre>application/json</pre></div><p class="paragraph"/>As mentioned the default configuration in Grails is to ignore the accept header for browsers. This is done by the configuration setting <code>grails.mime.disable.accept.header.userAgents</code>, which is configured to detect the major rendering engines and ignore their ACCEPT headers. This allows Grails' content negotiation to continue to work for non-browser clients:<p class="paragraph"/><div class="code"><pre>grails.mime.disable.accept.header.userAgents = ['Gecko', 'WebKit', 'Presto', 'Trident']</pre></div><p class="paragraph"/>For example, if it sees the accept header above ('application/json') it will set <code>format</code> to <code>json</code> as you'd expect. And of course this works with the <code>withFormat()</code> method in just the same way as when the <code>format</code> URL parameter is set (although the URL parameter takes precedence).<p class="paragraph"/>An accept header of '*/*' results in a value of <code>all</code> for the <code>format</code> property.<p class="paragraph"/><blockquote class="note"> |
| If the accept header is used but contains no registered content types, Grails will assume a broken browser is making the request and will set the HTML format - note that this is different from how the other content negotiation modes work as those would activate the "all" format! |
| </blockquote><p class="paragraph"/> |
| <h4>Request format vs. Response format</h4><p class="paragraph"/>As of Grails 2.0, there is a separate notion of the <em class="italic">request</em> format and the <em class="italic">response</em> format. The request format is dictated by the <code>CONTENT_TYPE</code> header and is typically used to detect if the incoming request can be parsed into XML or JSON, whilst the response format uses the file extension, format parameter or ACCEPT header to attempt to deliver an appropriate response to the client.<p class="paragraph"/>The <a href="../ref/Controllers/withFormat.html" class="controllers">withFormat</a> available on controllers deals specifically with the response format. If you wish to add logic that deals with the request format then you can do so using a separate <code>withFormat</code> method available on the request:<p class="paragraph"/><div class="code"><pre>request.withFormat { |
| xml { |
| // read XML |
| } |
| json { |
| // read JSON |
| } |
| }</pre></div><p class="paragraph"/><h4>Content Negotiation with the format Request Parameter</h4><p class="paragraph"/>If fiddling with request headers if not your favorite activity you can override the format used by specifying a <code>format</code> request parameter:<p class="paragraph"/><div class="code"><pre>/book/list?format=xml</pre></div><p class="paragraph"/>You can also define this parameter in the <a href="../guide/single.html#urlmappings" class="guide">URL Mappings</a> definition:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/book/list"</span>(controller:<span class="java-quote">"book"</span>, action:<span class="java-quote">"list"</span>) { |
| format = <span class="java-quote">"xml"</span> |
| }</pre></div><p class="paragraph"/><h4>Content Negotiation with URI Extensions</h4><p class="paragraph"/>Grails also supports content negotiation using URI extensions. For example given the following URI:<p class="paragraph"/><div class="code"><pre>/book/list.xml</pre></div><p class="paragraph"/>This works as a result of the default URL Mapping definition which is:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/$controller/$action?/$id?(.$format)?"</span>{</pre></div><p class="paragraph"/>Note the inclusion of the <code>format</code> variable in the path. If you do not wish to use content negotiation via the file extension then simply remove this part of the URL mapping:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/$controller/$action?/$id?"</span>{</pre></div><p class="paragraph"/> |
| <h4>Testing Content Negotiation</h4><p class="paragraph"/>To test content negotiation in a unit or integration test (see the section on <a href="../guide/single.html#testing" class="guide">Testing</a>) you can either manipulate the incoming request headers:<p class="paragraph"/><div class="code"><pre>void testJavascriptOutput() { |
| def controller = <span class="java-keyword">new</span> TestController() |
| controller.request.addHeader <span class="java-quote">"Accept"</span>, |
| <span class="java-quote">"text/javascript, text/html, application/xml, text/xml, */*"</span><p class="paragraph"/> controller.testAction() |
| assertEquals <span class="java-quote">"alert('hello')"</span>, controller.response.contentAsString |
| }</pre></div><p class="paragraph"/>Or you can set the format parameter to achieve a similar effect:<p class="paragraph"/><div class="code"><pre>void testJavascriptOutput() { |
| def controller = <span class="java-keyword">new</span> TestController() |
| controller.params.format = 'js'<p class="paragraph"/> controller.testAction() |
| assertEquals <span class="java-quote">"alert('hello')"</span>, controller.response.contentAsString |
| }</pre></div> |
| |
| |
| |
| <h1 id="traits">8 Traits</h1> |
| <h3>Overview</h3><p class="paragraph"/>Grails provides a number of traits which provide access to properties and behavior that may be accessed from various Grails artefacts as well as arbitrary Groovy classes which are part of a Grails project. Many of these traits are automatically added to Grails artefact classes (like controllers and taglibs, for example) and are easy to add to other classes. |
| |
| |
| |
| <h2 id="traitsprovided">8.1 Traits Provided</h2> |
| <h2>Traits Provided By Grails</h2><p class="paragraph"/>Grails artefacts are automatically augmented with certain traits at compile time.<p class="paragraph"/><h4>Domain Class Traits</h4> |
| <ul class="star"> |
| <li><a href="http://grails.org/doc/3.0.x/api/grails/artefact/DomainClass.html" class="api">grails.artefact.DomainClass</a></li> |
| <li><a href="http://grails.org/doc/3.0.x/api/grails/web/databinding/WebDataBinding.html" class="api">grails.web.databinding.WebDataBinding</a></li> |
| <li>org.grails.datastore.gorm.GormEntity</li> |
| <li>org.grails.datastore.gorm.GormValidateable</li> |
| </ul><p class="paragraph"/><h4>Controller Traits</h4> |
| <ul class="star"> |
| <li><a href="http://grails.org/doc/3.0.x/api/grails/artefact/gsp/TagLibraryInvoker.html" class="api">grails.artefact.gsp.TagLibraryInvoker</a></li> |
| <li><a href="http://grails.org/doc/3.0.x/api/grails/artefact/AsyncController.html" class="api">grails.artefact.AsyncController</a></li> |
| <li><a href="http://grails.org/doc/3.0.x/api/grails/artefact/controller/RestResponder.html" class="api">grails.artefact.controller.RestResponder</a></li> |
| <li><a href="http://grails.org/doc/3.0.x/api/grails/artefact/Controller.html" class="api">grails.artefact.Controller</a></li> |
| </ul><p class="paragraph"/><h4>Interceptor Trait</h4> |
| <ul class="star"> |
| <li><a href="http://grails.org/doc/3.0.x/api/grails/artefact/Interceptor.html" class="api">grails.artefact.Interceptor</a></li> |
| </ul><p class="paragraph"/><h4>Tag Library Trait</h4> |
| <ul class="star"> |
| <li><a href="http://grails.org/doc/3.0.x/api/grails/artefact/TagLibrary.html" class="api">grails.artefact.TagLibrary</a></li> |
| </ul><p class="paragraph"/><h4>Service Trait</h4> |
| <ul class="star"> |
| <li><a href="http://grails.org/doc/3.0.x/api/grails/artefact/Service.html" class="api">grails.artefact.Service</a></li> |
| </ul><p class="paragraph"/>Below is a list of other traits provided by the framework. The javadocs provide more detail about methods and properties related to each trait.<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th><strong class="bold">Trait</strong></th><th><strong class="bold">Brief Description</strong></th></tr><tr class="table-odd"><td><a href="http://grails.org/doc/3.0.x/api/grails/web/api/WebAttributes.html" class="api">grails.web.api.WebAttributes</a></td><td>Common Web Attributes</td></tr><tr class="table-even"><td><a href="http://grails.org/doc/3.0.x/api/grails/web/api/ServletAttributes.html" class="api">grails.web.api.ServletAttributes</a></td><td>Servlet API Attributes</td></tr><tr class="table-odd"><td><a href="http://grails.org/doc/3.0.x/api/grails/web/databinding/DataBinder.html" class="api">grails.web.databinding.DataBinder</a></td><td>Data Binding API</td></tr><tr class="table-even"><td><a href="http://grails.org/doc/3.0.x/api/grails/artefact/controller/support/RequestForwarder.html" class="api">grails.artefact.controller.support.RequestForwarder</a></td><td>Request Forwarding API</td></tr><tr class="table-odd"><td><a href="http://grails.org/doc/3.0.x/api/grails/artefact/controller/support/ResponseRedirector.html" class="api">grails.artefact.controller.support.ResponseRedirector</a></td><td>Response Redirecting API</td></tr><tr class="table-even"><td><a href="http://grails.org/doc/3.0.x/api/grails/artefact/controller/support/ResponseRenderer.html" class="api">grails.artefact.controller.support.ResponseRenderer</a></td><td>Response Rendering API</td></tr><tr class="table-odd"><td><a href="http://grails.org/doc/3.0.x/api/grails/validation/Validateable.html" class="api">grails.validation.Validateable</a></td><td>Validation API</td></tr></table> |
| |
| |
| |
| <h2 id="example">8.1.1 WebAttributes Trait Example</h2> |
| <a href="http://grails.org/doc/3.0.x/api/grails/web/api/WebAttributes.html" class="api">WebAttributes</a> is one of the traits provided by the framework. Any Groovy class may implement this trait to inherit all of the properties and behaviors provided by the trait.<p class="paragraph"/><div class="code"><pre>// src/main/groovy/demo/Helper.groovy |
| <span class="java-keyword">package</span> demo<p class="paragraph"/><span class="java-keyword">import</span> grails.web.api.WebAttributes<p class="paragraph"/>class Helper <span class="java-keyword">implements</span> WebAttributes {<p class="paragraph"/> List<<span class="java-object">String</span>> getControllerNames() { |
| // There is no need to pass grailsApplication as an argument |
| // or otherwise inject the grailsApplication property. The |
| // WebAttributes trait provides access to grailsApplication. |
| grailsApplication.getArtefacts('Controller')*.name |
| } |
| }</pre></div><p class="paragraph"/>The traits are compatible with static compilation...<p class="paragraph"/><div class="code"><pre>// src/main/groovy/demo/Helper.groovy |
| <span class="java-keyword">package</span> demo<p class="paragraph"/><span class="java-keyword">import</span> grails.web.api.WebAttributes |
| <span class="java-keyword">import</span> groovy.transform.CompileStatic<p class="paragraph"/>@CompileStatic |
| class Helper <span class="java-keyword">implements</span> WebAttributes {<p class="paragraph"/> List<<span class="java-object">String</span>> getControllerNames() { |
| // There is no need to pass grailsApplication as an argument |
| // or otherwise inject the grailsApplication property. The |
| // WebAttributes trait provides access to grailsApplication. |
| grailsApplication.getArtefacts('Controller')*.name |
| } |
| }</pre></div> |
| |
| |
| <a name="8. Web Services"><!-- Legacy link --></a> |
| <h1 id="webServices">9 Web Services</h1> |
| Web Services are all about providing a web API onto your web application and are typically implemented in either <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer" target="blank">REST</a> or <a href="http://en.wikipedia.org/wiki/SOAP." target="blank">SOAP</a> |
| |
| |
| <a name="8.1 REST"><!-- Legacy link --></a> |
| <h2 id="REST">9.1 REST</h2> |
| REST is not really a technology in itself, but more an architectural pattern. REST is very simple and just involves using plain XML or JSON as a communication medium, combined with URL patterns that are "representational" of the underlying system, and HTTP methods such as GET, PUT, POST and DELETE.<p class="paragraph"/>Each HTTP method maps to an action type. For example GET for retrieving data, POST for creating data, PUT for updating and so on.<p class="paragraph"/>Grails includes flexible features that make it easy to create RESTful APIs. Creating a RESTful resource can be as simple as one line of code, as demonstrated in the next section. |
| |
| |
| <h2 id="domainResources">9.1.1 Domain classes as REST resources</h2> |
| The easiest way to create a RESTful API in Grails is to expose a domain class as a REST resource. This can be done by adding the <code>grails.rest.Resource</code> transformation to any domain class:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.<span class="java-keyword">rest</span>.*<p class="paragraph"/>@Resource(uri='/books') |
| class Book {<p class="paragraph"/> <span class="java-object">String</span> title<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| title blank:<span class="java-keyword">false</span> |
| } |
| }</pre></div><p class="paragraph"/>Simply by adding the <code>Resource</code> transformation and specifying a URI, your domain class will automatically be available as a REST resource in either XML or JSON formats. The transformation will automatically register the necessary <a href="../guide/single.html#restfulMappings" class="guide">RESTful URL mapping</a> and create a controller called <code>BookController</code>.<p class="paragraph"/>You can try it out by adding some test data to <code>BootStrap.groovy</code>:<p class="paragraph"/><div class="code"><pre>def init = { servletContext -><p class="paragraph"/> <span class="java-keyword">new</span> Book(title:<span class="java-quote">"The Stand"</span>).save() |
| <span class="java-keyword">new</span> Book(title:<span class="java-quote">"The Shining"</span>).save() |
| }</pre></div><p class="paragraph"/>And then hitting the URL http://localhost:8080/myapp/books/1, which will render the response like:<p class="paragraph"/><div class="code"><pre><?xml version=<span class="java-quote">"1.0"</span> encoding=<span class="java-quote">"UTF-8"</span>?> |
| <book id=<span class="java-quote">"1"</span>> |
| <title>The Stand</title> |
| </book></pre></div><p class="paragraph"/>If you change the URL to <code>http://localhost:8080/myapp/books/1.json</code> you will get a JSON response such as:<p class="paragraph"/> |
| <div class="code"><pre>{<span class="java-quote">"id"</span>:1,<span class="java-quote">"title"</span>:<span class="java-quote">"The Stand"</span>}</pre></div><p class="paragraph"/>If you wish to change the default to return JSON instead of XML, you can do this by setting the <code>formats</code> attribute of the <code>Resource</code> transformation:<p class="paragraph"/> <div class="code"><pre><span class="java-keyword">import</span> grails.<span class="java-keyword">rest</span>.*<p class="paragraph"/>@Resource(uri='/books', formats=['json', 'xml']) |
| class Book { |
| … |
| }</pre></div><p class="paragraph"/>With the above example JSON will be prioritized. The list that is passed should contain the names of the formats that the resource should expose. The names of formats are defined in the <code>grails.mime.types</code> setting of <code>Config.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.mime.types = [ |
| … |
| json: ['application/json', 'text/json'], |
| … |
| xml: ['text/xml', 'application/xml'] |
| ]</pre></div><p class="paragraph"/>See the section on <a href="../guide/single.html#contentNegotiation" class="guide">Configuring Mime Types</a> in the user guide for more information.<p class="paragraph"/>Instead of using the file extension in the URI, you can also obtain a JSON response using the ACCEPT header. Here's an example using the Unix <code>curl</code> tool:<p class="paragraph"/><div class="code"><pre>$ curl -i -H <span class="java-quote">"Accept: application/json"</span> localhost:8080/myapp/books/1 |
| {<span class="java-quote">"id"</span>:1,<span class="java-quote">"title"</span>:<span class="java-quote">"The Stand"</span>}</pre></div><p class="paragraph"/>This works thanks to Grails' <a href="../guide/single.html#contentNegotiation" class="guide">Content Negotiation</a> features.<p class="paragraph"/>You can create a new resource by issuing a <code>POST</code> request:<p class="paragraph"/><div class="code"><pre>$ curl -i -X POST -H <span class="java-quote">"Content-Type: application/json"</span> -d '{<span class="java-quote">"title"</span>:<span class="java-quote">"Along Came A Spider"</span>}' localhost:8080/myapp/books |
| HTTP/1.1 201 Created |
| Server: Apache-Coyote/1.1 |
| ...</pre></div><p class="paragraph"/>Updating can be done with a <code>PUT</code> request:<p class="paragraph"/><div class="code"><pre>$ curl -i -X PUT -H <span class="java-quote">"Content-Type: application/json"</span> -d '{<span class="java-quote">"title"</span>:<span class="java-quote">"Along Came A Spider"</span>}' localhost:8080/myapp/books/1 |
| HTTP/1.1 200 OK |
| Server: Apache-Coyote/1.1 |
| ...</pre></div><p class="paragraph"/>Finally a resource can be deleted with <code>DELETE</code> request:<p class="paragraph"/><div class="code"><pre>$ curl -i -X DELETE localhost:8080/myapp/books/1 |
| HTTP/1.1 204 No Content |
| Server: Apache-Coyote/1.1 |
| ...</pre></div><p class="paragraph"/>As you can see, the <code>Resource</code> transformation enables all of the HTTP method verbs on the resource. You can enable only read-only capabilities by setting the <code>readOnly</code> attribute to true:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.<span class="java-keyword">rest</span>.*<p class="paragraph"/>@Resource(uri='/books', readOnly=<span class="java-keyword">true</span>) |
| class Book { |
| … |
| }</pre></div><p class="paragraph"/>In this case POST, PUT and DELETE requests will be forbidden. |
| |
| |
| |
| <h2 id="urlMappings">9.1.2 Mapping to REST resources</h2> |
| If you prefer to keep the declaration of the URL mapping in your <code>UrlMappings.groovy</code> file then simply removing the <code>uri</code> attribute of the <code>Resource</code> transformation and adding the following line to <code>UrlMappings.groovy</code> will suffice:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/books"</span>(resources:<span class="java-quote">"book"</span>)</pre></div><p class="paragraph"/>Extending your API to include more end points then becomes trivial:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/books"</span>(resources:<span class="java-quote">"book"</span>) { |
| <span class="java-quote">"/publisher"</span>(controller:<span class="java-quote">"publisher"</span>, method:<span class="java-quote">"GET"</span>) |
| }</pre></div><p class="paragraph"/>The above example will expose the URI <code>/books/1/publisher</code>.<p class="paragraph"/>A more detailed explanation on <a href="../guide/single.html#restfulMappings" class="guide">creating RESTful URL mappings</a> can be found in the <a href="../guide/single.html#urlMappings" class="guide">URL Mappings section</a> of the user guide. |
| |
| |
| <h2 id="linkingToResources">9.1.3 Linking to REST resources</h2> |
| The <code>link</code> tag offers an easy way to link to any domain class resource:<p class="paragraph"/><div class="code"><pre><g:link resource=<span class="java-quote">"${book}"</span>>My Link</g:link></pre></div><p class="paragraph"/>However, currently you cannot use g:link to link to the DELETE action and most browsers do not support sending the DELETE method directly.<p class="paragraph"/>The best way to accomplish this is to use a form submit:<p class="paragraph"/><div class="code"><pre><form action=<span class="java-quote">"/book/2"</span> method=<span class="java-quote">"post"</span>> |
| <input type=<span class="java-quote">"hidden"</span> name=<span class="java-quote">"_method"</span> value=<span class="java-quote">"DELETE"</span>/> |
| </form></pre></div><p class="paragraph"/>Grails supports overriding the request method via the hidden _method parameter. This is for browser compatibility purposes. This is useful when using restful resource mappings to create powerful web interfaces. |
| To make a link fire this type of event, perhaps capture all click events for links with a `data-method` attribute and issue a form submit via javascript. |
| |
| |
| |
| <h2 id="versioningResources">9.1.4 Versioning REST resources</h2> |
| A common requirement with a REST API is to expose different versions at the same time. There are a few ways this can be achieved in Grails.<p class="paragraph"/><h4>Versioning using the URI</h4><p class="paragraph"/>A common approach is to use the URI to version APIs (although this approach is discouraged in favour of Hypermedia). For example, you can define the following URL mappings:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/books/v1"</span>(resources:<span class="java-quote">"book"</span>, namespace:'v1') |
| <span class="java-quote">"/books/v2"</span>(resources:<span class="java-quote">"book"</span>, namespace:'v2')</pre></div><p class="paragraph"/>That will match the following controllers:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> myapp.v1<p class="paragraph"/>class BookController { |
| <span class="java-keyword">static</span> namespace = 'v1' |
| }<p class="paragraph"/><span class="java-keyword">package</span> myapp.v2<p class="paragraph"/>class BookController { |
| <span class="java-keyword">static</span> namespace = 'v2' |
| }</pre></div><p class="paragraph"/>This approach has the disadvantage of requiring two different URI namespaces for your API.<p class="paragraph"/><h4>Versioning with the Accept-Version header</h4><p class="paragraph"/>As an alternative Grails supports the passing of an <code>Accept-Version</code> header from clients. For example you can define the following URL mappings:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/books"</span>(version:'1.0', resources:<span class="java-quote">"book"</span>, namespace:'v1') |
| <span class="java-quote">"/books"</span>(version:'2.0', resources:<span class="java-quote">"book"</span>, namespace:'v2')</pre></div><p class="paragraph"/> |
| Then in the client simply pass which version you need using the <code>Accept-Version</code> header:<p class="paragraph"/><div class="code"><pre>$ curl -i -H <span class="java-quote">"Accept-Version: 1.0"</span> -X GET http://localhost:8080/myapp/books</pre></div><p class="paragraph"/><h4>Versioning using Hypermedia / Mime Types</h4><p class="paragraph"/>Another approach to versioning is to use Mime Type definitions to declare the version of your custom media types (see the section on "Hypermedia as the Engine of Application State" for more information about Hypermedia concepts). For example, in <code>Config.groovy</code> you can declare a custom Mime Type for your resource that includes a version parameter (the 'v' parameter):<p class="paragraph"/><div class="code"><pre>grails.mime.types = [ |
| all: '*/*', |
| book: <span class="java-quote">"application/vnd.books.org.book+json;v=1.0"</span>, |
| bookv2: <span class="java-quote">"application/vnd.books.org.book+json;v=2.0"</span>, |
| … |
| }</pre></div><p class="paragraph"/><blockquote class="warning"> |
| It is critical that place your new mime types after the 'all' Mime Type because if the Content Type of the request cannot be established then the first entry in the map is used for the response. If you have your new Mime Type at the top then Grails will always try and send back your new Mime Type if the requested Mime Type cannot be established. |
| </blockquote><p class="paragraph"/>Then override the renderer (see the section on "Customizing Response Rendering" for more information on custom renderers) to send back the custom Mime Type in <code>grails-app/conf/spring/resourses.groovy</code>:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.<span class="java-keyword">rest</span>.render.json.* |
| <span class="java-keyword">import</span> grails.web.mime.*<p class="paragraph"/>beans = { |
| bookRendererV1(JsonRenderer, myapp.v1.Book, <span class="java-keyword">new</span> MimeType(<span class="java-quote">"application/vnd.books.org.book+json"</span>, [v:<span class="java-quote">"1.0"</span>])) |
| bookRendererV2(JsonRenderer, myapp.v2.Book, <span class="java-keyword">new</span> MimeType(<span class="java-quote">"application/vnd.books.org.book+json"</span>, [v:<span class="java-quote">"2.0"</span>])) |
| }</pre></div><p class="paragraph"/>Then using the <code>Accept</code> header you can specify which version you need using the Mime Type:<p class="paragraph"/><div class="code"><pre>$ curl -i -H <span class="java-quote">"Accept: application/vnd.books.org.book+json;v=1.0"</span> -X GET http://localhost:8080/myapp/books</pre></div> |
| |
| |
| |
| <h2 id="restfulControllers">9.1.5 Implementing REST controllers</h2> |
| The <code>Resource</code> transformation is a quick way to get started, but typically you'll want to customize the controller logic, the rendering of the response or extend the API to include additional actions. |
| |
| |
| <h2 id="extendingRestfulController">9.1.5.1 Extending the RestfulController super class</h2> |
| The easiest way to get started doing so is to create a new controller for your resource that extends the <code>grails.rest.RestfulController</code> super class. For example:<p class="paragraph"/><div class="code"><pre>class BookController <span class="java-keyword">extends</span> RestfulController { |
| <span class="java-keyword">static</span> responseFormats = ['json', 'xml'] |
| BookController() { |
| <span class="java-keyword">super</span>(Book) |
| } |
| }</pre></div><p class="paragraph"/>To customize any logic you can just override the appropriate action. The following table provides the names of the action names and the URIs they map to:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>HTTP Method</th><th>URI</th><th>Controller Action</th></tr><tr class="table-odd"><td>GET</td><td>/books</td><td>index</td></tr><tr class="table-even"><td>GET</td><td>/books/create</td><td>create</td></tr><tr class="table-odd"><td>POST</td><td>/books</td><td>save</td></tr><tr class="table-even"><td>GET</td><td>/books/${id}</td><td>show</td></tr><tr class="table-odd"><td>GET</td><td>/books/${id}/edit</td><td>edit</td></tr><tr class="table-even"><td>PUT</td><td>/books/${id}</td><td>update</td></tr><tr class="table-odd"><td>DELETE</td><td>/books/${id}</td><td>delete</td></tr></table><p class="paragraph"/><blockquote class="note"> |
| Note that the <code>create</code> and <code>edit</code> actions are only needed if the controller exposes an HTML interface. |
| </blockquote><p class="paragraph"/>As an example, if you have a <a href="../guide/single.html#restfulMappings" class="guide">nested resource</a> then you would typically want to query both the parent and the child identifiers. For example, given the following URL mapping:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/authors"</span>(resources:'author') { |
| <span class="java-quote">"/books"</span>(resources:'book') |
| }</pre></div><p class="paragraph"/>You could implement the nested controller as follows:<p class="paragraph"/><div class="code"><pre>class BookController <span class="java-keyword">extends</span> RestfulController { |
| <span class="java-keyword">static</span> responseFormats = ['json', 'xml'] |
| BookController() { |
| <span class="java-keyword">super</span>(Book) |
| }<p class="paragraph"/> @Override |
| <span class="java-keyword">protected</span> Book queryForResource(Serializable id) { |
| Book.where { |
| id == id && author.id = params.authorId |
| }.find() |
| }<p class="paragraph"/>}</pre></div><p class="paragraph"/>The example above subclasses <code>RestfulController</code> and overrides the protected <code>queryForResource</code> method to customize the query for the resource to take into account the parent resource.<p class="paragraph"/><h4>Customizing Data Binding In A RestfulController Subclass</h4><p class="paragraph"/>The RestfulController class contains code which does data binding for actions like <code>save</code> and <code>update</code>. The class defines a <code>getObjectToBind()</code> method which returns a value which will be used as the source for data binding. For example, the update action does something like this...<p class="paragraph"/><div class="code"><pre>class RestfulController<T> {<p class="paragraph"/> def update() { |
| T instance = // retrieve instance from the database...<p class="paragraph"/> instance.properties = getObjectToBind()<p class="paragraph"/> // … |
| }<p class="paragraph"/> // … |
| }</pre></div><p class="paragraph"/>By default the <code>getObjectToBind()</code> method returns the <a href="../ref/Controllers/request.html" class="controllers">request</a> object. When the <code>request</code> object is used as the binding source, if the request has a body then the body will be parsed and its contents will be used to do the data binding, otherwise the request parameters will be used to do the data binding. Subclasses of RestfulController may override the <code>getObjectToBind()</code> method and return anything that is a valid binding source, including a <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Map.html" class="api">Map</a> or a <a href="http://grails.org/doc/3.0.x/api/org/grails/databinding/DataBindingSource.html" class="api">DataBindingSource</a>. For most use cases binding the request is appropriate but the <code>getObjectToBind()</code> method allows for changing that behavior where desired.<p class="paragraph"/><h4>Using custom subclass of RestfulController with Resource annotation</h4><p class="paragraph"/>You can also customize the behaviour of the controller that backs the Resource annotation.<p class="paragraph"/>The class must provide a constructor that takes a domain class as it's argument. The second constructor is required for supporting Resource annotation with readOnly=true.<p class="paragraph"/>This is a template that can be used for subclassed RestfulController classes used in Resource annotations: |
| <div class="code"><pre>class SubclassRestfulController<T> <span class="java-keyword">extends</span> RestfulController<T> { |
| SubclassRestfulController(<span class="java-object">Class</span><T> domainClass) { |
| <span class="java-keyword">this</span>(domainClass, <span class="java-keyword">false</span>) |
| }<p class="paragraph"/> SubclassRestfulController(<span class="java-object">Class</span><T> domainClass, <span class="java-object">boolean</span> readOnly) { |
| <span class="java-keyword">super</span>(domainClass, readOnly) |
| } |
| }</pre></div><p class="paragraph"/> |
| You can specify the super class of the controller that backs the Resource annotation with the <code>superClass</code> attribute.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.<span class="java-keyword">rest</span>.*<p class="paragraph"/>@Resource(uri='/books', superClass=SubclassRestfulController) |
| class Book {<p class="paragraph"/> <span class="java-object">String</span> title<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| title blank:<span class="java-keyword">false</span> |
| } |
| }</pre></div> |
| |
| |
| |
| <h2 id="restControllersStepByStep">9.1.5.2 Implementing REST Controllers Step by Step</h2> |
| If you don't want to take advantage of the features provided by the <code>RestfulController</code> super class, then you can implement each HTTP verb yourself manually. The first step is to create a controller:<p class="paragraph"/><div class="code"><pre>$ grails create-controller book</pre></div><p class="paragraph"/>Then add some useful imports and enable readOnly by default:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.transaction.* |
| <span class="java-keyword">import</span> <span class="java-keyword">static</span> org.springframework.http.HttpStatus.* |
| <span class="java-keyword">import</span> <span class="java-keyword">static</span> org.springframework.http.HttpMethod.*<p class="paragraph"/>@Transactional(readOnly = <span class="java-keyword">true</span>) |
| class BookController { |
| … |
| }</pre></div><p class="paragraph"/>Recall that each HTTP verb matches a particular Grails action according to the following conventions:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>HTTP Method</th><th>URI</th><th>Controller Action</th></tr><tr class="table-odd"><td>GET</td><td>/books</td><td>index</td></tr><tr class="table-even"><td>GET</td><td>/books/${id}</td><td>show</td></tr><tr class="table-odd"><td>GET</td><td>/books/create</td><td>create</td></tr><tr class="table-even"><td>GET</td><td>/books/${id}/edit</td><td>edit</td></tr><tr class="table-odd"><td>POST</td><td>/books</td><td>save</td></tr><tr class="table-even"><td>PUT</td><td>/books/${id}</td><td>update</td></tr><tr class="table-odd"><td>DELETE</td><td>/books/${id}</td><td>delete</td></tr></table><p class="paragraph"/><blockquote class="note"> |
| The 'create' and 'edit' actions are already required if you plan to implement an HTML interface for the REST resource. They are there in order to render appropriate HTML forms to create and edit a resource. If this is not a requirement they can be discarded. |
| </blockquote><p class="paragraph"/>The key to implementing REST actions is the <a href="../ref/Controllers/respond.html" class="controllers">respond</a> method introduced in Grails 2.3. The <code>respond</code> method tries to produce the most appropriate response for the requested content type (JSON, XML, HTML etc.)<p class="paragraph"/><h4>Implementing the 'index' action</h4><p class="paragraph"/>For example, to implement the <code>index</code> action, simply call the <code>respond</code> method passing the list of objects to respond with:<p class="paragraph"/><div class="code"><pre>def index(<span class="java-object">Integer</span> max) { |
| params.max = <span class="java-object">Math</span>.min(max ?: 10, 100) |
| respond Book.list(params), model:[bookCount: Book.count()] |
| }</pre></div><p class="paragraph"/>Note that in the above example we also use the <code>model</code> argument of the <code>respond</code> method to supply the total count. This is only required if you plan to support pagination via some user interface.<p class="paragraph"/>The <code>respond</code> method will, using <a href="../guide/single.html#contentNegotiation" class="guide">Content Negotiation</a>, attempt to reply with the most appropriate response given the content type requested by the client (via the ACCEPT header or file extension).<p class="paragraph"/>If the content type is established to be HTML then a model will be produced such that the action above would be the equivalent of writing:<p class="paragraph"/><div class="code"><pre>def index(<span class="java-object">Integer</span> max) { |
| params.max = <span class="java-object">Math</span>.min(max ?: 10, 100) |
| [bookList: Book.list(params), bookCount: Book.count()] |
| }</pre></div><p class="paragraph"/>By providing an <code>index.gsp</code> file you can render an appropriate view for the given model. If the content type is something other than HTML then the <code>respond</code> method will attempt to lookup an appropriate <code>grails.rest.render.Renderer</code> instance that is capable of rendering the passed object. This is done by inspecting the <code>grails.rest.render.RendererRegistry</code>.<p class="paragraph"/>By default there are already renderers configured for JSON and XML, to find out how to register a custom renderer see the section on "Customizing Response Rendering".<p class="paragraph"/><h4>Implementing the 'show' action</h4><p class="paragraph"/>The <code>show</code> action, which is used to display and individual resource by id, can be implemented in one line of Groovy code (excluding the method signature):<p class="paragraph"/><div class="code"><pre>def show(Book book) { |
| respond book |
| }</pre></div><p class="paragraph"/>By specifying the domain instance as a parameter to the action Grails will automatically attempt to lookup the domain instance using the <code>id</code> parameter of the request. If the domain instance doesn't exist, then <code>null</code> will be passed into the action. The <code>respond</code> method will return a 404 error if null is passed otherwise once again it will attempt to render an appropriate response. If the format is HTML then an appropriate model will produced. The following action is functionally equivalent to the above action:<p class="paragraph"/><div class="code"><pre>def show(Book book) { |
| <span class="java-keyword">if</span>(book == <span class="java-keyword">null</span>) { |
| render status:404 |
| } |
| <span class="java-keyword">else</span> { |
| <span class="java-keyword">return</span> [book: book] |
| } |
| }</pre></div><p class="paragraph"/><h4>Implementing the 'save' action</h4><p class="paragraph"/>The <code>save</code> action creates new resource representations. To start off, simply define an action that accepts a resource as the first argument and mark it as <code>Transactional</code> with the <code>grails.transaction.Transactional</code> transform:<p class="paragraph"/><div class="code"><pre>@Transactional |
| def save(Book book) { |
| … |
| }</pre></div><p class="paragraph"/>Then the first thing to do is check whether the resource has any <a href="../guide/single.html#validation" class="guide">validation errors</a> and if so respond with the errors:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">if</span>(book.hasErrors()) { |
| respond book.errors, view:'create' |
| } |
| <span class="java-keyword">else</span> { |
| … |
| }</pre></div><p class="paragraph"/>In the case of HTML the 'create' view will be rendered again so the user can correct the invalid input. In the case of other formats (JSON, XML etc.), the errors object itself will be rendered in the appropriate format and a status code of 422 (UNPROCESSABLE_ENTITY) returned.<p class="paragraph"/>If there are no errors then the resource can be saved and an appropriate response sent:<p class="paragraph"/><div class="code"><pre>book.save flush:<span class="java-keyword">true</span> |
| withFormat { |
| html { |
| flash.message = message(code: '<span class="java-keyword">default</span>.created.message', args: [message(code: 'book.label', <span class="java-keyword">default</span>: 'Book'), book.id]) |
| redirect book |
| } |
| '*' { render status: CREATED } |
| }</pre></div><p class="paragraph"/>In the case of HTML a redirect is issued to the originating resource and for other formats a status code of 201 (CREATED) is returned.<p class="paragraph"/><h4>Implementing the 'update' action</h4><p class="paragraph"/> |
| The <code>update</code> action updates an existing resource representations and is largely similar to the <code>save</code> action. First define the method signature:<p class="paragraph"/><div class="code"><pre>@Transactional |
| def update(Book book) { |
| … |
| }</pre></div><p class="paragraph"/>If the resource exists then Grails will load the resource, otherwise null we passed. In the case of null, you should return a 404:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">if</span>(book == <span class="java-keyword">null</span>) { |
| render status: NOT_FOUND |
| } |
| <span class="java-keyword">else</span> { |
| … |
| }</pre></div><p class="paragraph"/>Then once again check for errors <a href="../guide/single.html#validation" class="guide">validation errors</a> and if so respond with the errors:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">if</span>(book.hasErrors()) { |
| respond book.errors, view:'edit' |
| } |
| <span class="java-keyword">else</span> { |
| … |
| }</pre></div><p class="paragraph"/>In the case of HTML the 'edit' view will be rendered again so the user can correct the invalid input. In the case of other formats (JSON, XML etc.) the errors object itself will be rendered in the appropriate format and a status code of 422 (UNPROCESSABLE_ENTITY) returned.<p class="paragraph"/>If there are no errors then the resource can be saved and an appropriate response sent:<p class="paragraph"/><div class="code"><pre>book.save flush:<span class="java-keyword">true</span> |
| withFormat { |
| html { |
| flash.message = message(code: '<span class="java-keyword">default</span>.updated.message', args: [message(code: 'book.label', <span class="java-keyword">default</span>: 'Book'), book.id]) |
| redirect book |
| } |
| '*' { render status: OK } |
| }</pre></div><p class="paragraph"/>In the case of HTML a redirect is issued to the originating resource and for other formats a status code of 200 (OK) is returned.<p class="paragraph"/><h4>Implementing the 'delete' action</h4><p class="paragraph"/>The <code>delete</code> action deletes an existing resource. The implementation is largely similar to the <code>update</code> action, expect the <code>delete()</code> method is called instead:<p class="paragraph"/><div class="code"><pre>book.delete flush:<span class="java-keyword">true</span> |
| withFormat { |
| html { |
| flash.message = message(code: '<span class="java-keyword">default</span>.deleted.message', args: [message(code: 'Book.label', <span class="java-keyword">default</span>: 'Book'), book.id]) |
| redirect action:<span class="java-quote">"index"</span>, method:<span class="java-quote">"GET"</span> |
| } |
| '*'{ render status: NO_CONTENT } |
| }</pre></div><p class="paragraph"/>Notice that for an HTML response a redirect is issued back to the <code>index</code> action, whilst for other content types a response code 204 (NO_CONTENT) is returned.<p class="paragraph"/> |
| |
| |
| |
| <h2 id="generatingRestControllers">9.1.5.3 Generating a REST controller using scaffolding</h2> |
| To see some of these concepts in action and help you get going the <a href="http://grails.org/plugin/scaffolding" target="blank">Scaffolding plugin</a>, version 2.0 and above, can generate a REST ready controller for you, simply run the command:<p class="paragraph"/><div class="code"><pre>$ grails generate-controller [Domain <span class="java-object">Class</span> Name]</pre></div> |
| |
| |
| <h2 id="renderers">9.1.6 Customizing Response Rendering</h2> |
| There are several ways to customize response rendering in Grails. |
| |
| |
| |
| <h2 id="defaultRenderers">9.1.6.1 Customizing the Default Renderers</h2> |
| The default renderers for XML and JSON can be found in the <code>grails.rest.render.xml</code> and <code>grails.rest.render.json</code> packages respectively. These use the Grails converters (<code>grails.converters.XML</code> and <code>grails.converters.JSON</code>) by default for response rendering.<p class="paragraph"/>You can easily customize response rendering using these default renderers. A common change you may want to make is to include or exclude certain properties from rendering.<p class="paragraph"/><h4>Including or Excluding Properties from Rendering</h4><p class="paragraph"/>As mentioned previously, Grails maintains a registry of <code>grails.rest.render.Renderer</code> instances. There are some default configured renderers and the ability to register or override renderers for a given domain class or even for a collection of domain classes. To include a particular property from rendering you need to register a custom renderer by defining a bean in <code>grails-app/conf/spring/resources.groovy</code>:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.<span class="java-keyword">rest</span>.render.xml.*<p class="paragraph"/>beans = { |
| bookRenderer(XmlRenderer, Book) { |
| includes = ['title'] |
| } |
| }</pre></div><p class="paragraph"/> |
| <blockquote class="note"> |
| The bean name is not important (Grails will scan the application context for all registered renderer beans), but for organizational and readability purposes it is recommended you name it something meaningful. |
| </blockquote><p class="paragraph"/>To exclude a property, the <code>excludes</code> property of the <code>XmlRenderer</code> class can be used:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.<span class="java-keyword">rest</span>.render.xml.*<p class="paragraph"/>beans = { |
| bookRenderer(XmlRenderer, Book) { |
| excludes = ['isbn'] |
| } |
| }</pre></div><p class="paragraph"/><h4>Customizing the Converters</h4><p class="paragraph"/>As mentioned previously, the default renders use the <code>grails.converters</code> package under the covers. In other words, under the covers they essentially do the following:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.converters.*<p class="paragraph"/>… |
| render book as XML<p class="paragraph"/>// or render book as JSON</pre></div><p class="paragraph"/>Why the separation between converters and renderers? Well a renderer has more flexibility to use whatever rendering technology you chose. When implementing a custom renderer you could use <a href="http://wiki.fasterxml.com/JacksonHome" target="blank">Jackson</a>, <a href="http://code.google.com/p/google-gson/" target="blank">Gson</a> or any Java library to implement the renderer. Converters on the other hand are very much tied to Grails' own marshalling implementation. |
| |
| |
| |
| <h2 id="objectMarshallers">9.1.6.2 Registering Custom Objects Marshallers</h2> |
| Grails' Converters feature the notion of an <a href="http://grails.org/doc/3.0.x/api/org/grails/web/converters/marshaller/ObjectMarshaller.html" class="api">ObjectMarshaller</a> and each type can have a registered <code>ObjectMarshaller</code>. You can register custom <code>ObjectMarshaller</code> instances to completely customize response rendering. For example, you can define the following in <code>BootStrap.init</code>:<p class="paragraph"/><div class="code"><pre>XML.registerObjectMarshaller Book, { Book book, XML xml -> |
| xml.attribute 'id', book.id |
| xml.build { |
| title(book.title) |
| } |
| }</pre></div><p class="paragraph"/>You can customize the formatting of an individual value this way too. For example the <a href="http://grails.org/plugin/jodatime" target="blank">JodaTime plugin</a> does the following to support rendering of JodaTime dates in JSON output:<p class="paragraph"/><div class="code"><pre>JSON.registerObjectMarshaller(DateTime) { |
| <span class="java-keyword">return</span> it?.toString(<span class="java-quote">"yyyy-MM-dd'T'HH:mm:ss'Z'"</span>) |
| }</pre></div><p class="paragraph"/>In the case of JSON it's often simple to use a map to customize output:<p class="paragraph"/><div class="code"><pre>JSON.registerObjectMarshaller(Book) { |
| def map= [:] |
| map['titl'] = it.title |
| map['auth'] = it.author |
| <span class="java-keyword">return</span> map |
| }</pre></div><p class="paragraph"/><h4>Registering Custom Marshallers via Spring</h4><p class="paragraph"/>Note that if you have many custom marshallers it is recommended you split the registration of these into a separate class:<p class="paragraph"/><div class="code"><pre>class CustomMarshallerRegistrar {<p class="paragraph"/> @javax.annotation.PostConstruct |
| void registerMarshallers() { |
| JSON.registerObjectMarshaller(DateTime) { |
| <span class="java-keyword">return</span> it?.toString(<span class="java-quote">"yyyy-MM-dd'T'HH:mm:ss'Z'"</span>) |
| } |
| } |
| }</pre></div><p class="paragraph"/>Then define this class as Spring bean in <code>grails-app/conf/spring/resources.groovy</code>:<p class="paragraph"/><div class="code"><pre>beans = { |
| myCustomMarshallerRegistrar(CustomMarshallerRegistrar) |
| }</pre></div><p class="paragraph"/>The <code>PostConstruct</code> annotation will get triggered on startup of your application. |
| |
| |
| |
| <h2 id="namedObjectMarshallers">9.1.6.3 Using Named Configurations for Object Marshallers</h2> |
| It is also possible to register named configurations. For example:<p class="paragraph"/><div class="code"><pre>XML.createNamedConfig('publicApi') { |
| it.registerObjectMarshaller(Book) { Book book, XML xml -> |
| // <span class="java-keyword">do</span> <span class="java-keyword">public</span> API |
| } |
| } |
| XML.createNamedConfig('adminApi') { |
| it.registerObjectMarshaller(Book) { Book book, XML xml -> |
| // <span class="java-keyword">do</span> admin API |
| } |
| }</pre></div><p class="paragraph"/>Then when you use either the <code>render</code> or <code>respond</code> methods you can wrap the call in a named configuration if necessary to customize rendering per request:<p class="paragraph"/><div class="code"><pre>XML.use( isAdmin ? 'adminApi' : 'publicApi') { |
| render book as XML |
| }</pre></div><p class="paragraph"/>or<p class="paragraph"/><div class="code"><pre>XML.use( isAdmin ? 'adminApi' : 'publicApi') { |
| respond book |
| }</pre></div> |
| |
| |
| <h2 id="objectMarshallerInterface">9.1.6.4 Implementing the ObjectMarshaller Interface</h2> |
| For more complex marshallers it is recommended you implement the <a href="http://grails.org/doc/3.0.x/api/org/grails/web/converters/marshaller/ObjectMarshaller.html" class="api">ObjectMarshaller</a> interface. For example given a domain class:<p class="paragraph"/><div class="code"><pre>class Book { |
| <span class="java-object">String</span> title |
| }</pre></div><p class="paragraph"/>By default the output when using:<p class="paragraph"/><div class="code"><pre>render book as XML</pre></div><p class="paragraph"/>Would look like:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><book id=<span class="xml-quote">"1"</span>></span> |
| <span class="xml-tag"><title></span>The Stand<span class="xml-tag"></title></span> |
| <span class="xml-tag"></book></span></pre></div><p class="paragraph"/>To write a custom marshaller you can do the following:<p class="paragraph"/><div class="code"><pre>class BookMarshaller <span class="java-keyword">implements</span> ObjectMarshaller<XML> {<p class="paragraph"/> <span class="java-keyword">public</span> <span class="java-object">boolean</span> supports(<span class="java-object">Object</span> object) { |
| <span class="java-keyword">return</span> object <span class="java-keyword">instanceof</span> Book |
| }<p class="paragraph"/> <span class="java-keyword">public</span> void marshalObject(<span class="java-object">Object</span> object, XML converter) { |
| Book book = (Book)object |
| converter.chars book.title |
| } |
| }</pre></div><p class="paragraph"/>And then register the marshaller with:<p class="paragraph"/><div class="code"><pre>XML.registerObjectMarshaller(<span class="java-keyword">new</span> BookMarshaller())</pre></div><p class="paragraph"/>With the custom <code>ObjectMarshaller</code> in place, the output is now:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><book></span>The Stand<span class="xml-tag"></book></span></pre></div><p class="paragraph"/><h4>Customizing the Name of the Root Element</h4><p class="paragraph"/>If you wish the customize the name of the surrounding element, you can implement <a href="http://grails.org/doc/3.0.x/api/org/grails/web/converters/marshaller/NameAwareMarshaller.html" class="api">NameAwareMarshaller</a>:<p class="paragraph"/><div class="code"><pre>class BookMarshaller <span class="java-keyword">implements</span> ObjectMarshaller<XML>,NameAwareMarshaller {<p class="paragraph"/> ...<p class="paragraph"/> <span class="java-object">String</span> getElementName(<span class="java-object">Object</span> o) { |
| <span class="java-keyword">return</span> 'custom-book' |
| }<p class="paragraph"/>}</pre></div><p class="paragraph"/>With the above change the output would now be:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><custom-book></span>The Stand<span class="xml-tag"></custom-book></span></pre></div><p class="paragraph"/><h4>Outputting Markup Using the Converters API or Builder</h4><p class="paragraph"/>With the passed Converter object you can explicitly code to the Converters API to stream markup to the response:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">public</span> void marshalObject(<span class="java-object">Object</span> object, XML converter) { |
| Book book = (Book)object<p class="paragraph"/> converter.attribute 'id', book.id.toString() |
| converter.attribute 'date-released', book.dateReleased.toString()<p class="paragraph"/> converter.startNode 'title' |
| converter.chars book.title |
| converter.end()<p class="paragraph"/>}</pre></div><p class="paragraph"/>The above code results in:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><book id=<span class="xml-quote">"1"</span> date-released=<span class="xml-quote">"..."</span>></span> |
| <span class="xml-tag"><title></span>The Stand<span class="xml-tag"></title></span> |
| <span class="xml-tag"></book></span></pre></div><p class="paragraph"/>You can also use a builder notation to achieve a similar result (although the builder notation does not work for <code>CompileStatic</code>):<p class="paragraph"/><div class="code"><pre><span class="java-keyword">public</span> void marshalObject(<span class="java-object">Object</span> object, XML converter) { |
| Book b = (Book)object<p class="paragraph"/> converter.build { |
| book(id: b.id) { |
| title b.title |
| } |
| } |
| }</pre></div><p class="paragraph"/><h4>Using the convertAnother Method to Recursively Convert Objects</h4><p class="paragraph"/>To create more complex responses you can use the <code>convertAnother</code> method to convert associations and other objects:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">public</span> void marshalObject(<span class="java-object">Object</span> object, XML converter) { |
| Book book = (Book)object<p class="paragraph"/> converter.startNode 'title' |
| converter.chars book.title |
| converter.end()<p class="paragraph"/> <span class="java-keyword">if</span> (book.authors) { |
| converter.startNode 'authors' |
| <span class="java-keyword">for</span>(author in book.authors) { |
| converter.convertAnother author |
| } |
| converter.end() |
| } |
| }</pre></div> |
| |
| |
| |
| <h2 id="customRenderers">9.1.6.5 Implementing a Custom Renderer</h2> |
| If you want even more control of the rendering or prefer to use your own marshalling techniques then you can implement your own <code>Renderer</code> instance. For example below is a simple implementation that customizes the rendering of the <code>Book</code> class:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> myapp |
| <span class="java-keyword">import</span> grails.<span class="java-keyword">rest</span>.render.* |
| <span class="java-keyword">import</span> grails.web.mime.MimeType<p class="paragraph"/>class BookXmlRenderer <span class="java-keyword">extends</span> AbstractRenderer<Book> { |
| BookXmlRenderer() { |
| <span class="java-keyword">super</span>(Book, [MimeType.XML,MimeType.TEXT_XML] as MimeType[]) |
| }<p class="paragraph"/> void render(Book object, RenderContext context) { |
| context.contentType = MimeType.XML.name<p class="paragraph"/> def xml = <span class="java-keyword">new</span> groovy.xml.MarkupBuilder(context.writer) |
| xml.book(id: object.id, title:object.title) |
| } |
| }</pre></div><p class="paragraph"/>The <code>AbstractRenderer</code> super class has a constructor that takes the class that it renders and the <code>MimeType</code>(s) that are accepted (via the ACCEPT header or file extension) for the renderer.<p class="paragraph"/>To configure this renderer, simply add it is a bean to <code>grails-app/conf/spring/resources.groovy</code>:<p class="paragraph"/><div class="code"><pre>beans = { |
| bookRenderer(myapp.BookXmlRenderer) |
| }</pre></div><p class="paragraph"/>The result will be that all <code>Book</code> instances will be rendered in the following format:<p class="paragraph"/><div class="code"><pre><book id=<span class="java-quote">"1"</span> title=<span class="java-quote">"The Stand"</span>/></pre></div><p class="paragraph"/><blockquote class="note"> |
| Note that if you change the rendering to a completely different format like the above, then you also need to change the binding if you plan to support POST and PUT requests. Grails will not automatically know how to bind data from a custom XML format to a domain class otherwise. See the section on "Customizing Binding of Resources" for further information. |
| </blockquote><p class="paragraph"/><h4>Container Renderers</h4><p class="paragraph"/>A <code>grails.rest.render.ContainerRenderer</code> is a renderer that renders responses for containers of objects (lists, maps, collections etc.). The interface is largely the same as the <code>Renderer</code> interface except for the addition of the <code>getComponentType()</code> method, which should return the "contained" type. For example:<p class="paragraph"/><div class="code"><pre>class BookListRenderer <span class="java-keyword">implements</span> ContainerRenderer<List, Book> { |
| <span class="java-object">Class</span><List> getTargetType() { List } |
| <span class="java-object">Class</span><Book> getComponentType() { Book } |
| MimeType[] getMimeTypes() { [ MimeType.XML] as MimeType[] } |
| void render(List object, RenderContext context) { |
| .... |
| } |
| }</pre></div> |
| |
| |
| |
| <h2 id="gspRenderers">9.1.6.6 Using GSP to Customize Rendering</h2> |
| You can also customize rendering on a per action basis using Groovy Server Pages (GSP). For example given the <code>show</code> action mentioned previously:<p class="paragraph"/><div class="code"><pre>def show(Book book) { |
| respond book |
| }</pre></div><p class="paragraph"/>You could supply a <code>show.xml.gsp</code> file to customize the rendering of the XML:<p class="paragraph"/><div class="code"><pre><%@page contentType=<span class="java-quote">"application/xml"</span>%> |
| <book id=<span class="java-quote">"${book.id}"</span> title=<span class="java-quote">"${book.title}"</span>/></pre></div><p class="paragraph"/> |
| |
| |
| <h2 id="hypermedia">9.1.7 Hypermedia as the Engine of Application State</h2> |
| <a href="http://en.wikipedia.org/wiki/HATEOAS" target="blank">HATEOS</a>, an abbreviation for Hypermedia as the Engine of Application State, is a common pattern applied to REST architectures that uses hypermedia and linking to define the REST API.<p class="paragraph"/>Hypermedia (also called Mime or Media Types) are used to describe the state of a REST resource, and links tell clients how to transition to the next state. The format of the response is typically JSON or XML, although standard formats such as <a href="http://tools.ietf.org/html/rfc4287" target="blank">Atom</a> and/or <a href="http://stateless.co/hal_specification.html" target="blank">HAL</a> are frequently used. |
| |
| |
| <h2 id="hal">9.1.7.1 HAL Support</h2> |
| <a href="http://stateless.co/hal_specification.html" target="blank">HAL</a> is a standard exchange format commonly used when developing REST APIs that follow HATEOAS principals. An example HAL document representing a list of orders can be seen below:<p class="paragraph"/><div class="code"><pre>{ |
| <span class="java-quote">"_links"</span>: { |
| <span class="java-quote">"self"</span>: { <span class="java-quote">"href"</span>: <span class="java-quote">"/orders"</span> }, |
| <span class="java-quote">"next"</span>: { <span class="java-quote">"href"</span>: <span class="java-quote">"/orders?page=2"</span> }, |
| <span class="java-quote">"find"</span>: { |
| <span class="java-quote">"href"</span>: <span class="java-quote">"/orders{?id}"</span>, |
| <span class="java-quote">"templated"</span>: <span class="java-keyword">true</span> |
| }, |
| <span class="java-quote">"admin"</span>: [{ |
| <span class="java-quote">"href"</span>: <span class="java-quote">"/admins/2"</span>, |
| <span class="java-quote">"title"</span>: <span class="java-quote">"Fred"</span> |
| }, { |
| <span class="java-quote">"href"</span>: <span class="java-quote">"/admins/5"</span>, |
| <span class="java-quote">"title"</span>: <span class="java-quote">"Kate"</span> |
| }] |
| }, |
| <span class="java-quote">"currentlyProcessing"</span>: 14, |
| <span class="java-quote">"shippedToday"</span>: 20, |
| <span class="java-quote">"_embedded"</span>: { |
| <span class="java-quote">"order"</span>: [{ |
| <span class="java-quote">"_links"</span>: { |
| <span class="java-quote">"self"</span>: { <span class="java-quote">"href"</span>: <span class="java-quote">"/orders/123"</span> }, |
| <span class="java-quote">"basket"</span>: { <span class="java-quote">"href"</span>: <span class="java-quote">"/baskets/98712"</span> }, |
| <span class="java-quote">"customer"</span>: { <span class="java-quote">"href"</span>: <span class="java-quote">"/customers/7809"</span> } |
| }, |
| <span class="java-quote">"total"</span>: 30.00, |
| <span class="java-quote">"currency"</span>: <span class="java-quote">"USD"</span>, |
| <span class="java-quote">"status"</span>: <span class="java-quote">"shipped"</span> |
| }, { |
| <span class="java-quote">"_links"</span>: { |
| <span class="java-quote">"self"</span>: { <span class="java-quote">"href"</span>: <span class="java-quote">"/orders/124"</span> }, |
| <span class="java-quote">"basket"</span>: { <span class="java-quote">"href"</span>: <span class="java-quote">"/baskets/97213"</span> }, |
| <span class="java-quote">"customer"</span>: { <span class="java-quote">"href"</span>: <span class="java-quote">"/customers/12369"</span> } |
| }, |
| <span class="java-quote">"total"</span>: 20.00, |
| <span class="java-quote">"currency"</span>: <span class="java-quote">"USD"</span>, |
| <span class="java-quote">"status"</span>: <span class="java-quote">"processing"</span> |
| }] |
| } |
| }</pre></div><p class="paragraph"/><h4>Exposing Resources Using HAL</h4><p class="paragraph"/>To return HAL instead of regular JSON for a resource you can simply override the renderer in <code>grails-app/conf/spring/resources.groovy</code> with an instance of <code>grails.rest.render.hal.HalJsonRenderer</code> (or <code>HalXmlRenderer</code> for the XML variation):<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.<span class="java-keyword">rest</span>.render.hal.* |
| beans = { |
| halBookRenderer(HalJsonRenderer, <span class="java-keyword">rest</span>.test.Book) |
| }</pre></div><p class="paragraph"/>With the bean in place requesting the HAL content type will return HAL:<p class="paragraph"/><div class="code"><pre>$ curl -i -H <span class="java-quote">"Accept: application/hal+json"</span> http://localhost:8080/myapp/books/1<p class="paragraph"/>HTTP/1.1 200 OK |
| Server: Apache-Coyote/1.1 |
| Content-Type: application/hal+json;charset=ISO-8859-1<p class="paragraph"/>{ |
| <span class="java-quote">"_links"</span>: { |
| <span class="java-quote">"self"</span>: { |
| <span class="java-quote">"href"</span>: <span class="java-quote">"http://localhost:8080/myapp/books/1"</span>, |
| <span class="java-quote">"hreflang"</span>: <span class="java-quote">"en"</span>, |
| <span class="java-quote">"type"</span>: <span class="java-quote">"application/hal+json"</span> |
| } |
| }, |
| <span class="java-quote">"title"</span>: <span class="java-quote">""The Stand""</span> |
| }</pre></div><p class="paragraph"/>To use HAL XML format simply change the renderer:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.<span class="java-keyword">rest</span>.render.hal.* |
| beans = { |
| halBookRenderer(HalXmlRenderer, <span class="java-keyword">rest</span>.test.Book) |
| }</pre></div><p class="paragraph"/><h4>Rendering Collections Using HAL</h4><p class="paragraph"/>To return HAL instead of regular JSON for a list of resources you can simply override the renderer in <code>grails-app/conf/spring/resources.groovy</code> with an instance of <code>grails.rest.render.hal.HalJsonCollectionRenderer</code>:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.<span class="java-keyword">rest</span>.render.hal.* |
| beans = { |
| halBookCollectionRenderer(HalJsonCollectionRenderer, <span class="java-keyword">rest</span>.test.Book) |
| }</pre></div><p class="paragraph"/>With the bean in place requesting the HAL content type will return HAL:<p class="paragraph"/><div class="code"><pre>$ curl -i -H <span class="java-quote">"Accept: application/hal+json"</span> http://localhost:8080/myapp/books |
| HTTP/1.1 200 OK |
| Server: Apache-Coyote/1.1 |
| Content-Type: application/hal+json;charset=UTF-8 |
| Transfer-Encoding: chunked |
| Date: Thu, 17 Oct 2013 02:34:14 GMT<p class="paragraph"/>{ |
| <span class="java-quote">"_links"</span>: { |
| <span class="java-quote">"self"</span>: { |
| <span class="java-quote">"href"</span>: <span class="java-quote">"http://localhost:8080/myapp/books"</span>, |
| <span class="java-quote">"hreflang"</span>: <span class="java-quote">"en"</span>, |
| <span class="java-quote">"type"</span>: <span class="java-quote">"application/hal+json"</span> |
| } |
| }, |
| <span class="java-quote">"_embedded"</span>: { |
| <span class="java-quote">"book"</span>: [ |
| { |
| <span class="java-quote">"_links"</span>: { |
| <span class="java-quote">"self"</span>: { |
| <span class="java-quote">"href"</span>: <span class="java-quote">"http://localhost:8080/myapp/books/1"</span>, |
| <span class="java-quote">"hreflang"</span>: <span class="java-quote">"en"</span>, |
| <span class="java-quote">"type"</span>: <span class="java-quote">"application/hal+json"</span> |
| } |
| }, |
| <span class="java-quote">"title"</span>: <span class="java-quote">"The Stand"</span> |
| }, |
| { |
| <span class="java-quote">"_links"</span>: { |
| <span class="java-quote">"self"</span>: { |
| <span class="java-quote">"href"</span>: <span class="java-quote">"http://localhost:8080/myapp/books/2"</span>, |
| <span class="java-quote">"hreflang"</span>: <span class="java-quote">"en"</span>, |
| <span class="java-quote">"type"</span>: <span class="java-quote">"application/hal+json"</span> |
| } |
| }, |
| <span class="java-quote">"title"</span>: <span class="java-quote">"Infinite Jest"</span> |
| }, |
| { |
| <span class="java-quote">"_links"</span>: { |
| <span class="java-quote">"self"</span>: { |
| <span class="java-quote">"href"</span>: <span class="java-quote">"http://localhost:8080/myapp/books/3"</span>, |
| <span class="java-quote">"hreflang"</span>: <span class="java-quote">"en"</span>, |
| <span class="java-quote">"type"</span>: <span class="java-quote">"application/hal+json"</span> |
| } |
| }, |
| <span class="java-quote">"title"</span>: <span class="java-quote">"Walden"</span> |
| } |
| ] |
| } |
| }</pre></div><p class="paragraph"/>Notice that the key associated with the list of <code>Book</code> objects in the rendered JSON is <code>book</code> which is derived from the type of objects in the collection, namely <code>Book</code>. In order to customize the value of this key assign a value to the <code>collectionName</code> property on the <code>HalJsonCollectionRenderer</code> bean as shown below:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.<span class="java-keyword">rest</span>.render.hal.* |
| beans = { |
| halBookCollectionRenderer(HalCollectionJsonRenderer, <span class="java-keyword">rest</span>.test.Book) { |
| collectionName = 'publications' |
| } |
| }</pre></div><p class="paragraph"/>With that in place the rendered HAL will look like the following:<p class="paragraph"/><div class="code"><pre>$ curl -i -H <span class="java-quote">"Accept: application/hal+json"</span> http://localhost:8080/myapp/books |
| HTTP/1.1 200 OK |
| Server: Apache-Coyote/1.1 |
| Content-Type: application/hal+json;charset=UTF-8 |
| Transfer-Encoding: chunked |
| Date: Thu, 17 Oct 2013 02:34:14 GMT<p class="paragraph"/>{ |
| <span class="java-quote">"_links"</span>: { |
| <span class="java-quote">"self"</span>: { |
| <span class="java-quote">"href"</span>: <span class="java-quote">"http://localhost:8080/myapp/books"</span>, |
| <span class="java-quote">"hreflang"</span>: <span class="java-quote">"en"</span>, |
| <span class="java-quote">"type"</span>: <span class="java-quote">"application/hal+json"</span> |
| } |
| }, |
| <span class="java-quote">"_embedded"</span>: { |
| <span class="java-quote">"publications"</span>: [ |
| { |
| <span class="java-quote">"_links"</span>: { |
| <span class="java-quote">"self"</span>: { |
| <span class="java-quote">"href"</span>: <span class="java-quote">"http://localhost:8080/myapp/books/1"</span>, |
| <span class="java-quote">"hreflang"</span>: <span class="java-quote">"en"</span>, |
| <span class="java-quote">"type"</span>: <span class="java-quote">"application/hal+json"</span> |
| } |
| }, |
| <span class="java-quote">"title"</span>: <span class="java-quote">"The Stand"</span> |
| }, |
| { |
| <span class="java-quote">"_links"</span>: { |
| <span class="java-quote">"self"</span>: { |
| <span class="java-quote">"href"</span>: <span class="java-quote">"http://localhost:8080/myapp/books/2"</span>, |
| <span class="java-quote">"hreflang"</span>: <span class="java-quote">"en"</span>, |
| <span class="java-quote">"type"</span>: <span class="java-quote">"application/hal+json"</span> |
| } |
| }, |
| <span class="java-quote">"title"</span>: <span class="java-quote">"Infinite Jest"</span> |
| }, |
| { |
| <span class="java-quote">"_links"</span>: { |
| <span class="java-quote">"self"</span>: { |
| <span class="java-quote">"href"</span>: <span class="java-quote">"http://localhost:8080/myapp/books/3"</span>, |
| <span class="java-quote">"hreflang"</span>: <span class="java-quote">"en"</span>, |
| <span class="java-quote">"type"</span>: <span class="java-quote">"application/hal+json"</span> |
| } |
| }, |
| <span class="java-quote">"title"</span>: <span class="java-quote">"Walden"</span> |
| } |
| ] |
| } |
| }</pre></div><p class="paragraph"/><h4>Using Custom Media / Mime Types</h4><p class="paragraph"/>If you wish to use a custom Mime Type then you first need to declare the Mime Types in <code>grails-app/conf/Config.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.mime.types = [ |
| all: <span class="java-quote">"*/*"</span>, |
| book: <span class="java-quote">"application/vnd.books.org.book+json"</span>, |
| bookList: <span class="java-quote">"application/vnd.books.org.booklist+json"</span>, |
| … |
| ]</pre></div><p class="paragraph"/><blockquote class="warning"> |
| It is critical that place your new mime types after the 'all' Mime Type because if the Content Type of the request cannot be established then the first entry in the map is used for the response. If you have your new Mime Type at the top then Grails will always try and send back your new Mime Type if the requested Mime Type cannot be established. |
| </blockquote><p class="paragraph"/>Then override the renderer to return HAL using the custom Mime Types:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.<span class="java-keyword">rest</span>.render.hal.* |
| <span class="java-keyword">import</span> grails.web.mime.*<p class="paragraph"/>beans = { |
| halBookRenderer(HalJsonRenderer, <span class="java-keyword">rest</span>.test.Book, <span class="java-keyword">new</span> MimeType(<span class="java-quote">"application/vnd.books.org.book+json"</span>, [v:<span class="java-quote">"1.0"</span>])) |
| halBookListRenderer(HalJsonCollectionRenderer, <span class="java-keyword">rest</span>.test.Book, <span class="java-keyword">new</span> MimeType(<span class="java-quote">"application/vnd.books.org.booklist+json"</span>, [v:<span class="java-quote">"1.0"</span>])) |
| }</pre></div><p class="paragraph"/>In the above example the first bean defines a HAL renderer for a single book instance that returns a Mime Type of <code>application/vnd.books.org.book+json</code>. The second bean defines the Mime Type used to render a collection of books (in this case <code>application/vnd.books.org.booklist+json</code>).<p class="paragraph"/>With this in place issuing a request for the new Mime Type returns the necessary HAL:<p class="paragraph"/><div class="code"><pre>$ curl -i -H <span class="java-quote">"Accept: application/vnd.books.org.book+json"</span> http://localhost:8080/myapp/books/1<p class="paragraph"/>HTTP/1.1 200 OK |
| Server: Apache-Coyote/1.1 |
| Content-Type: application/vnd.books.org.book+json;charset=ISO-8859-1<p class="paragraph"/> |
| { |
| <span class="java-quote">"_links"</span>: { |
| <span class="java-quote">"self"</span>: { |
| <span class="java-quote">"href"</span>: <span class="java-quote">"http://localhost:8080/myapp/books/1"</span>, |
| <span class="java-quote">"hreflang"</span>: <span class="java-quote">"en"</span>, |
| <span class="java-quote">"type"</span>: <span class="java-quote">"application/vnd.books.org.book+json"</span> |
| } |
| }, |
| <span class="java-quote">"title"</span>: <span class="java-quote">""The Stand""</span> |
| }</pre></div><p class="paragraph"/> |
| <h4>Customizing Link Rendering</h4><p class="paragraph"/>An important aspect of HATEOAS is the usage of links that describe the transitions the client can use to interact with the REST API. By default the <code>HalJsonRenderer</code> will automatically create links for you for associations and to the resource itself (using the "self" relationship).<p class="paragraph"/>However you can customize link rendering using the <code>link</code> method that is added to all domain classes annotated with <code>grails.rest.Resource</code> or any class annotated with <code>grails.rest.Linkable</code>. For example, the <code>show</code> action can be modified as follows to provide a new link in the resulting output:<p class="paragraph"/><div class="code"><pre>def show(Book book) { |
| book.link rel:'publisher', href: g.link(resource:<span class="java-quote">"publisher"</span>, params:[bookId: book.id]) |
| respond book |
| }</pre></div><p class="paragraph"/>Which will result in output such as:<p class="paragraph"/><div class="code"><pre>{ |
| <span class="java-quote">"_links"</span>: { |
| <span class="java-quote">"self"</span>: { |
| <span class="java-quote">"href"</span>: <span class="java-quote">"http://localhost:8080/myapp/books/1"</span>, |
| <span class="java-quote">"hreflang"</span>: <span class="java-quote">"en"</span>, |
| <span class="java-quote">"type"</span>: <span class="java-quote">"application/vnd.books.org.book+json"</span> |
| } |
| <span class="java-quote">"publisher"</span>: { |
| <span class="java-quote">"href"</span>: <span class="java-quote">"http://localhost:8080/myapp/books/1/publisher"</span>, |
| <span class="java-quote">"hreflang"</span>: <span class="java-quote">"en"</span> |
| } |
| }, |
| <span class="java-quote">"title"</span>: <span class="java-quote">""The Stand""</span> |
| }</pre></div><p class="paragraph"/>The <code>link</code> method can be passed named arguments that match the properties of the <code>grails.rest.Link</code> class. |
| |
| |
| |
| <h2 id="atom">9.1.7.2 Atom Support</h2> |
| <a href="http://tools.ietf.org/html/rfc4287" target="blank">Atom</a> is another standard interchange format used to implement REST APIs. An example of Atom output can be seen below:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><?xml version=<span class="xml-quote">"1.0"</span> encoding=<span class="xml-quote">"utf-8"</span>?></span> |
| <span class="xml-tag"><feed xmlns=<span class="xml-quote">"http://www.w3.org/2005/Atom"</span>></span><p class="paragraph"/> <span class="xml-tag"><title></span>Example Feed<span class="xml-tag"></title></span> |
| <span class="xml-tag"><link href=<span class="xml-quote">"http://example.org/"</span>/></span> |
| <span class="xml-tag"><updated></span>2003-12-13T18:30:02Z<span class="xml-tag"></updated></span> |
| <span class="xml-tag"><author></span> |
| <span class="xml-tag"><name></span>John Doe<span class="xml-tag"></name></span> |
| <span class="xml-tag"></author></span> |
| <span class="xml-tag"><id></span>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6<span class="xml-tag"></id></span><p class="paragraph"/> <span class="xml-tag"><entry></span> |
| <span class="xml-tag"><title></span>Atom-Powered Robots Run Amok<span class="xml-tag"></title></span> |
| <span class="xml-tag"><link href=<span class="xml-quote">"http://example.org/2003/12/13/atom03"</span>/></span> |
| <span class="xml-tag"><id></span>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a<span class="xml-tag"></id></span> |
| <span class="xml-tag"><updated></span>2003-12-13T18:30:02Z<span class="xml-tag"></updated></span> |
| <span class="xml-tag"><summary></span>Some text.<span class="xml-tag"></summary></span> |
| <span class="xml-tag"></entry></span><p class="paragraph"/><span class="xml-tag"></feed></span></pre></div><p class="paragraph"/>To use Atom rendering again simply define a custom renderer:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.<span class="java-keyword">rest</span>.render.atom.* |
| beans = { |
| halBookRenderer(AtomRenderer, <span class="java-keyword">rest</span>.test.Book) |
| halBookListRenderer(AtomCollectionRenderer, <span class="java-keyword">rest</span>.test.Book) |
| }</pre></div> |
| |
| |
| <h2 id="vndError">9.1.7.3 Vnd.Error Support</h2> |
| <a href="https://github.com/blongden/vnd.error" target="blank">Vnd.Error</a> is a standardised way of expressing an error response.<p class="paragraph"/>By default when a validation error occurs when attempting to POST new resources then the errors object will be sent back allow with a 422 respond code:<p class="paragraph"/><div class="code"><pre>$ curl -i -H <span class="java-quote">"Accept: application/json"</span> -H <span class="java-quote">"Content-Type: application/json"</span> -X POST -d <span class="java-quote">""</span> http://localhost:8080/myapp/books<p class="paragraph"/>HTTP/1.1 422 Unprocessable Entity |
| Server: Apache-Coyote/1.1 |
| Content-Type: application/json;charset=ISO-8859-1<p class="paragraph"/>{<span class="java-quote">"errors"</span>:[{<span class="java-quote">"object"</span>:<span class="java-quote">"<span class="java-keyword">rest</span>.test.Book"</span>, <span class="java-quote">"field"</span>:<span class="java-quote">"title"</span>, <span class="java-quote">"rejected-value"</span>:<span class="java-keyword">null</span>, <span class="java-quote">"message"</span>:<span class="java-quote">"Property [title] of class [class <span class="java-keyword">rest</span>.test.Book] cannot be <span class="java-keyword">null</span>"</span>}]}</pre></div><p class="paragraph"/>If you wish to change the format to Vnd.Error then simply register <code>grails.rest.render.errors.VndErrorJsonRenderer</code> bean in <code>grails-app/conf/spring/resources.groovy</code>:<p class="paragraph"/> |
| <div class="code"><pre>beans = { |
| vndJsonErrorRenderer(grails.<span class="java-keyword">rest</span>.render.errors.VndErrorJsonRenderer) |
| // <span class="java-keyword">for</span> Vnd.Error XML format |
| vndXmlErrorRenderer(grails.<span class="java-keyword">rest</span>.render.errors.VndErrorXmlRenderer) |
| }</pre></div><p class="paragraph"/>Then if you alter the client request to accept Vnd.Error you get an appropriate response:<p class="paragraph"/><div class="code"><pre>$ curl -i -H <span class="java-quote">"Accept: application/vnd.error+json,application/json"</span> -H <span class="java-quote">"Content-Type: application/json"</span> -X POST -d <span class="java-quote">""</span> http://localhost:8080/myapp/books |
| HTTP/1.1 200 OK |
| Server: Apache-Coyote/1.1 |
| Content-Type: application/vnd.error+json;charset=ISO-8859-1<p class="paragraph"/>[ |
| { |
| <span class="java-quote">"logref"</span>: <span class="java-quote">""book.nullable""</span>, |
| <span class="java-quote">"message"</span>: <span class="java-quote">"Property [title] of class [class <span class="java-keyword">rest</span>.test.Book] cannot be <span class="java-keyword">null</span>"</span>, |
| <span class="java-quote">"_links"</span>: { |
| <span class="java-quote">"resource"</span>: { |
| <span class="java-quote">"href"</span>: <span class="java-quote">"http://localhost:8080/<span class="java-keyword">rest</span>-test/books"</span> |
| } |
| } |
| } |
| ]</pre></div> |
| |
| |
| |
| <h2 id="binding">9.1.8 Customizing Binding of Resources</h2> |
| The framework provides a sophisticated but simple mechanism for binding REST requests to domain objects and command objects. One way to take advantage of this is to bind the <code>request</code> property in a controller the <code>properties</code> of a domain class. Given the following XML as the body of the request, the <code>createBook</code> action will create a new <code>Book</code> and assign "The Stand" to the <code>title</code> property and "Stephen King" to the <code>authorName</code> property.<p class="paragraph"/><div class="code"><pre><?xml version=<span class="java-quote">"1.0"</span> encoding=<span class="java-quote">"UTF-8"</span>?> |
| <book> |
| <title>The Stand</title> |
| <authorName>Stephen King</authorName> |
| </book></pre></div><p class="paragraph"/><div class="code"><pre>class BookController {<p class="paragraph"/> def createBook() { |
| def book = <span class="java-keyword">new</span> Book() |
| book.properties = request<p class="paragraph"/> // … |
| } |
| }</pre></div><p class="paragraph"/>If the root element of the XML document contains an <code>id</code> attribute, the <code>id</code> value will be used to retrieve the corresponding persistent instance from the database and then the rest of the document will be bound to the instance. If no corresponding record is found in the database, the command object reference will be null.<p class="paragraph"/><div class="code"><pre><?xml version=<span class="java-quote">"1.0"</span> encoding=<span class="java-quote">"UTF-8"</span>?> |
| <book> |
| <title>The Stand</title> |
| <authorName>Stephen King</authorName> |
| </book></pre></div><p class="paragraph"/>Command objects will automatically be bound with the body of the request:<p class="paragraph"/><div class="code"><pre>class BookController { |
| def createBook(BookCommand book) {<p class="paragraph"/> // … |
| } |
| }<p class="paragraph"/>class BookCommand { |
| <span class="java-object">String</span> title |
| <span class="java-object">String</span> authorName |
| }</pre></div><p class="paragraph"/>If the command object type is a domain class and the root element of the XML document contains an <code>id</code> attribute, the <code>id</code> value will be used to retrieve the corresponding persistent instance from the database and then the rest of the document will be bound to the instance. If no corresponding record is found in the database, the command object reference will be null.<p class="paragraph"/><div class="code"><pre><?xml version=<span class="java-quote">"1.0"</span> encoding=<span class="java-quote">"UTF-8"</span>?> |
| <book id=<span class="java-quote">"42"</span>> |
| <title>Walden</title> |
| <authorName>Henry David Thoreau</authorName> |
| </book></pre></div><p class="paragraph"/><div class="code"><pre>class BookController { |
| def updateBook(Book book) { |
| // The book will have been retrieved from the database and updated |
| // by doing something like <span class="java-keyword">this</span>: |
| // |
| // book == Book.get('42') |
| // <span class="java-keyword">if</span>(book != <span class="java-keyword">null</span>) { |
| // book.properties = request |
| // } |
| // |
| // the code above represents what the framework will |
| // have done. There is no need to write that code.<p class="paragraph"/> // ...<p class="paragraph"/> } |
| }</pre></div><p class="paragraph"/>The data binding depends on an instance of the <a href="http://grails.org/doc/3.0.x/api/org/grails/databinding/DataBindingSource.html" class="api">DataBindingSource</a> interface created by an instance of the <a href="http://grails.org/doc/3.0.x/api/org/grails/databinding/bindingsource/DataBindingSourceCreator.html" class="api">DataBindingSourceCreator</a> interface. The specific implementation of <code>DataBindingSourceCreator</code> will be selected based on the <code>contentType</code> of the request. Several implementations are provided to handle common content types. The default implementations will be fine for most use cases. The following table lists the content types which are supported by the core framework and which <code>DataBindingSourceCreator</code> implementations are used for each. All of the implementation classes are in the <code>org.grails.databinding.bindingsource</code> package.<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Content Type(s)</th><th>Bean Name</th><th>DataBindingSourceCreator Impl.</th></tr><tr class="table-odd"><td>application/xml, text/xml</td><td>xmlDataBindingSourceCreator</td><td>XmlDataBindingSourceCreator</td></tr><tr class="table-even"><td>application/json, text/json</td><td>jsonDataBindingSourceCreator</td><td>JsonDataBindingSourceCreator</td></tr><tr class="table-odd"><td>application/hal+json</td><td>halJsonDataBindingSourceCreator</td><td>HalJsonDataBindingSourceCreator</td></tr><tr class="table-even"><td>application/hal+xml</td><td>halXmlDataBindingSourceCreator</td><td>HalXmlDataBindingSourceCreator</td></tr></table><p class="paragraph"/>In order to provide your own <code>DataBindingSourceCreator</code> for any of those content types, write a class which implements |
| <code>DataBindingSourceCreator</code> and register an instance of that class in the Spring application context. If you |
| are replacing one of the existing helpers, use the corresponding bean name from above. If you are providing a |
| helper for a content type other than those accounted for by the core framework, the bean name may be anything that |
| you like but you should take care not to conflict with one of the bean names above.<p class="paragraph"/>The <code>DataBindingSourceCreator</code> interface defines just 2 methods:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> org.grails.databinding.bindingsource<p class="paragraph"/><span class="java-keyword">import</span> grails.web.mime.MimeType |
| <span class="java-keyword">import</span> grails.databinding.DataBindingSource<p class="paragraph"/>/** |
| * A factory <span class="java-keyword">for</span> DataBindingSource instances |
| * |
| * @since 2.3 |
| * @see DataBindingSourceRegistry |
| * @see DataBindingSource |
| * |
| */ |
| <span class="java-keyword">interface</span> DataBindingSourceCreator {<p class="paragraph"/> /** |
| * <code><span class="java-keyword">return</span> All of the {</code>link MimeType} supported by <span class="java-keyword">this</span> helper |
| */ |
| MimeType[] getMimeTypes()<p class="paragraph"/> /** |
| * Creates a DataBindingSource suitable <span class="java-keyword">for</span> binding bindingSource to bindingTarget |
| * |
| * @param mimeType a mime type |
| * @param bindingTarget the target of the data binding |
| * @param bindingSource the value being bound |
| * @<span class="java-keyword">return</span> a DataBindingSource |
| */ |
| DataBindingSource createDataBindingSource(MimeType mimeType, <span class="java-object">Object</span> bindingTarget, <span class="java-object">Object</span> bindingSource) |
| }</pre></div><p class="paragraph"/><a href="http://grails.org/doc/3.0.x/api/org/grails/databinding/bindingsource/AbstractRequestbodyDataBindingSourceCreator.html" class="api">AbstractRequestBodyDataBindingSourceCreator</a> |
| is an abstract class designed to be extended to simplify writing custom <code>DataBindingSourceCreator</code> classes. Classes which |
| extend <code>AbstractRequestbodyDatabindingSourceCreator</code> need to implement a method named <code>createBindingSource</code> |
| which accepts an <code>InputStream</code> as an argument and returns a <code>DataBindingSource</code> as well as implementing the <code>getMimeTypes</code> |
| method described in the <code>DataBindingSourceCreator</code> interface above. The <code>InputStream</code> argument to <code>createBindingSource</code> |
| provides access to the body of the request.<p class="paragraph"/>The code below shows a simple implementation.<p class="paragraph"/> |
| <div class="code"><pre>// MyCustomDataBindingSourceCreator.groovy in |
| // src/groovy/com/demo/myapp/databinding |
| <span class="java-keyword">package</span> com.demo.myapp.databinding<p class="paragraph"/><span class="java-keyword">import</span> grails.web.mime.MimeType |
| <span class="java-keyword">import</span> grails.databinding.DataBindingSource |
| <span class="java-keyword">import</span> org...databinding.SimpleMapDataBindingSource |
| <span class="java-keyword">import</span> org...databinding.bindingsource.AbstractRequestBodyDataBindingSourceCreator<p class="paragraph"/>/** |
| * A custom DataBindingSourceCreator capable of parsing key value pairs out of |
| * a request body containing a comma separated list of key:value pairs like: |
| * |
| * name:Herman,age:99,town:STL |
| * |
| */ |
| class MyCustomDataBindingSourceCreator <span class="java-keyword">extends</span> AbstractRequestBodyDataBindingSourceCreator {<p class="paragraph"/> @Override |
| <span class="java-keyword">public</span> MimeType[] getMimeTypes() { |
| [<span class="java-keyword">new</span> MimeType('text/custom+demo+csv')] as MimeType[] |
| }<p class="paragraph"/> @Override |
| <span class="java-keyword">protected</span> DataBindingSource createBindingSource(InputStream inputStream) { |
| def map = [:]<p class="paragraph"/> def reader = <span class="java-keyword">new</span> InputStreamReader(inputStream)<p class="paragraph"/> // <span class="java-keyword">this</span> is an obviously naive parser and is intended |
| // <span class="java-keyword">for</span> demonstration purposes only.<p class="paragraph"/> reader.eachLine { line -> |
| def keyValuePairs = line.split(',') |
| keyValuePairs.each { keyValuePair -> |
| <span class="java-keyword">if</span>(keyValuePair?.trim()) { |
| def keyValuePieces = keyValuePair.split(':') |
| def key = keyValuePieces[0].trim() |
| def value = keyValuePieces[1].trim() |
| map[key] = value |
| } |
| } |
| }<p class="paragraph"/> // create and <span class="java-keyword">return</span> a DataBindingSource which contains the parsed data |
| <span class="java-keyword">new</span> SimpleMapDataBindingSource(map) |
| } |
| }</pre></div><p class="paragraph"/>An instance of <code>MyCustomDataSourceCreator</code> needs to be registered in the spring application context.<p class="paragraph"/><div class="code"><pre>// grails-app/conf/spring/resources.groovy |
| beans = {<p class="paragraph"/> myCustomCreator com.demo.myapp.databinding.MyCustomDataBindingSourceCreator<p class="paragraph"/> // … |
| }</pre></div><p class="paragraph"/> |
| With that in place the framework will use the <code>myCustomCreator</code> bean any time a <code>DataBindingSourceCreator</code> is needed |
| to deal with a request which has a <code>contentType</code> of "text/custom+demo+csv". |
| |
| |
| <a name="8.2 SOAP"><!-- Legacy link --></a> |
| <h2 id="SOAP">9.2 SOAP</h2> |
| Grails does not feature SOAP support out-of-the-box, but there are several plugins that can help for both producing SOAP servers and calling SOAP web services.<p class="paragraph"/><h4>SOAP Clients</h4><p class="paragraph"/>To call SOAP web services there are generally 2 approaches taken, one is to use a tool to generate client stubs, the other is to manually construct the SOAP calls. The former can be easier to use, but the latter provides more flexibility / control.<p class="paragraph"/>The <a href="http://grails.org/plugin/cxf-client" target="blank">CXF client plugin</a> uses the CXF framework, which includes a <code>wsdl2java</code> tool for generating a client. There is nothing Groovy/Grails specific here in the generated code as it simply provides a Java API which you can invoke to call SOAP web services.<p class="paragraph"/>See the documentation on the <a href="https://github.com/ctoestreich/cxf-client" target="blank">CXF client plugin</a> for further information.<p class="paragraph"/>Alternatively, if you prefer more control over your SOAP calls the <a href="https://github.com/jwagenleitner/groovy-wslite" target="blank">WS-Lite library</a> is an excellent choice and features a <a href="http://grails.org/plugin/wslite" target="blank">Grails plugin</a>. You have more control over the SOAP requests sent, and since Groovy has fantastic support for building and parsing XML it can be very productive approach.<p class="paragraph"/>Below is an example of a SOAP call with wslite:<p class="paragraph"/><div class="code"><pre>withSoap(serviceURL: 'http://www.holidaywebservice.com/Holidays/US/Dates/USHolidayDates.asmx') { |
| def response = send { |
| body { |
| GetMothersDay(xmlns: 'http://www.27seconds.com/Holidays/US/Dates/') { |
| year(2011) |
| } |
| } |
| } |
| println response.GetMothersDayResponse.GetMothersDayResult.text() |
| }</pre></div><p class="paragraph"/>It is not recommended that you use the <a href="http://groovy.codehaus.org/GroovyWS" target="blank">GroovyWS</a> library, it pulls in many dependencies which increases the likelihood of conflicts. The WSlite library provides a far simpler and easier to use solution.<p class="paragraph"/><h4>SOAP Servers</h4><p class="paragraph"/>Again, Grails does not have direct support for exposing SOAP web services, however if you wish to expose a SOAP service from your application then the <a href="http://grails.org/plugin/cxf" target="blank">CXF plugin</a> (not to be confused with the cxf-client plugin), provides an easy way to do so.<p class="paragraph"/>Typically it involves taking a Grails service and adding 'expose'-style configuration, such as the below:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> expose = EndpointType.JAX_WS_WSDL |
| //your path (preferred) or url to wsdl |
| <span class="java-keyword">static</span> wsdl = 'org/grails/cxf/test/soap/CustomerService.wsdl'</pre></div><p class="paragraph"/>Please refer to the <a href="https://github.com/thorstadt/grails-cxf#soap" target="blank">documentation of the plugin</a> for more information. |
| |
| |
| <a name="8.3 RSS and Atom"><!-- Legacy link --></a> |
| <h2 id="RSSAndAtom">9.3 RSS and Atom</h2> |
| No direct support is provided for RSS or Atom within Grails. You could construct RSS or ATOM feeds with the <a href="../ref/Controllers/render.html" class="controllers">render</a> method's XML capability. There is however a <a href="http://grails.org/plugin/feeds" target="blank">Feeds plugin</a> available for Grails that provides a RSS and Atom builder using the popular <a href="https://rome.dev.java.net/" target="blank">ROME</a> library. An example of its usage can be seen below:<p class="paragraph"/><div class="code"><pre>def feed() { |
| render(feedType: <span class="java-quote">"rss"</span>, feedVersion: <span class="java-quote">"2.0"</span>) { |
| title = <span class="java-quote">"My test feed"</span> |
| link = <span class="java-quote">"http://your.test.server/yourController/feed"</span><p class="paragraph"/> <span class="java-keyword">for</span> (article in Article.list()) { |
| entry(article.title) { |
| link = <span class="java-quote">"http://your.test.server/article/${article.id}"</span> |
| article.content // <span class="java-keyword">return</span> the content |
| } |
| } |
| } |
| }</pre></div> |
| |
| |
| <a name="8 Asynchronous Programming"><!-- Legacy link --></a> |
| <h1 id="async">10 Asynchronous Programming</h1> |
| With modern hardware featuring multiple cores, many programming languages have been adding asynchronous, parallel programming APIs, Groovy being no exception.<p class="paragraph"/>The excellent <a href="http://gpars.codehaus.org" target="blank">GPars</a> project features a whole range of different APIs for asynchronous programming techniques including actors, promises, STM and data flow concurrency.<p class="paragraph"/>Added Grails 2.3, the Async features of Grails aim to simplify concurrent programming within the framework and include the concept of Promises and a unified event model. |
| |
| |
| <h2 id="promises">10.1 Promises</h2> |
| A Promise is a concept being embraced by many concurrency frameworks. They are similar to <code>java.util.concurrent.Future</code> instances, but include a more user friendly exception handling model, useful features like chaining and the ability to attach listeners.<p class="paragraph"/><h3>Promise Basics</h3><p class="paragraph"/>In Grails the <code>grails.async.Promises</code> class provides the entry point to the Promise API:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> <span class="java-keyword">static</span> grails.async.Promises.*</pre></div><p class="paragraph"/>To create promises you can use the <code>task</code> method, which returns an instance of the <code>grails.async.Promise</code> interface:<p class="paragraph"/><div class="code"><pre>def p1 = task { 2 * 2 } |
| def p2 = task { 4 * 4 } |
| def p3 = task { 8 * 8 } |
| assert [4,16,64] == waitAll(p1, p2, p3)</pre></div><p class="paragraph"/>The <code>waitAll</code> method waits synchronously, blocking the current thread, for all of the concurrent tasks to complete and returns the results.<p class="paragraph"/>If you prefer not to block the current thread you can use the <code>onComplete</code> method:<p class="paragraph"/><div class="code"><pre>onComplete([p1,p2,p3]) { List results -> |
| assert [4,16,64] == results |
| }</pre></div><p class="paragraph"/>The <code>waitAll</code> method will throw an exception if an error occurs executing one of the promises. The originating exception will be thrown. The <code>onComplete</code> method, however, will simply not execute the passed closure if an exception occurs. You can register an <code>onError</code> listener if you wish to handle exceptions without blocking:<p class="paragraph"/><div class="code"><pre>onError([p1,p2,p3]) { Throwable t -> |
| println <span class="java-quote">"An error occured ${t.message}"</span> |
| }</pre></div><p class="paragraph"/>If you have just a single long running promise then the <code>grails.async.Promise</code> interface provides a similar API on the promise itself. For example:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> <span class="java-keyword">static</span> java.util.concurrent.TimeUnit.* |
| <span class="java-keyword">import</span> <span class="java-keyword">static</span> grails.async.Promises.*<p class="paragraph"/>Promise p = task { |
| // <span class="java-object">Long</span> running task |
| } |
| p.onError { Throwable err -> |
| println <span class="java-quote">"An error occured ${err.message}"</span> |
| } |
| p.onComplete { result -> |
| println <span class="java-quote">"Promise returned $result"</span> |
| } |
| // block until result is called |
| def result = p.get() |
| // block <span class="java-keyword">for</span> the specified time |
| def result = p.get(1,MINUTES)</pre></div><p class="paragraph"/><h3>Promise Chaining</h3><p class="paragraph"/>It is possible to chain several promises and wait for the chain to complete using the <code>then</code> method:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">final</span> polish = { … } |
| <span class="java-keyword">final</span> transform = { … } |
| <span class="java-keyword">final</span> save = { … } |
| <span class="java-keyword">final</span> notify = { … }<p class="paragraph"/>Promise promise = task { |
| // <span class="java-object">long</span> running task |
| } |
| promise.then polish then transform then save then { |
| // notify end result |
| }</pre></div><p class="paragraph"/>If an exception occurs at any point in the chain it will be propagated back to the caller and the next step in the chain will not be called.<p class="paragraph"/><h3>Promise Lists and Maps</h3><p class="paragraph"/>Grails' async API also features the concept of a promise lists and maps. These are represented by the <code>grails.async.PromiseList</code> and <code>grails.async.PromiseMap</code> classes respectively.<p class="paragraph"/>The easiest way to create a promise list or map is via the <code>tasks</code> method of the <code>Promises</code> class:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> <span class="java-keyword">static</span> grails.async.Promises.*<p class="paragraph"/>def promiseList = tasks([{ 2 * 2 }, { 4 * 4}, { 8 * 8 }])<p class="paragraph"/>assert [4,16,64] == promiseList.get()</pre></div><p class="paragraph"/>The <code>tasks</code> method, when passed a list of closures, returns a <code>PromiseList</code>. You can also construct a <code>PromiseList</code> manually:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.async.*<p class="paragraph"/>def list = <span class="java-keyword">new</span> PromiseList() |
| list << { 2 * 2 } |
| list << { 4 * 4 } |
| list << { 8 * 8 } |
| list.onComplete { List results -> |
| assert [4,16,64] == results |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| The <code>PromiseList</code> class does not implement the java.util.List interface, but instead returns a java.util.List from the get() method |
| </blockquote><p class="paragraph"/>Working with <code>PromiseMap</code> instances is largely similar. Again you can either use the <code>tasks</code> method:<p class="paragraph"/> |
| <div class="code"><pre><span class="java-keyword">import</span> <span class="java-keyword">static</span> grails.async.Promises.*<p class="paragraph"/>def promiseList = tasks one:{ 2 * 2 }, |
| two:{ 4 * 4}, |
| three:{ 8 * 8 }<p class="paragraph"/>assert [one:4,two:16,three:64] == promiseList.get()</pre></div><p class="paragraph"/>Or construct a <code>PromiseMap</code> manually:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.async.*<p class="paragraph"/>def map = <span class="java-keyword">new</span> PromiseMap() |
| map['one'] = { 2 * 2 } |
| map['two'] = { 4 * 4 } |
| map['three'] = { 8 * 8 } |
| map.onComplete { Map results -> |
| assert [one:4,two:16,three:64] == results |
| }</pre></div><p class="paragraph"/><h3>Promise Factories</h3><p class="paragraph"/>The <code>Promises</code> class uses a <code>grails.async.PromiseFactory</code> instance to create <code>Promise</code> instances.<p class="paragraph"/>The default implementation uses the GPars concurrency library and is called <code>org.grails.async.factory.gpars.GparsPromiseFactory</code>, however it is possible to swap implementations by setting the <code>Promises.promiseFactory</code> variable.<p class="paragraph"/>One common use case for this is unit testing, typically you do not want promises to execute asynchronously during unit tests, as this makes tests harder to write. For this purpose Grails ships with a <code>org.grails.async.factory.SynchronousPromiseFactory</code> instance that makes it easier to test promises:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.grails.async.factory.* |
| <span class="java-keyword">import</span> grails.async.*<p class="paragraph"/>Promises.promiseFactory = <span class="java-keyword">new</span> SynchronousPromiseFactory()</pre></div><p class="paragraph"/>Using the <code>PromiseFactory</code> mechanism is theoretically possible to plug in other concurrency libraries into the Grails framework.<p class="paragraph"/><h3>DelegateAsync Transformation</h3><p class="paragraph"/>It is quite common to require both synchronous and asynchronous versions of the same API. Developing both can result in a maintenance problem as typically the asynchronous API would simply delegate to the synchronous version.<p class="paragraph"/>The <code>DelegateAsync</code> transformation is designed to mitigate this problem by transforming any synchronous API into an asynchronous one.<p class="paragraph"/>For example, consider the following service:<p class="paragraph"/><div class="code"><pre>class BookService { |
| List<Book> findBooks(<span class="java-object">String</span> title) { |
| // implementation |
| } |
| }</pre></div><p class="paragraph"/>The <code>findBooks</code> method executes synchronously in the same thread as the caller. To make an asynchronous version of this API you can define another class as follows:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.async.*<p class="paragraph"/>class AsyncBookService { |
| @DelegateAsync BookService bookService |
| }</pre></div><p class="paragraph"/>The <code>DelegateAsync</code> transformation will automatically add a new method that looks like the following to the <code>AsyncBookService</code> class:<p class="paragraph"/><div class="code"><pre>Promise<List<Book>> findBooks(<span class="java-object">String</span> title) { |
| Promises.task { |
| bookService.findBooks(title) |
| } |
| }</pre></div><p class="paragraph"/>As you see the transform adds equivalent methods that return a Promise and execute asynchronously.<p class="paragraph"/>The <code>AsyncBookService</code> can then be injected into other controllers and services and used as follows:<p class="paragraph"/><div class="code"><pre>AsyncBookService asyncBookService |
| def findBooks(<span class="java-object">String</span> title) { |
| asyncBookService.findBooks(title) |
| .onComplete { List results -> |
| println <span class="java-quote">"Books = ${results}"</span> |
| } |
| }</pre></div> |
| |
| |
| <a name="4.3 Hooking into Events"><!-- Legacy link --></a> |
| <h2 id="events">10.2 Events</h2> |
| Grails 3.0 introduces a new Events API based on <a href="https://github.com/reactor/reactor" target="blank">Reactor</a>.<p class="paragraph"/>All services and controllers in Grails 3.0 implement the <a href="http://grails.org/doc/3.0.x/api/grails/events/Events.html" class="api">Events</a> trait.<p class="paragraph"/>The <code>Events</code> trait allows the ability to consume and publish events that are handled by Reactor.<p class="paragraph"/>The default Reactor configuration utilises a thread pool backed event bus. You can however configure Reactor within <code>application.yml</code>, for example:<p class="paragraph"/><div class="code"><pre>reactor |
| dispatchers: |
| <span class="java-keyword">default</span>: myExecutor |
| myExecutor: |
| type: threadPoolExecutor |
| size: 5 |
| backlog: 2048</pre></div> |
| |
| |
| |
| <h2 id="consuming">10.2.1 Consuming Events</h2> |
| There are several ways to consume an event. As mentioned previously services and controllers implement the <a href="http://grails.org/doc/3.0.x/api/grails/events/Events.html" class="api">Events</a> trait.<p class="paragraph"/>The <code>Events</code> trait provides several methods to register event consumers. For example:<p class="paragraph"/><div class="code"><pre>on(<span class="java-quote">"myEvent"</span>) { |
| println <span class="java-quote">"Event fired!"</span> |
| }</pre></div><p class="paragraph"/>Note that if you wish a class (other than a controller or service) to be an event consumer you simply have to implement the <code>Events</code> trait and ensure the class is registered as a Spring bean. |
| |
| |
| |
| <h2 id="notifying">10.2.2 Event Notification</h2> |
| The <code>Events</code> trait also provides methods for notifying of events. For example:<p class="paragraph"/><div class="code"><pre>notify <span class="java-quote">"myEvent"</span>, <span class="java-quote">"myData"</span> |
| sendAndReceive <span class="java-quote">"myEvent"</span>, <span class="java-quote">"myData"</span>, { |
| println <span class="java-quote">"Got response!"</span> |
| }</pre></div> |
| |
| |
| |
| <h2 id="asyncGorm">10.3 Asynchronous GORM</h2> |
| Since Grails 2.3, GORM features an asynchronous programming model that works across all supported datastores (Hibernate, MongoDB etc.).<p class="paragraph"/><h3>Async Namespace</h3><p class="paragraph"/>The Asynchronous GORM API is available on every domain class via the <code>async</code> namespace.<p class="paragraph"/>For example, the following code listing reads 3 objects from the database asynchronously:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> <span class="java-keyword">static</span> grails.async.Promises.*<p class="paragraph"/>def p1 = Person.async.get(1L) |
| def p2 = Person.async.get(2L) |
| def p3 = Person.async.get(3L) |
| def results = waitAll(p1, p2, p3)</pre></div><p class="paragraph"/>Using the <code>async</code> namespace, all the regular GORM methods are available (even dynamic finders), but instead of executing synchronously, the query is run in the background and a <code>Promise</code> instance is returned.<p class="paragraph"/>The following code listing shows a few common examples of GORM queries executed asynchronously:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> <span class="java-keyword">static</span> grails.async.Promises.*<p class="paragraph"/>Person.async.list().onComplete { List results -> |
| println <span class="java-quote">"Got people = ${results}"</span> |
| } |
| def p = Person.async.getAll(1L, 2L, 3L) |
| List results = p.get()<p class="paragraph"/>def p1 = Person.async.findByFirstName(<span class="java-quote">"Homer"</span>) |
| def p2 = Person.async.findByFirstName(<span class="java-quote">"Bart"</span>) |
| def p3 = Person.async.findByFirstName(<span class="java-quote">"Barney"</span>) |
| results = waitAll(p1, p2, p3)</pre></div><p class="paragraph"/><h3>Async and the Session</h3><p class="paragraph"/>When using GORM async each promise is executed in a different thread. Since the Hibernate session is not concurrency safe, a new session is bound per thread.<p class="paragraph"/>This is an important consideration when using GORM async (particularly with Hibernate as the persistence engine). The objects returned from asynchronous queries will be detached entities.<p class="paragraph"/>This means you cannot save objects returned from asynchronous queries without first merging them back into session. For example the following will not work:<p class="paragraph"/><div class="code"><pre>def promise = Person.async.findByFirstName(<span class="java-quote">"Homer"</span>) |
| def person = promise.get() |
| person.firstName = <span class="java-quote">"Bart"</span> |
| person.save()</pre></div><p class="paragraph"/>Instead you need to merge the object with the session bound to the calling thread. The above code needs to be written as:<p class="paragraph"/><div class="code"><pre>def promise = Person.async.findByFirstName(<span class="java-quote">"Homer"</span>) |
| def person = promise.get() |
| person.merge() |
| person.firstName = <span class="java-quote">"Bart"</span></pre></div><p class="paragraph"/>Note that <code>merge()</code> is called first because it may refresh the object from the cache or database, which would result in the change being lost. In general it is not recommended to read and write objects in different threads and you should avoid this technique unless absolutely necessary.<p class="paragraph"/>Finally, another issue with detached objects is that association lazy loading <strong class="bold">will not</strong> work and you will encounter <code>LazyInitializationException</code> errors if you do so. If you plan to access the associated objects of those returned from asynchronous queries you should use eager queries (which is recommended anyway to avoid N+1 problems).<p class="paragraph"/><h3>Multiple Asynchronous GORM calls</h3><p class="paragraph"/>As discussed in the previous section you should avoid reading and writing objects in different threads as merging tends to be inefficient.<p class="paragraph"/>However, if you wish to do more complex GORM work asynchronously then the GORM async namespace provides a <code>task</code> method that makes this possible. For example:<p class="paragraph"/><div class="code"><pre>def promise = Person.async.task { |
| withTransaction { |
| def person = findByFirstName(<span class="java-quote">"Homer"</span>) |
| person.firstName = <span class="java-quote">"Bart"</span> |
| person.save(flush:<span class="java-keyword">true</span>) |
| } |
| }<p class="paragraph"/>Person updatedPerson = promise.get()</pre></div><p class="paragraph"/>Note that the GORM <code>task</code> method differs from the static <code>Promises.task</code> method in that it deals with binding a new session to the asynchronous thread for you. If you do not use the GORM version and do asynchronous work with GORM then you need to do this manually. Example:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> <span class="java-keyword">static</span> grails.async.Promises.*<p class="paragraph"/>def promise = task { |
| Person.withNewSession { |
| // your logic here |
| } |
| }</pre></div><p class="paragraph"/><h3>Async DetachedCriteria</h3><p class="paragraph"/>The <code>DetachedCriteria</code> class also supports the <code>async</code> namespace. For example you can do the following:<p class="paragraph"/><div class="code"><pre>DetachedCriteria query = Person.where { |
| lastName == <span class="java-quote">"Simpson"</span> |
| }<p class="paragraph"/>def promise = query.async.list()</pre></div><p class="paragraph"/><p class="paragraph"/> |
| |
| |
| <h2 id="asyncRequests">10.4 Asynchronous Request Handling</h2> |
| If you are deploying to a Servlet 3.0 container such as Tomcat 7 and above then it is possible to deal with responses asynchronously.<p class="paragraph"/>In general for controller actions that execute quickly there is little benefit in handling requests asynchronously. However, for long running controller actions it is extremely beneficial.<p class="paragraph"/>The reason being that with an asynchronous / non-blocking response, the one thread == one request == one response relationship is broken. The container can keep a client response open and active, and at the same time return the thread back to the container to deal with another request, improving scalability.<p class="paragraph"/>For example, if you have 70 available container threads and an action takes a minute to complete, if the actions are not executed in a non-blocking fashion the likelihood of all 70 threads being occupied and the container not being able to respond is quite high and you should consider asynchronous request processing.<p class="paragraph"/>Since Grails 2.3, Grails features a simplified API for creating asynchronous responses built on the <code>Promise</code> mechanism discussed previously.<p class="paragraph"/>The implementation is based on Servlet 3.0 async so to enable the async features you need to set your servlet target version to 3.0 in BuildConfig.groovy:<p class="paragraph"/><div class="code"><pre>grails.servlet.version = <span class="java-quote">"3.0"</span></pre></div><p class="paragraph"/><h4>Async Models</h4><p class="paragraph"/>A typical activity in a Grails controller is to produce a model (a map of key/value pairs) that can be rendered by a view.<p class="paragraph"/>If the model takes a while to produce then the server could arrive at a blocking state, impacting scalability. You tell Grails to build the model asynchronously by returning a <code>grails.async.PromiseMap</code> via the <code>Promises.tasks</code> method:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> <span class="java-keyword">static</span> grails.async.Promises.* |
| … |
| def index() { |
| tasks books: Book.async.list(), |
| totalBooks: Book.async.count(), |
| otherValue: { |
| // <span class="java-keyword">do</span> hard work |
| } |
| }</pre></div><p class="paragraph"/>Grails will handle the response asynchronously, waiting for the promises to complete before rendering the view. The equivalent synchronous action of the above is:<p class="paragraph"/><div class="code"><pre>def index() { |
| def otherValue = … |
| [ books: Book.list() , |
| totalBooks: Book.count(), |
| otherValue: otherValue ] |
| }</pre></div><p class="paragraph"/>You can even render different view by passing the <code>PromiseMap</code> to the <code>model</code> attribute of the <code>render</code> method:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> <span class="java-keyword">static</span> grails.async.Promises.* |
| … |
| def index() { |
| render view:<span class="java-quote">"myView"</span>, model: tasks( one:{ 2 * 2 }, |
| two:{ 3 * 3 } ) |
| }</pre></div><p class="paragraph"/><h4>Async Response Rendering</h4><p class="paragraph"/>You can also write to the response asynchronously using promises in Grails 2.3 and above:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> <span class="java-keyword">static</span> grails.async.Promises.* |
| class StockController {<p class="paragraph"/> def stock(<span class="java-object">String</span> ticker) { |
| task { |
| ticker = ticker ?: 'GOOG' |
| def url = <span class="java-keyword">new</span> URL(<span class="java-quote">"http://download.finance.yahoo.com/d/quotes.csv?s=${ticker}&f=nsl1op&e=.csv"</span>) |
| <span class="java-object">Double</span> price = url.text.split(',')[-1] as <span class="java-object">Double</span> |
| render <span class="java-quote">"ticker: $ticker, price: $price"</span> |
| } |
| } |
| }</pre></div><p class="paragraph"/>The above example using Yahoo Finance to query stock prices, executing asynchronously and only rendering the response once the result has been obtained. This is done by returning a <code>Promise</code> instance from the controller action.<p class="paragraph"/>If the Yahoo URL is unresponsive the original request thread will not be blocked and the container will not become unresponsive. |
| |
| |
| |
| <h2 id="asyncServletApi">10.5 Servlet 3.0 Async</h2> |
| In addition to the higher level async features discussed earlier in the section, you can access the raw Servlet 3.0 asynchronous API from a Grails application.<p class="paragraph"/><h4>Servlet 3.0 Asynchronous Rendering</h4><p class="paragraph"/>You can render content (templates, binary data etc.) in an asynchronous manner by calling the <code>startAsync</code> method which returns an instance of the Servlet 3.0 <code>AsyncContext</code>. Once you have a reference to the <code>AsyncContext</code> you can use Grails' regular render method to render content:<p class="paragraph"/><div class="code"><pre>def index() { |
| def ctx = startAsync() |
| ctx.start { |
| <span class="java-keyword">new</span> Book(title:<span class="java-quote">"The Stand"</span>).save() |
| render template:<span class="java-quote">"books"</span>, model:[books:Book.list()] |
| ctx.complete() |
| } |
| }</pre></div><p class="paragraph"/>Note that you must call the <code>complete()</code> method to terminate the connection.<p class="paragraph"/><h4>Resuming an Async Request</h4><p class="paragraph"/>You resume processing of an async request (for example to delegate to view rendering) by using the <code>dispatch</code> method of the <code>AsyncContext</code> class:<p class="paragraph"/><div class="code"><pre>def index() { |
| def ctx = startAsync() |
| ctx.start { |
| // <span class="java-keyword">do</span> working |
| … |
| // render view |
| ctx.dispatch() |
| } |
| }</pre></div> |
| |
| |
| <a name="10. Validation"><!-- Legacy link --></a> |
| <h1 id="validation">11 Validation</h1> |
| Grails validation capability is built on <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/validation/package-summary.html" target="blank">Spring's Validator API</a> and data binding capabilities. However Grails takes this further and provides a unified way to define validation "constraints" with its constraints mechanism.<p class="paragraph"/>Constraints in Grails are a way to declaratively specify validation rules. Most commonly they are applied to <a href="../guide/single.html#GORM" class="guide">domain classes</a>, however <a href="../guide/single.html#urlmappings" class="guide">URL Mappings</a> and <a href="../guide/single.html#commandObjects" class="guide">Command Objects</a> also support constraints. |
| |
| |
| <a name="10.1 Declaring Constraints"><!-- Legacy link --></a> |
| <h2 id="constraints">11.1 Declaring Constraints</h2> |
| Within a domain class <a href="../ref/Domain Classes/constraints.html" class="domainClasses">constraints</a> are defined with the constraints property that is assigned a code block:<p class="paragraph"/><div class="code"><pre>class User { |
| <span class="java-object">String</span> login |
| <span class="java-object">String</span> password |
| <span class="java-object">String</span> email |
| <span class="java-object">Integer</span> age<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| … |
| } |
| }</pre></div><p class="paragraph"/>You then use method calls that match the property name for which the constraint applies in combination with named parameters to specify constraints:<p class="paragraph"/><div class="code"><pre>class User { |
| ...<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| login size: 5..15, blank: <span class="java-keyword">false</span>, unique: <span class="java-keyword">true</span> |
| password size: 5..15, blank: <span class="java-keyword">false</span> |
| email email: <span class="java-keyword">true</span>, blank: <span class="java-keyword">false</span> |
| age min: 18 |
| } |
| }</pre></div><p class="paragraph"/>In this example we've declared that the <code>login</code> property must be between 5 and 15 characters long, it cannot be blank and must be unique. We've also applied other constraints to the <code>password</code>, <code>email</code> and <code>age</code> properties.<p class="paragraph"/><blockquote class="note"> |
| By default, all domain class properties are not nullable (i.e. they have an implicit <code>nullable: false</code> constraint). |
| </blockquote><p class="paragraph"/>A complete reference for the available constraints can be found in the Quick Reference section under the Constraints heading.<p class="paragraph"/>Note that constraints are only evaluated once which may be relevant for a constraint that relies on a value like an instance of <code>java.util.Date</code>.<p class="paragraph"/><div class="code"><pre>class User { |
| ...<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| // <span class="java-keyword">this</span> Date object is created when the constraints are evaluated, not |
| // each time an instance of the User class is validated. |
| birthDate max: <span class="java-keyword">new</span> Date() |
| } |
| }</pre></div><p class="paragraph"/><h3>A word of warning - referencing domain class properties from constraints</h3><p class="paragraph"/>It's very easy to attempt to reference instance variables from the static constraints block, but this isn't legal in Groovy (or Java). If you do so, you will get a <code>MissingPropertyException</code> for your trouble. For example, you may try |
| <div class="code"><pre>class Response { |
| Survey survey |
| Answer answer<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| survey blank: <span class="java-keyword">false</span> |
| answer blank: <span class="java-keyword">false</span>, inList: survey.answers |
| } |
| }</pre></div><p class="paragraph"/>See how the <code>inList</code> constraint references the instance property <code>survey</code>? That won't work. Instead, use a custom <a href="../ref/Constraints/validator.html" class="constraints">validator</a>:<p class="paragraph"/><div class="code"><pre>class Response { |
| … |
| <span class="java-keyword">static</span> constraints = { |
| survey blank: <span class="java-keyword">false</span> |
| answer blank: <span class="java-keyword">false</span>, validator: { val, obj -> val in obj.survey.answers } |
| } |
| }</pre></div><p class="paragraph"/>In this example, the <code>obj</code> argument to the custom validator is the domain <em class="italic">instance</em> that is being validated, so we can access its <code>survey</code> property and return a boolean to indicate whether the new value for the <code>answer</code> property, <code>val</code>, is valid. |
| |
| |
| <a name="10.2 Validating Constraints"><!-- Legacy link --></a> |
| <h2 id="validatingConstraints">11.2 Validating Constraints</h2> |
| <h4>Validation Basics</h4><p class="paragraph"/>Call the <a href="../ref/Domain Classes/validate.html" class="domainClasses">validate</a> method to validate a domain class instance:<p class="paragraph"/><div class="code"><pre>def user = <span class="java-keyword">new</span> User(params)<p class="paragraph"/><span class="java-keyword">if</span> (user.validate()) { |
| // <span class="java-keyword">do</span> something with user |
| } |
| <span class="java-keyword">else</span> { |
| user.errors.allErrors.each { |
| println it |
| } |
| }</pre></div><p class="paragraph"/>The <code>errors</code> property on domain classes is an instance of the Spring <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/validation/Errors.html" class="api">Errors</a> interface. The <code>Errors</code> interface provides methods to navigate the validation errors and also retrieve the original values.<p class="paragraph"/><h4>Validation Phases</h4><p class="paragraph"/>Within Grails there are two phases of validation, the first one being <a href="../guide/single.html#dataBinding" class="guide">data binding</a> which occurs when you bind request parameters onto an instance such as:<p class="paragraph"/><div class="code"><pre>def user = <span class="java-keyword">new</span> User(params)</pre></div><p class="paragraph"/>At this point you may already have errors in the <code>errors</code> property due to type conversion (such as converting Strings to Dates). You can check these and obtain the original input value using the <code>Errors</code> API:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">if</span> (user.hasErrors()) { |
| <span class="java-keyword">if</span> (user.errors.hasFieldErrors(<span class="java-quote">"login"</span>)) { |
| println user.errors.getFieldError(<span class="java-quote">"login"</span>).rejectedValue |
| } |
| }</pre></div><p class="paragraph"/>The second phase of validation happens when you call <a href="../ref/Domain Classes/validate.html" class="domainClasses">validate</a> or <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a>. This is when Grails will validate the bound values against the <a href="../ref/Domain Classes/constraints.html" class="domainClasses">constraints</a> you defined. For example, by default the <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> method calls <code>validate</code> before executing, allowing you to write code like:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">if</span> (user.save()) { |
| <span class="java-keyword">return</span> user |
| } |
| <span class="java-keyword">else</span> { |
| user.errors.allErrors.each { |
| println it |
| } |
| }</pre></div> |
| |
| |
| |
| <h2 id="sharingConstraints">11.3 Sharing Constraints Between Classes</h2> |
| A common pattern in Grails is to use <a href="../guide/single.html#commandObjects" class="guide">command objects</a> for validating user-submitted data and then copy the properties of the command object to the relevant domain classes. This often means that your command objects and domain classes share properties and their constraints. You could manually copy and paste the constraints between the two, but that's a very error-prone approach. Instead, make use of Grails' global constraints and import mechanism.<p class="paragraph"/><h3>Global Constraints</h3><p class="paragraph"/>In addition to defining constraints in domain classes, command objects and <a href="../guide/single.html#validationNonDomainAndCommandObjectClasses" class="guide">other validateable classes</a>, you can also define them in <code>grails-app/conf/Config.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.gorm.<span class="java-keyword">default</span>.constraints = { |
| '*'(nullable: <span class="java-keyword">true</span>, size: 1..20) |
| myShared(nullable: <span class="java-keyword">false</span>, blank: <span class="java-keyword">false</span>) |
| }</pre></div><p class="paragraph"/>These constraints are not attached to any particular classes, but they can be easily referenced from any validateable class:<p class="paragraph"/><div class="code"><pre>class User { |
| ...<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| login shared: <span class="java-quote">"myShared"</span> |
| } |
| }</pre></div><p class="paragraph"/>Note the use of the <code>shared</code> argument, whose value is the name of one of the constraints defined in <code>grails.gorm.default.constraints</code>. Despite the name of the configuration setting, you can reference these shared constraints from any validateable class, such as command objects.<p class="paragraph"/>The '*' constraint is a special case: it means that the associated constraints ('nullable' and 'size' in the above example) will be applied to all properties in all validateable classes. These defaults can be overridden by the constraints declared in a validateable class.<p class="paragraph"/><h3>Importing Constraints</h3><p class="paragraph"/>Grails 2 introduced an alternative approach to sharing constraints that allows you to import a set of constraints from one class into another.<p class="paragraph"/>Let's say you have a domain class like so:<p class="paragraph"/><div class="code"><pre>class User { |
| <span class="java-object">String</span> firstName |
| <span class="java-object">String</span> lastName |
| <span class="java-object">String</span> passwordHash<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| firstName blank: <span class="java-keyword">false</span>, nullable: <span class="java-keyword">false</span> |
| lastName blank: <span class="java-keyword">false</span>, nullable: <span class="java-keyword">false</span> |
| passwordHash blank: <span class="java-keyword">false</span>, nullable: <span class="java-keyword">false</span> |
| } |
| }</pre></div><p class="paragraph"/>You then want to create a command object, <code>UserCommand</code>, that shares some of the properties of the domain class and the corresponding constraints. You do this with the <code>importFrom()</code> method:<p class="paragraph"/><div class="code"><pre>class UserCommand { |
| <span class="java-object">String</span> firstName |
| <span class="java-object">String</span> lastName |
| <span class="java-object">String</span> password |
| <span class="java-object">String</span> confirmPassword<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| importFrom User<p class="paragraph"/> password blank: <span class="java-keyword">false</span>, nullable: <span class="java-keyword">false</span> |
| confirmPassword blank: <span class="java-keyword">false</span>, nullable: <span class="java-keyword">false</span> |
| } |
| }</pre></div><p class="paragraph"/>This will import all the constraints from the <code>User</code> domain class and apply them to <code>UserCommand</code>. The import will ignore any constraints in the source class (<code>User</code>) that don't have corresponding properties in the importing class (<code>UserCommand</code>). In the above example, only the 'firstName' and 'lastName' constraints will be imported into <code>UserCommand</code> because those are the only properties shared by the two classes.<p class="paragraph"/>If you want more control over which constraints are imported, use the <code>include</code> and <code>exclude</code> arguments. Both of these accept a list of simple or regular expression strings that are matched against the property names in the source constraints. So for example, if you only wanted to import the 'lastName' constraint you would use:<p class="paragraph"/><div class="code"><pre>… |
| <span class="java-keyword">static</span> constraints = { |
| importFrom User, include: [<span class="java-quote">"lastName"</span>] |
| … |
| }</pre></div><p class="paragraph"/>or if you wanted all constraints that ended with 'Name':<p class="paragraph"/><div class="code"><pre>… |
| <span class="java-keyword">static</span> constraints = { |
| importFrom User, include: [/.*Name/] |
| … |
| }</pre></div><p class="paragraph"/>Of course, <code>exclude</code> does the reverse, specifying which constraints should <em class="italic">not</em> be imported. |
| |
| |
| <a name="10.3 Validation on the Client"><!-- Legacy link --></a> |
| <h2 id="validationOnTheClient">11.4 Validation on the Client</h2> |
| <h4>Displaying Errors</h4><p class="paragraph"/>Typically if you get a validation error you redirect back to the view for rendering. Once there you need some way of displaying errors. Grails supports a rich set of tags for dealing with errors. To render the errors as a list you can use <a href="../ref/Tags/renderErrors.html" class="tags">renderErrors</a>:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:renderErrors bean=<span class="xml-quote">"${user}"</span> /></span></pre></div><p class="paragraph"/>If you need more control you can use <a href="../ref/Tags/hasErrors.html" class="tags">hasErrors</a> and <a href="../ref/Tags/eachError.html" class="tags">eachError</a>:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:hasErrors bean=<span class="xml-quote">"${user}"</span>></span> |
| <span class="xml-tag"><ul></span> |
| <span class="xml-tag"><g:eachError var=<span class="xml-quote">"err"</span> bean=<span class="xml-quote">"${user}"</span>></span> |
| <span class="xml-tag"><li></span>${err}<span class="xml-tag"></li></span> |
| <span class="xml-tag"></g:eachError></span> |
| <span class="xml-tag"></ul></span> |
| <span class="xml-tag"></g:hasErrors></span></pre></div><p class="paragraph"/><h4>Highlighting Errors</h4><p class="paragraph"/>It is often useful to highlight using a red box or some indicator when a field has been incorrectly input. This can also be done with the <a href="../ref/Tags/hasErrors.html" class="tags">hasErrors</a> by invoking it as a method. For example:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><div class='value ${hasErrors(bean:user,field:'login','errors')}'></span> |
| <span class="xml-tag"><input type=<span class="xml-quote">"text"</span> name=<span class="xml-quote">"login"</span> value=<span class="xml-quote">"${fieldValue(bean:user,field:'login')}"</span>/></span> |
| <span class="xml-tag"></div></span></pre></div><p class="paragraph"/>This code checks if the <code>login</code> field of the <code>user</code> bean has any errors and if so it adds an <code>errors</code> CSS class to the <code>div</code>, allowing you to use CSS rules to highlight the <code>div</code>.<p class="paragraph"/><h4>Retrieving Input Values</h4><p class="paragraph"/>Each error is actually an instance of the <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/validation/FieldError.html" class="api">FieldError</a> class in Spring, which retains the original input value within it. This is useful as you can use the error object to restore the value input by the user using the <a href="../ref/Tags/fieldValue.html" class="tags">fieldValue</a> tag:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><input type=<span class="xml-quote">"text"</span> name=<span class="xml-quote">"login"</span> value=<span class="xml-quote">"${fieldValue(bean:user,field:'login')}"</span>/></span></pre></div><p class="paragraph"/>This code will check for an existing <code>FieldError</code> in the <code>User</code> bean and if there is obtain the originally input value for the <code>login</code> field. |
| |
| |
| <a name="10.4 Validation and Internationalization"><!-- Legacy link --></a> |
| <h2 id="validationAndInternationalization">11.5 Validation and Internationalization</h2> |
| Another important thing to note about errors in Grails is that error messages are not hard coded anywhere. The <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/validation/FieldError.html" class="api">FieldError</a> class in Spring resolves messages from message bundles using Grails' <a href="../guide/single.html#i18n" class="guide">i18n</a> support.<p class="paragraph"/><h4>Constraints and Message Codes</h4><p class="paragraph"/>The codes themselves are dictated by a convention. For example consider the constraints we looked at earlier:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> com.mycompany.myapp<p class="paragraph"/>class User { |
| ...<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| login size: 5..15, blank: <span class="java-keyword">false</span>, unique: <span class="java-keyword">true</span> |
| password size: 5..15, blank: <span class="java-keyword">false</span> |
| email email: <span class="java-keyword">true</span>, blank: <span class="java-keyword">false</span> |
| age min: 18 |
| } |
| }</pre></div><p class="paragraph"/>If a constraint is violated Grails will by convention look for a message code of the form:<p class="paragraph"/><div class="code"><pre>[<span class="java-object">Class</span> Name].[Property Name].[Constraint Code]</pre></div><p class="paragraph"/>In the case of the <code>blank</code> constraint this would be <code>user.login.blank</code> so you would need a message such as the following in your <code>grails-app/i18n/messages.properties</code> file:<p class="paragraph"/><div class="code"><pre>user.login.blank=Your login name must be specified!</pre></div><p class="paragraph"/>The class name is looked for both with and without a package, with the packaged version taking precedence. So for example, com.mycompany.myapp.User.login.blank will be used before user.login.blank. This allows for cases where your domain class message codes clash with a plugin's.<p class="paragraph"/>For a reference on what codes are for which constraints refer to the reference guide for each constraint.<p class="paragraph"/><h4>Displaying Messages</h4><p class="paragraph"/>The <a href="../ref/Tags/renderErrors.html" class="tags">renderErrors</a> tag will automatically look up messages for you using the <a href="../ref/Tags/message.html" class="tags">message</a> tag. If you need more control of rendering you can handle this yourself:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:hasErrors bean=<span class="xml-quote">"${user}"</span>></span> |
| <span class="xml-tag"><ul></span> |
| <span class="xml-tag"><g:eachError var=<span class="xml-quote">"err"</span> bean=<span class="xml-quote">"${user}"</span>></span> |
| <span class="xml-tag"><li></span><span class="xml-tag"><g:message error=<span class="xml-quote">"${err}"</span> /></span><span class="xml-tag"></li></span> |
| <span class="xml-tag"></g:eachError></span> |
| <span class="xml-tag"></ul></span> |
| <span class="xml-tag"></g:hasErrors></span></pre></div><p class="paragraph"/>In this example within the body of the <a href="../ref/Tags/eachError.html" class="tags">eachError</a> tag we use the <a href="../ref/Tags/message.html" class="tags">message</a> tag in combination with its <code>error</code> argument to read the message for the given error.<p class="paragraph"/> |
| |
| <a name="10.5 Validation Non Domain and Command Object Classes"><!-- Legacy link --></a> |
| <h2 id="validationNonDomainAndCommandObjectClasses">11.6 Applying Validation to Other Classes</h2> |
| <a href="../guide/single.html#domainClasses" class="guide">Domain classes</a> and <a href="../guide/single.html#commandObjects" class="guide">command objects</a> support validation by default. Other classes may be made validateable by defining the static <code>constraints</code> property in the class (as described above) and then telling the framework about them. It is important that the application register the validateable classes with the framework. Simply defining the <code>constraints</code> property is not sufficient.<p class="paragraph"/><h4>The Validateable Trait</h4><p class="paragraph"/>Classes which define the static <code>constraints</code> property and implement the <a href="http://grails.org/doc/3.0.x/api/grails/validation/Validateable.html" class="api">Validateable</a> trait will be validateable. Consider this example:<p class="paragraph"/><div class="code"><pre>// src/groovy/com/mycompany/myapp/User.groovy |
| <span class="java-keyword">package</span> com.mycompany.myapp<p class="paragraph"/><span class="java-keyword">import</span> grails.validation.Validateable<p class="paragraph"/>class User <span class="java-keyword">implements</span> Validateable { |
| ...<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| login size: 5..15, blank: <span class="java-keyword">false</span>, unique: <span class="java-keyword">true</span> |
| password size: 5..15, blank: <span class="java-keyword">false</span> |
| email email: <span class="java-keyword">true</span>, blank: <span class="java-keyword">false</span> |
| age min: 18 |
| } |
| }</pre></div> |
| |
| |
| <a name="11. The Service Layer"><!-- Legacy link --></a> |
| <h1 id="services">12 The Service Layer</h1> |
| Grails defines the notion of a service layer. The Grails team discourages the embedding of core application logic inside controllers, as it does not promote reuse and a clean separation of concerns.<p class="paragraph"/>Services in Grails are the place to put the majority of the logic in your application, leaving controllers responsible for handling request flow with redirects and so on.<p class="paragraph"/><h4>Creating a Service</h4><p class="paragraph"/>You can create a Grails service by running the <a href="../ref/Command Line/create-service.html" class="commandLine">create-service</a> command from the root of your project in a terminal window:<p class="paragraph"/><div class="code"><pre>grails create-service helloworld.simple</pre></div><p class="paragraph"/><blockquote class="note"> |
| If no package is specified with the create-service script, Grails automatically uses the application name as the package name. |
| </blockquote><p class="paragraph"/>The above example will create a service at the location <code>grails-app/services/helloworld/SimpleService.groovy</code>. A service's name ends with the convention <code>Service</code>, other than that a service is a plain Groovy class:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> helloworld<p class="paragraph"/>class SimpleService { |
| }</pre></div> |
| |
| |
| <a name="11.1 Declarative Transactions"><!-- Legacy link --></a> |
| <h2 id="declarativeTransactions">12.1 Declarative Transactions</h2> |
| <h3>Default Declarative Transactions</h3><p class="paragraph"/>Services are typically involved with coordinating logic between <a href="../guide/single.html#GORM" class="guide">domain classes</a>, and hence often involved with persistence that spans large operations. Given the nature of services, they frequently require transactional behaviour. You can use programmatic transactions with the <a href="../ref/Domain Classes/withTransaction.html" class="domainClasses">withTransaction</a> method, however this is repetitive and doesn't fully leverage the power of Spring's underlying transaction abstraction.<p class="paragraph"/>Services enable transaction demarcation, which is a declarative way of defining which methods are to be made transactional. All services are transactional by default. To disable this set the <code>transactional</code> property to <code>false</code>:<p class="paragraph"/><div class="code"><pre>class CountryService { |
| <span class="java-keyword">static</span> transactional = <span class="java-keyword">false</span> |
| }</pre></div><p class="paragraph"/>You may also set this property to <code>true</code> to make it clear that the service is intentionally transactional.<p class="paragraph"/><blockquote class="warning"> |
| Warning: <a href="../guide/single.html#dependencyInjectionServices" class="guide">dependency injection</a> is the <strong class="bold">only</strong> way that declarative transactions work. You will not get a transactional service if you use the <code>new</code> operator such as <code>new BookService()</code> |
| </blockquote><p class="paragraph"/>The result is that all methods are wrapped in a transaction and automatic rollback occurs if a method throws a runtime exception (i.e. one that extends <code>RuntimeException</code>) or an <code>Error</code>. The propagation level of the transaction is by default set to <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/transaction/TransactionDefinition.html#PROPAGATION_REQUIRED" target="blank">PROPAGATION_REQUIRED</a>.<p class="paragraph"/><blockquote class="warning"> |
| Checked exceptions do <strong class="bold">not</strong> roll back transactions. Even though Groovy blurs the distinction between checked and unchecked exceptions, Spring isn't aware of this and its default behaviour is used, so it's important to understand the distinction between checked and unchecked exceptions. |
| </blockquote><p class="paragraph"/><h3>Custom Transaction Configuration</h3><p class="paragraph"/>Grails also provides <code>@Transactional</code> and <code>@NotTransactional</code> annotations for cases where you need more fine-grained control over transactions at a per-method level or need to specify an alternative propagation level. For example, the <code>@NotTransactional</code> annotation can be used to mark a particular method to be skipped when a class is annotated with <code>@Transactional</code>.<p class="paragraph"/><blockquote class="note"> |
| The <code>grails.transaction.Transactional</code> annotation was first introduced in Grails 2.3. Prior to 2.3, Spring's @Transactional annotation was used. |
| </blockquote><p class="paragraph"/><blockquote class="note"> |
| Annotating a service method with <code>Transactional</code> disables the default Grails transactional behavior for that service (in the same way that adding <code>transactional=false</code> does) so if you use any annotations you must annotate all methods that require transactions. |
| </blockquote><p class="paragraph"/>In this example <code>listBooks</code> uses a read-only transaction, <code>updateBook</code> uses a default read-write transaction, and <code>deleteBook</code> is not transactional (probably not a good idea given its name).<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.springframework.transaction.annotation.Transactional<p class="paragraph"/>class BookService {<p class="paragraph"/> @Transactional(readOnly = <span class="java-keyword">true</span>) |
| def listBooks() { |
| Book.list() |
| }<p class="paragraph"/> @Transactional |
| def updateBook() { |
| // … |
| }<p class="paragraph"/> def deleteBook() { |
| // … |
| } |
| }</pre></div><p class="paragraph"/>You can also annotate the class to define the default transaction behavior for the whole service, and then override that default per-method. For example, this service is equivalent to one that has no annotations (since the default is implicitly <code>transactional=true</code>):<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.springframework.transaction.annotation.Transactional<p class="paragraph"/>@Transactional |
| class BookService {<p class="paragraph"/> def listBooks() { |
| Book.list() |
| }<p class="paragraph"/> def updateBook() { |
| // … |
| }<p class="paragraph"/> def deleteBook() { |
| // … |
| } |
| }</pre></div><p class="paragraph"/>This version defaults to all methods being read-write transactional (due to the class-level annotation), but the <code>listBooks</code> method overrides this to use a read-only transaction:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.springframework.transaction.annotation.Transactional<p class="paragraph"/>@Transactional |
| class BookService {<p class="paragraph"/> @Transactional(readOnly = <span class="java-keyword">true</span>) |
| def listBooks() { |
| Book.list() |
| }<p class="paragraph"/> def updateBook() { |
| // … |
| }<p class="paragraph"/> def deleteBook() { |
| // … |
| } |
| }</pre></div><p class="paragraph"/>Although <code>updateBook</code> and <code>deleteBook</code> aren't annotated in this example, they inherit the configuration from the class-level annotation.<p class="paragraph"/>For more information refer to the section of the Spring user guide on <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/transaction.html#transaction-declarative-annotations" target="blank">Using @Transactional</a>.<p class="paragraph"/>Unlike Spring you do not need any prior configuration to use <code>Transactional</code>; just specify the annotation as needed and Grails will detect them up automatically. |
| |
| |
| <a name="11.1.1 Transactions Rollback and the Session"><!-- Legacy link --></a> |
| <h2 id="transactionsRollbackAndTheSession">12.1.1 Transactions Rollback and the Session</h2> |
| <h3>Understanding Transactions and the Hibernate Session</h3><p class="paragraph"/>When using transactions there are important considerations you must take into account with regards to how the underlying persistence session is handled by Hibernate. When a transaction is rolled back the Hibernate session used by GORM is cleared. This means any objects within the session become detached and accessing uninitialized lazy-loaded collections will lead to <code>LazyInitializationException</code>s.<p class="paragraph"/>To understand why it is important that the Hibernate session is cleared. Consider the following example:<p class="paragraph"/><div class="code"><pre>class Author { |
| <span class="java-object">String</span> name |
| <span class="java-object">Integer</span> age<p class="paragraph"/> <span class="java-keyword">static</span> hasMany = [books: Book] |
| }</pre></div><p class="paragraph"/>If you were to save two authors using consecutive transactions as follows:<p class="paragraph"/><div class="code"><pre>Author.withTransaction { status -> |
| <span class="java-keyword">new</span> Author(name: <span class="java-quote">"Stephen King"</span>, age: 40).save() |
| status.setRollbackOnly() |
| }<p class="paragraph"/>Author.withTransaction { status -> |
| <span class="java-keyword">new</span> Author(name: <span class="java-quote">"Stephen King"</span>, age: 40).save() |
| }</pre></div><p class="paragraph"/>Only the second author would be saved since the first transaction rolls back the author <code>save()</code> by clearing the Hibernate session. If the Hibernate session were not cleared then both author instances would be persisted and it would lead to very unexpected results.<p class="paragraph"/>It can, however, be frustrating to get <code>LazyInitializationException</code>s due to the session being cleared.<p class="paragraph"/>For example, consider the following example:<p class="paragraph"/><div class="code"><pre>class AuthorService {<p class="paragraph"/> void updateAge(id, <span class="java-object">int</span> age) { |
| def author = Author.get(id) |
| author.age = age |
| <span class="java-keyword">if</span> (author.isTooOld()) { |
| <span class="java-keyword">throw</span> <span class="java-keyword">new</span> AuthorException(<span class="java-quote">"too old"</span>, author) |
| } |
| } |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class AuthorController {<p class="paragraph"/> def authorService<p class="paragraph"/> def updateAge() { |
| <span class="java-keyword">try</span> { |
| authorService.updateAge(params.id, params.<span class="java-object">int</span>(<span class="java-quote">"age"</span>)) |
| } |
| <span class="java-keyword">catch</span>(e) { |
| render <span class="java-quote">"Author books ${e.author.books}"</span> |
| } |
| } |
| }</pre></div><p class="paragraph"/>In the above example the transaction will be rolled back if the <code>Author</code>'s age exceeds the maximum value defined in the <code>isTooOld()</code> method by throwing an <code>AuthorException</code>. The <code>AuthorException</code> references the author but when the <code>books</code> association is accessed a <code>LazyInitializationException</code> will be thrown because the underlying Hibernate session has been cleared.<p class="paragraph"/>To solve this problem you have a number of options. One is to ensure you query eagerly to get the data you will need:<p class="paragraph"/><div class="code"><pre>class AuthorService { |
| … |
| void updateAge(id, <span class="java-object">int</span> age) { |
| def author = Author.findById(id, [fetch:[books:<span class="java-quote">"eager"</span>]]) |
| ...</pre></div><p class="paragraph"/>In this example the <code>books</code> association will be queried when retrieving the <code>Author</code>.<p class="paragraph"/><blockquote class="note"> |
| This is the optimal solution as it requires fewer queries then the following suggested solutions. |
| </blockquote><p class="paragraph"/>Another solution is to redirect the request after a transaction rollback:<p class="paragraph"/><div class="code"><pre>class AuthorController {<p class="paragraph"/> AuthorService authorService<p class="paragraph"/> def updateAge() { |
| <span class="java-keyword">try</span> { |
| authorService.updateAge(params.id, params.<span class="java-object">int</span>(<span class="java-quote">"age"</span>)) |
| } |
| <span class="java-keyword">catch</span>(e) { |
| flash.message <span class="java-quote">"Can't update age"</span> |
| redirect action:<span class="java-quote">"show"</span>, id:params.id |
| } |
| } |
| }</pre></div><p class="paragraph"/>In this case a new request will deal with retrieving the <code>Author</code> again. And, finally a third solution is to retrieve the data for the <code>Author</code> again to make sure the session remains in the correct state:<p class="paragraph"/><div class="code"><pre>class AuthorController {<p class="paragraph"/> def authorService<p class="paragraph"/> def updateAge() { |
| <span class="java-keyword">try</span> { |
| authorService.updateAge(params.id, params.<span class="java-object">int</span>(<span class="java-quote">"age"</span>)) |
| } |
| <span class="java-keyword">catch</span>(e) { |
| def author = Author.read(params.id) |
| render <span class="java-quote">"Author books ${author.books}"</span> |
| } |
| } |
| }</pre></div><p class="paragraph"/><h3>Validation Errors and Rollback</h3><p class="paragraph"/>A common use case is to rollback a transaction if there are validation errors. For example consider this service:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.validation.ValidationException<p class="paragraph"/>class AuthorService {<p class="paragraph"/> void updateAge(id, <span class="java-object">int</span> age) { |
| def author = Author.get(id) |
| author.age = age |
| <span class="java-keyword">if</span> (!author.validate()) { |
| <span class="java-keyword">throw</span> <span class="java-keyword">new</span> ValidationException(<span class="java-quote">"Author is not valid"</span>, author.errors) |
| } |
| } |
| }</pre></div><p class="paragraph"/>To re-render the same view that a transaction was rolled back in you can re-associate the errors with a refreshed instance before rendering:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.validation.ValidationException<p class="paragraph"/>class AuthorController {<p class="paragraph"/> def authorService<p class="paragraph"/> def updateAge() { |
| <span class="java-keyword">try</span> { |
| authorService.updateAge(params.id, params.<span class="java-object">int</span>(<span class="java-quote">"age"</span>)) |
| } |
| <span class="java-keyword">catch</span> (ValidationException e) { |
| def author = Author.read(params.id) |
| author.errors = e.errors |
| render view: <span class="java-quote">"edit"</span>, model: [author:author] |
| } |
| } |
| }</pre></div> |
| |
| |
| <a name="11.2 Scoped Services"><!-- Legacy link --></a> |
| <h2 id="scopedServices">12.2 Scoped Services</h2> |
| By default, access to service methods is not synchronised, so nothing prevents concurrent execution of those methods. In fact, because the service is a singleton and may be used concurrently, you should be very careful about storing state in a service. Or take the easy (and better) road and never store state in a service.<p class="paragraph"/>You can change this behaviour by placing a service in a particular scope. The supported scopes are: |
| <ul class="star"> |
| <li><code>prototype</code> - A new service is created every time it is injected into another class</li> |
| <li><code>request</code> - A new service will be created per request</li> |
| <li><code>flash</code> - A new service will be created for the current and next request only</li> |
| <li><code>flow</code> - In web flows the service will exist for the scope of the flow</li> |
| <li><code>conversation</code> - In web flows the service will exist for the scope of the conversation. ie a root flow and its sub flows</li> |
| <li><code>session</code> - A service is created for the scope of a user session</li> |
| <li><code>singleton</code> (default) - Only one instance of the service ever exists</li> |
| </ul><p class="paragraph"/><blockquote class="note"> |
| If your service is <code>flash</code>, <code>flow</code> or <code>conversation</code> scoped it must implement <code>java.io.Serializable</code> and can only be used in the context of a Web Flow. |
| </blockquote><p class="paragraph"/>To enable one of the scopes, add a static scope property to your class whose value is one of the above, for example<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> scope = <span class="java-quote">"flow"</span></pre></div><p class="paragraph"/><blockquote class="note"> |
| For new Grails apps since 2.3, default controller scope is <code>singleton</code>, resulting in <code>prototype</code> scope services that are effectively per-controller singletons. If non-singleton services are required, controller scope should be changed as well. |
| </blockquote> |
| |
| |
| <a name="11.3 Dependency Injection and Services"><!-- Legacy link --></a> |
| <h2 id="dependencyInjectionServices">12.3 Dependency Injection and Services</h2> |
| <h4>Dependency Injection Basics</h4><p class="paragraph"/>A key aspect of Grails services is the ability to use <a href="http://www.springframework.org/" target="blank">Spring Framework</a>'s dependency injection features. Grails supports "dependency injection by convention". In other words, you can use the property name representation of the class name of a service to automatically inject them into controllers, tag libraries, and so on.<p class="paragraph"/>As an example, given a service called <code>BookService</code>, if you define a property called <code>bookService</code> in a controller as follows:<p class="paragraph"/><div class="code"><pre>class BookController { |
| def bookService |
| … |
| }</pre></div><p class="paragraph"/>In this case, the Spring container will automatically inject an instance of that service based on its configured scope. All dependency injection is done by name. You can also specify the type as follows:<p class="paragraph"/><div class="code"><pre>class AuthorService { |
| BookService bookService |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| NOTE: Normally the property name is generated by lower casing the first letter of the type. For example, an instance of the <code>BookService</code> class would map to a property named <code>bookService</code>.<p class="paragraph"/>To be consistent with standard JavaBean conventions, if the first 2 letters of the class name are upper case, the property name is the same as the class name. For example, the property name of the <code>JDBCHelperService</code> class would be <code>JDBCHelperService</code>, not <code>jDBCHelperService</code> or <code>jdbcHelperService</code>.<p class="paragraph"/>See section 8.8 of the JavaBean specification for more information on de-capitalization rules. |
| </blockquote><p class="paragraph"/><h4>Dependency Injection and Services</h4><p class="paragraph"/>You can inject services in other services with the same technique. If you had an <code>AuthorService</code> that needed to use the <code>BookService</code>, declaring the <code>AuthorService</code> as follows would allow that:<p class="paragraph"/><div class="code"><pre>class AuthorService { |
| def bookService |
| }</pre></div><p class="paragraph"/><h4>Dependency Injection and Domain Classes / Tag Libraries</h4><p class="paragraph"/>You can even inject services into domain classes and tag libraries, which can aid in the development of rich domain models and views:<p class="paragraph"/><div class="code"><pre>class Book { |
| … |
| def bookService<p class="paragraph"/> def buyBook() { |
| bookService.buyBook(<span class="java-keyword">this</span>) |
| } |
| }</pre></div><p class="paragraph"/><h4>Service Bean Names</h4><p class="paragraph"/>The default bean name which is associated with a service can be problematic if there are multiple services with the same name defined in different packages. For example consider the situation where an application defines a service class named <code>com.demo.ReportingService</code> and the application uses a plugin named <code>ReportingUtilities</code> and that plugin provides a service class named <code>com.reporting.util.ReportingService</code>. The default bean name for each of those would be <code>reportingService</code> so they would conflict with each other. Grails manages this by changing the default bean name for services provided by plugins by prefixing the bean name with the plugin name. In the scenario described above the <code>reportingService</code> bean would be an instance of the <code>com.demo.ReportingService</code> class defined in the application and the <code>reportingUtilitiesReportingService</code> bean would be an instance of the <code>com.reporting.util.ReportingService</code> class provided by the <code>ReportingUtilities</code> plugin. For all service beans provided by plugins, if there are no other services with the same name within the application or other plugins in the application then a bean alias will be created which does not include the plugin name and that alias points to the bean referred to by the name that does include the plugin name prefix. For example, if the <code>ReportingUtilities</code> plugin provides a service named <code>com.reporting.util.AuthorService</code> and there is no other <code>AuthorService</code> in the application or in any of the plugins that the application is using then there will be a bean named <code>reportingUtilitiesAuthorService</code> which is an instance of this <code>com.reporting.util.AuthorService</code> class and there will be a bean alias defined in the context named <code>authorService</code> which points to that same bean. |
| |
| <a name="11.4 Using Services from Java"><!-- Legacy link --></a> |
| <h2 id="usingServicesFromJava">12.4 Using Services from Java</h2> |
| One of the powerful things about services is that since they encapsulate re-usable logic, you can use them from other classes, including Java classes. There are a couple of ways you can reuse a service from Java. The simplest way is to move your service into a package within the <code>grails-app/services</code> directory. The reason this is important is that it is not possible to import classes into Java from the default package (the package used when no package declaration is present). So for example the <code>BookService</code> below cannot be used from Java as it stands:<p class="paragraph"/><div class="code"><pre>class BookService { |
| void buyBook(Book book) { |
| // logic |
| } |
| }</pre></div><p class="paragraph"/>However, this can be rectified by placing this class in a package, by moving the class into a sub directory such as <code>grails-app/services/bookstore</code> and then modifying the package declaration:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> bookstore<p class="paragraph"/>class BookService { |
| void buyBook(Book book) { |
| // logic |
| } |
| }</pre></div><p class="paragraph"/>An alternative to packages is to instead have an interface within a package that the service implements:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> bookstore<p class="paragraph"/><span class="java-keyword">interface</span> BookStore { |
| void buyBook(Book book) |
| }</pre></div><p class="paragraph"/>And then the service:<p class="paragraph"/><div class="code"><pre>class BookService <span class="java-keyword">implements</span> bookstore.BookStore { |
| void buyBook(Book b) { |
| // logic |
| } |
| }</pre></div><p class="paragraph"/>This latter technique is arguably cleaner, as the Java side only has a reference to the interface and not to the implementation class (although it's always a good idea to use packages). Either way, the goal of this exercise to enable Java to statically resolve the class (or interface) to use, at compile time.<p class="paragraph"/>Now that this is done you can create a Java class within the <code>src/java</code> directory and add a setter that uses the type and the name of the bean in Spring:<p class="paragraph"/><div class="code"><pre>// src/java/bookstore/BookConsumer.java |
| <span class="java-keyword">package</span> bookstore;<p class="paragraph"/><span class="java-keyword">public</span> class BookConsumer {<p class="paragraph"/> <span class="java-keyword">private</span> BookStore store;<p class="paragraph"/> <span class="java-keyword">public</span> void setBookStore(BookStore storeInstance) { |
| <span class="java-keyword">this</span>.store = storeInstance; |
| } |
| … |
| }</pre></div><p class="paragraph"/>Once this is done you can configure the Java class as a Spring bean in <code>grails-app/conf/spring/resources.xml</code> (for more information see the section on <a href="../guide/single.html#spring" class="guide">Grails and Spring</a>):<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><bean id=<span class="xml-quote">"bookConsumer"</span> class=<span class="xml-quote">"bookstore.BookConsumer"</span>></span> |
| <span class="xml-tag"><property name=<span class="xml-quote">"bookStore"</span> ref=<span class="xml-quote">"bookService"</span> /></span> |
| <span class="xml-tag"></bean></span></pre></div><p class="paragraph"/>or in <code>grails-app/conf/spring/resources.groovy</code>:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> bookstore.BookConsumer<p class="paragraph"/>beans = { |
| bookConsumer(BookConsumer) { |
| bookStore = ref(<span class="java-quote">"bookService"</span>) |
| } |
| }</pre></div> |
| |
| |
| |
| <h1 id="staticTypeCheckingAndCompilation">13 Static Type Checking And Compilation</h1> |
| Groovy is a dynamic language and by default Groovy uses a dynamic dispatch mechanism to carry out method calls and property access. This dynamic dispatch mechanism provides a lot of flexibility and power to the language. For example, it is possible to dynamically add methods to classes at runtime and it is possible to dynamically replace existing methods at runtime. Features like these are important and provide a lot of power to the language. However, there are times when you may want to disable this dynamic dispatch in favor of a more static dispatch mechanism and Groovy provides a way to do that. The way to tell the Groovy compiler that a particular class should compiled statically is to mark the class with the <a href="http://docs.groovy-lang.org/docs/latest/html/api/groovy/transform/CompileStatic.html" class="api">groovy.transform.CompileStatic</a> annotation as shown below.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> groovy.transform.CompileStatic<p class="paragraph"/>@CompileStatic |
| class MyClass {<p class="paragraph"/> // <span class="java-keyword">this</span> class will be statically compiled...<p class="paragraph"/>}</pre></div><p class="paragraph"/>See <a href="http://docs.codehaus.org/display/GroovyJSR/GEP+10+-+Static+compilation" target="blank">these notes on Groovy static compilation</a> for more details on how <code>CompileStatic</code> works and why you might want to use it.<p class="paragraph"/>One limitation of using <code>CompileStatic</code> is that when you use it you give up access to the power and flexibility offered by dynamic dispatch. For example, in Grails you would not be able to invoke a GORM dynamic finder from a class that is marked with <code>CompileStatic</code> because the compiler cannot verify that the dynamic finder method exists, because it doesn't exist at compile time. It may be that you want to take advantage of Groovy's static compilation benefits without giving up access to dynamic dispatch for Grails specific things like dynamic finders and this is where <a href="http://grails.org/doc/3.0.x/api/grails/compiler/GrailsCompileStatic.html" class="api">grails.compiler.GrailsCompileStatic</a> comes in. <code>GrailsCompileStatic</code> behaves just like <code>CompileStatic</code> but is aware of certain Grails features and allows access to those specific features to be accessed dynamically. |
| |
| |
| |
| <h2 id="grailsCompileStatic">13.1 The GrailsCompileStatic Annotation</h2> |
| <h4>GrailsCompileStatic</h4><p class="paragraph"/>The <code>GrailsCompileStatic</code> annotation may be applied to a class or methods within a class.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.compiler.GrailsCompileStatic<p class="paragraph"/>@GrailsCompileStatic |
| class SomeClass {<p class="paragraph"/> // all of the code in <span class="java-keyword">this</span> class will be statically compiled<p class="paragraph"/> def methodOne() { |
| // … |
| }<p class="paragraph"/> def methodTwo() { |
| // … |
| }<p class="paragraph"/> def methodThree() { |
| // … |
| } |
| }</pre></div><p class="paragraph"/> |
| <div class="code"><pre><span class="java-keyword">import</span> grails.compiler.GrailsCompileStatic<p class="paragraph"/>class SomeClass {<p class="paragraph"/> // methodOne and methodThree will be statically compiled |
| // methodTwo will be dynamically compiled<p class="paragraph"/> @GrailsCompileStatic |
| def methodOne() { |
| // … |
| }<p class="paragraph"/> def methodTwo() { |
| // … |
| }<p class="paragraph"/> @GrailsCompileStatic |
| def methodThree() { |
| // … |
| } |
| }</pre></div><p class="paragraph"/>It is possible to mark a class with <code>GrailsCompileStatic</code> and exclude specific methods by marking them with <code>GrailsCompileStatic</code> and specifying that the type checking should be skipped for that particular method as shown below.<p class="paragraph"/> |
| <div class="code"><pre><span class="java-keyword">import</span> grails.compiler.GrailsCompileStatic |
| <span class="java-keyword">import</span> groovy.transform.TypeCheckingMode<p class="paragraph"/>@GrailsCompileStatic |
| class SomeClass {<p class="paragraph"/> // methodOne and methodThree will be statically compiled |
| // methodTwo will be dynamically compiled<p class="paragraph"/> def methodOne() { |
| // … |
| }<p class="paragraph"/> @GrailsCompileStatic(TypeCheckingMode.SKIP) |
| def methodTwo() { |
| // … |
| }<p class="paragraph"/> def methodThree() { |
| // … |
| } |
| }</pre></div><p class="paragraph"/>Code that is marked with <code>GrailsCompileStatic</code> will all be statically compiled except for Grails specific interactions that cannot be statically compiled but that <code>GrailsCompileStatic</code> can identify as permissible for dynamic dispatch. These include things like invoking dynamic finders and DSL code in configuration blocks like constraints and mapping closures in domain classes.<p class="paragraph"/>Care must be taken when deciding to statically compile code. There are benefits associated with static compilation but in order to take advantage of those benefits you are giving up the power and flexibility of dynamic dispatch. For example if code is statically compiled it cannot take advantage of runtime metaprogramming enhancements which may be provided by plugins. |
| |
| |
| <h2 id="grailsTypeChecked">13.2 The GrailsTypeChecked Annotation</h2> |
| <h4>GrailsTypeChecked</h4><p class="paragraph"/>The <a href="http://grails.org/doc/3.0.x/api/grails/compiler/GrailsTypeChecked.html" class="api">grails.compiler.GrailsTypeChecked</a> annotation works a lot like the <code>GrailsCompileStatic</code> annotation except that it only enables static type checking, not static compilation. This affords compile time feedback for expressions which cannot be validated statically at compile time while still leaving dynamic dispatch in place for the class.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.compiler.GrailsTypeChecked<p class="paragraph"/>@GrailsTypeChecked |
| class SomeClass {<p class="paragraph"/> // all of the code in <span class="java-keyword">this</span> class will be statically type |
| // checked and will be dynamically dispatched at runtime<p class="paragraph"/> def methodOne() { |
| // … |
| }<p class="paragraph"/> def methodTwo() { |
| // … |
| }<p class="paragraph"/> def methodThree() { |
| // … |
| } |
| }</pre></div><p class="paragraph"/> |
| |
| <a name="12. Testing"><!-- Legacy link --></a> |
| <h1 id="testing">14 Testing</h1> |
| Automated testing is a key part of Grails. Hence, Grails provides many ways to making testing easier from low level unit testing to high level functional tests. This section details the different capabilities that Grails offers for testing.<p class="paragraph"/><blockquote class="note"> |
| Grails 1.3.x and below used the <code>grails.test.GrailsUnitTestCase</code> class hierarchy for testing in a JUnit 3 style. Grails 2.0.x and above deprecates these test harnesses in favour of mixins that can be applied to a range of different kinds of tests (JUnit 3, JUnit 4, Spock etc.) without subclassing |
| </blockquote><p class="paragraph"/>The first thing to be aware of is that all of the <code>create-*</code> and <code>generate-*</code> commands create <code>unit</code> or <code>integration</code> tests automatically. For example if you run the <a href="../ref/Command Line/create-controller.html" class="commandLine">create-controller</a> command as follows:<p class="paragraph"/><div class="code"><pre>grails create-controller com.acme.app.simple</pre></div><p class="paragraph"/>Grails will create a controller at <code>grails-app/controllers/com/acme/app/SimpleController.groovy</code>, and also a unit test at <code>test/unit/com/acme/app/SimpleControllerTests.groovy</code>. What Grails won't do however is populate the logic inside the test! That is left up to you.<p class="paragraph"/><blockquote class="note"> |
| The default class name suffix is <code>Tests</code> but as of Grails 1.2.2, the suffix of <code>Test</code> is also supported. |
| </blockquote><p class="paragraph"/><h4>Running Tests</h4><p class="paragraph"/>Tests are run with the <a href="../ref/Command Line/test-app.html" class="commandLine">test-app</a> command:<p class="paragraph"/><div class="code"><pre>grails test-app</pre></div><p class="paragraph"/>The command will produce output such as:<p class="paragraph"/><div class="code"><pre>------------------------------------------------------- |
| Running Unit Tests… |
| Running test FooTests...FAILURE |
| Unit Tests Completed in 464ms … |
| -------------------------------------------------------<p class="paragraph"/>Tests failed: 0 errors, 1 failures</pre></div><p class="paragraph"/>whilst showing the reason for each test failure.<p class="paragraph"/><blockquote class="note"> |
| You can force a clean before running tests by passing <code>-clean</code> to the <code>test-app</code> command. |
| </blockquote><p class="paragraph"/>Grails writes both plain text and HTML test reports to the <code>target/test-reports</code> directory, along with the original XML files. The HTML reports are generally the best ones to look at.<p class="paragraph"/>Using Grails' <a href="../guide/single.html#interactiveMode" class="guide">interactive mode</a> confers some distinct advantages when executing tests. First, the tests will execute significantly faster on the second and subsequent runs. Second, a shortcut is available to open the HTML reports in your browser:<p class="paragraph"/><div class="code"><pre>open test-report</pre></div><p class="paragraph"/>You can also run your unit tests from within most IDEs.<p class="paragraph"/><h4>Targeting Tests</h4><p class="paragraph"/>You can selectively target the test(s) to be run in different ways. To run all tests for a controller named <code>SimpleController</code> you would run:<p class="paragraph"/><div class="code"><pre>grails test-app SimpleController</pre></div><p class="paragraph"/>This will run any tests for the class named <code>SimpleController</code>. Wildcards can be used...<p class="paragraph"/><div class="code"><pre>grails test-app *Controller</pre></div><p class="paragraph"/>This will test all classes ending in <code>Controller</code>. Package names can optionally be specified...<p class="paragraph"/><div class="code"><pre>grails test-app some.org.*Controller</pre></div><p class="paragraph"/>or to run all tests in a package...<p class="paragraph"/><div class="code"><pre>grails test-app some.org.*</pre></div><p class="paragraph"/>or to run all tests in a package including subpackages...<p class="paragraph"/><div class="code"><pre>grails test-app some.org.**.*</pre></div><p class="paragraph"/>You can also target particular test methods...<p class="paragraph"/><div class="code"><pre>grails test-app SimpleController.testLogin</pre></div><p class="paragraph"/>This will run the <code>testLogin</code> test in the <code>SimpleController</code> tests. You can specify as many patterns in combination as you like...<p class="paragraph"/><div class="code"><pre>grails test-app some.org.* SimpleController.testLogin BookController</pre></div><p class="paragraph"/><h4>Targeting Test Types and/or Phases</h4><p class="paragraph"/>In addition to targeting certain tests, you can also target test <em class="italic">types</em> and/or <em class="italic">phases</em> by using the <code>phase:type</code> syntax.<p class="paragraph"/><blockquote class="note"> |
| Grails organises tests by phase and by type. A test phase relates to the state of the Grails application during the tests, and the type relates to the testing mechanism.<p class="paragraph"/>Grails comes with support for 4 test phases (<code>unit</code>, <code>integration</code>, <code>functional</code> and <code>other</code>) and JUnit test types for the <code>unit</code> and <code>integration</code> phases. These test types have the same name as the phase.<p class="paragraph"/>Testing plugins may provide new test phases or new test types for existing phases. Refer to the plugin documentation. |
| </blockquote><p class="paragraph"/>To execute the JUnit <code>integration</code> tests you can run:<p class="paragraph"/><div class="code"><pre>grails test-app integration:integration</pre></div><p class="paragraph"/>Both <code>phase</code> and <code>type</code> are optional. Their absence acts as a wildcard. The following command will run all test types in the <code>unit</code> phase:<p class="paragraph"/><div class="code"><pre>grails test-app unit:</pre></div><p class="paragraph"/>The Grails <a href="http://grails.org/plugin/spock" target="blank">Spock Plugin</a> is one plugin that adds new test types to Grails. It adds a <code>spock</code> test type to the <code>unit</code>, <code>integration</code> and <code>functional</code> phases. To run all spock tests in all phases you would run the following:<p class="paragraph"/><div class="code"><pre>grails test-app :spock</pre></div><p class="paragraph"/>To run the all of the spock tests in the <code>functional</code> phase you would run...<p class="paragraph"/><div class="code"><pre>grails test-app functional:spock</pre></div><p class="paragraph"/>More than one pattern can be specified...<p class="paragraph"/><div class="code"><pre>grails test-app unit:spock integration:spock</pre></div><p class="paragraph"/><h4>Targeting Tests in Types and/or Phases</h4><p class="paragraph"/>Test and type/phase targetting can be applied at the same time:<p class="paragraph"/><div class="code"><pre>grails test-app integration: unit: some.org.**.*</pre></div><p class="paragraph"/>This would run all tests in the <code>integration</code> and <code>unit</code> phases that are in the package <code>some.org</code> or a subpackage. |
| |
| |
| <a name="12.1 Unit Testing"><!-- Legacy link --></a> |
| <h2 id="unitTesting">14.1 Unit Testing</h2> |
| Unit testing are tests at the "unit" level. In other words you are testing individual methods or blocks of code without consideration for surrounding infrastructure. Unit tests are typically run without the presence of physical resources that involve I/O such databases, socket connections or files. This is to ensure they run as quick as possible since quick feedback is important.<p class="paragraph"/><h4>The Test Mixins</h4><p class="paragraph"/>Since Grails 2.0, a collection of unit testing mixins is provided by Grails that lets you enhance the behavior of a typical JUnit 3, JUnit 4 or Spock test. The following sections cover the usage of these mixins.<p class="paragraph"/><blockquote class="note"> |
| The previous JUnit 3-style <code>GrailsUnitTestCase</code> class hierarchy is still present in Grails for backwards compatibility, but is now deprecated. The previous documentation on the subject can be found in the <a href="http://grails.org/doc/1.3.x/guide/9.%20Testing.html" target="blank">Grails 1.3.x documentation</a> |
| </blockquote><p class="paragraph"/>You won't normally have to import any of the testing classes because Grails does that for you. But if you find that your IDE for example can't find the classes, here they all are: |
| <ul class="star"> |
| <li><code>grails.test.mixin.TestFor</code></li> |
| <li><code>grails.test.mixin.Mock</code></li> |
| <li><code>grails.test.mixin.TestMixin</code></li> |
| <li><code>grails.test.mixin.support.GrailsUnitTestMixin</code></li> |
| <li><code>grails.test.mixin.domain.DomainClassUnitTestMixin</code></li> |
| <li><code>grails.test.mixin.services.ServiceUnitTestMixin</code></li> |
| <li><code>grails.test.mixin.web.ControllerUnitTestMixin</code></li> |
| <li><code>grails.test.mixin.web.FiltersUnitTestMixin</code></li> |
| <li><code>grails.test.mixin.web.GroovyPageUnitTestMixin</code></li> |
| <li><code>grails.test.mixin.web.UrlMappingsUnitTestMixin</code></li> |
| <li><code>grails.test.mixin.hibernate.HibernateTestMixin</code></li> |
| </ul><p class="paragraph"/>Note that you're only ever likely to use the first two explicitly. The rest are there for reference.<p class="paragraph"/><h4>Test Mixin Basics</h4><p class="paragraph"/>Most testing can be achieved via the <code>TestFor</code> annotation in combination with the <code>Mock</code> annotation for mocking collaborators. For example, to test a controller and associated domains you would define the following:<p class="paragraph"/><div class="code"><pre>@TestFor(BookController) |
| @Mock([Book, Author, BookService])</pre></div><p class="paragraph"/>The <code>TestFor</code> annotation defines the class under test and will automatically create a field for the type of class under test. For example in the above case a "controller" field will be present, however if <code>TestFor</code> was defined for a service a "service" field would be created and so on.<p class="paragraph"/>The <code>Mock</code> annotation creates mock version of any collaborators. There is an in-memory implementation of GORM that will simulate most interactions with the GORM API.<p class="paragraph"/><h4>doWithSpring and doWithConfig callback methods, FreshRuntime annotation</h4><p class="paragraph"/>The <code>doWithSpring</code> callback method can be used to add beans with the BeanBuilder DSL. There is the <code>doWithConfig</code> callback method for changing the grailsApplication.config values before the grailsApplication instance of the test runtime gets initialized.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.support.GrailsUnitTestMixin<p class="paragraph"/><span class="java-keyword">import</span> org.junit.ClassRule |
| <span class="java-keyword">import</span> org.junit.rules.TestRule<p class="paragraph"/><span class="java-keyword">import</span> spock.lang.Ignore; |
| <span class="java-keyword">import</span> spock.lang.IgnoreRest |
| <span class="java-keyword">import</span> spock.lang.Shared; |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestMixin(GrailsUnitTestMixin) |
| class StaticCallbacksSpec <span class="java-keyword">extends</span> Specification { |
| <span class="java-keyword">static</span> doWithSpring = { |
| myService(MyService) |
| }<p class="paragraph"/> <span class="java-keyword">static</span> doWithConfig(c) { |
| c.myConfigValue = 'Hello' |
| }<p class="paragraph"/> def <span class="java-quote">"grailsApplication is not <span class="java-keyword">null</span>"</span>() { |
| expect: |
| grailsApplication != <span class="java-keyword">null</span> |
| }<p class="paragraph"/> def <span class="java-quote">"doWithSpring callback is executed"</span>() { |
| expect: |
| grailsApplication.mainContext.getBean('myService') != <span class="java-keyword">null</span> |
| }<p class="paragraph"/> def <span class="java-quote">"doWithConfig callback is executed"</span>(){ |
| expect: |
| config.myConfigValue == 'Hello' |
| } |
| }</pre></div><p class="paragraph"/> |
| You can also use these callbacks without "static" together with the <code><a href="http://grails.org/doc/3.0.x/api/grails/test/runtime/FreshRuntime.html" class="api">grails.test.runtime.FreshRuntime</a></code> annotation. |
| In this case, a clean application context and grails application instance is initialized for each test method call.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.support.GrailsUnitTestMixin |
| <span class="java-keyword">import</span> grails.test.runtime.FreshRuntime;<p class="paragraph"/><span class="java-keyword">import</span> org.junit.ClassRule |
| <span class="java-keyword">import</span> org.junit.rules.TestRule<p class="paragraph"/><span class="java-keyword">import</span> spock.lang.Ignore; |
| <span class="java-keyword">import</span> spock.lang.IgnoreRest |
| <span class="java-keyword">import</span> spock.lang.Shared; |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@FreshRuntime |
| @TestMixin(GrailsUnitTestMixin) |
| class TestInstanceCallbacksSpec <span class="java-keyword">extends</span> Specification { |
| def doWithSpring = { |
| myService(MyService) |
| }<p class="paragraph"/> def doWithConfig(c) { |
| c.myConfigValue = 'Hello' |
| }<p class="paragraph"/> def <span class="java-quote">"grailsApplication is not <span class="java-keyword">null</span>"</span>() { |
| expect: |
| grailsApplication != <span class="java-keyword">null</span> |
| }<p class="paragraph"/> def <span class="java-quote">"doWithSpring callback is executed"</span>() { |
| expect: |
| grailsApplication.mainContext.getBean('myService') != <span class="java-keyword">null</span> |
| }<p class="paragraph"/> def <span class="java-quote">"doWithConfig callback is executed"</span>(){ |
| expect: |
| config.myConfigValue == 'Hello' |
| } |
| }</pre></div><p class="paragraph"/><p class="paragraph"/>You can use <code><a href="http://grails.org/doc/3.0.x/api/org/grails/spring/beans/factory/InstanceFactoryBean.html" class="api">org.grails.spring.beans.factory.InstanceFactoryBean</a></code> together with doWithSpring and the <a href="http://grails.org/doc/3.0.x/api/grails/test/runtime/FreshRuntime.html" class="api">FreshRuntime</a> annotation to mock beans in tests.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.support.GrailsUnitTestMixin |
| <span class="java-keyword">import</span> grails.test.runtime.FreshRuntime<p class="paragraph"/><span class="java-keyword">import</span> org.grails.spring.beans.factory.InstanceFactoryBean |
| <span class="java-keyword">import</span> org.junit.ClassRule<p class="paragraph"/><span class="java-keyword">import</span> spock.lang.Shared |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@FreshRuntime |
| @TestMixin(GrailsUnitTestMixin) |
| class MockedBeanSpec <span class="java-keyword">extends</span> Specification { |
| def myService=Mock(MyService)<p class="paragraph"/> def doWithSpring = { |
| myService(InstanceFactoryBean, myService, MyService) |
| }<p class="paragraph"/> def <span class="java-quote">"doWithSpring callback is executed"</span>() { |
| when: |
| def myServiceBean=grailsApplication.mainContext.getBean('myService') |
| myServiceBean.prova() |
| then: |
| 1 * myService.prova() >> { <span class="java-keyword">true</span> } |
| } |
| }</pre></div><p class="paragraph"/><h4>The DirtiesRuntime annotation</h4><p class="paragraph"/>Test methods may be marked with the <code><a href="http://grails.org/doc/3.0.x/api/grails/test/runtime/DirtiesRuntime.html" class="api">grails.test.runtime.DirtiesRuntime</a></code> annotation to indicate that the test modifies the runtime in ways which might be problematic for other tests and as such the runtime should be refreshed after this test method runs.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification |
| <span class="java-keyword">import</span> grails.test.runtime.DirtiesRuntime<p class="paragraph"/>@TestFor(PersonController) |
| class PersonControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> @DirtiesRuntime |
| void <span class="java-quote">"a test method which modifies the runtime"</span>() { |
| when: |
| Person.metaClass.someMethod = { … } |
| // ...<p class="paragraph"/> then: |
| // … |
| }<p class="paragraph"/> void <span class="java-quote">"a test method which should not be affected by the previous test method"</span>() { |
| // … |
| } |
| }</pre></div><p class="paragraph"/><h4>Sharing test runtime grailsApplication instance and beans for several test classes</h4><p class="paragraph"/>It's possible to share a single grailsApplication instance and beans for several test classes. |
| This feature is activated by the <code><a href="http://grails.org/doc/3.0.x/api/grails/test/runtime/SharedRuntime.html" class="api">SharedRuntime</a></code> annotation. This annotation takes an optional class parameter |
| implements <code><a href="http://grails.org/doc/3.0.x/api/grails/test/runtime/SharedRuntimeConfigurer.html" class="api">SharedRuntimeConfigurer</a></code> interface. All test classes referencing the same SharedRuntimeConfigurer implementation |
| class will share the same runtime during a single test run. |
| The value class for SharedRuntimeConfigurer annotation can also implement <code><a href="http://grails.org/doc/3.0.x/api/grails/test/runtime/TestEventInterceptor.html" class="api">TestEventInterceptor</a></code> . In this case the instance of the class |
| will be registered as a test event interceptor for the test runtime.<p class="paragraph"/> |
| <h4>Loading application beans in unit tests</h4><p class="paragraph"/>Adding <code>static loadExternalBeans = true</code> field definition to a unit test class makes the Grails unit test runtime load all bean definitions from <code>grails-app/conf/spring/resources.groovy</code> and <code>grails-app/conf/spring/resources.xml</code> files.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> spock.lang.Issue |
| <span class="java-keyword">import</span> spock.lang.Specification |
| <span class="java-keyword">import</span> grails.test.mixin.support.GrailsUnitTestMixin<p class="paragraph"/>@TestMixin(GrailsUnitTestMixin) |
| class LoadExternalBeansSpec <span class="java-keyword">extends</span> Specification { |
| <span class="java-keyword">static</span> loadExternalBeans = <span class="java-keyword">true</span><p class="paragraph"/> void <span class="java-quote">"should load external beans"</span>(){ |
| expect: |
| applicationContext.getBean('simpleBean') == 'Hello world!' |
| } |
| }</pre></div> |
| |
| |
| <a name="12.1.1 Unit Testing Controllers"><!-- Legacy link --></a> |
| <h2 id="unitTestingControllers">14.1.1 Unit Testing Controllers</h2> |
| <h4>The Basics</h4><p class="paragraph"/>You use the <code>grails.test.mixin.TestFor</code> annotation to unit test controllers. Using <code>TestFor</code> in this manner activates the <code>grails.test.mixin.web.ControllerUnitTestMixin</code> and its associated API. For example:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void <span class="java-quote">"test something"</span>() { |
| } |
| }</pre></div><p class="paragraph"/>Adding the <code>TestFor</code> annotation to a controller causes a new <code>controller</code> field to be automatically created for the controller under test.<p class="paragraph"/><blockquote class="note"> |
| The <code>TestFor</code> annotation will also automatically annotate any public methods starting with "test" with JUnit 4's @Test annotation. If any of your test method don't start with "test" just add this manually |
| </blockquote><p class="paragraph"/>To test the simplest "Hello World"-style example you can do the following:<p class="paragraph"/><div class="code"><pre>// Test class |
| class SimpleController { |
| def hello() { |
| render <span class="java-quote">"hello"</span> |
| } |
| }</pre></div><p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void <span class="java-quote">"test hello"</span>() { |
| when: |
| controller.hello()<p class="paragraph"/> then: |
| response.text == 'hello' |
| } |
| }</pre></div><p class="paragraph"/>The <code>response</code> object is an instance of <code>GrailsMockHttpServletResponse</code> (from the package <code>org.codehaus.groovy.grails.plugins.testing</code>) which extends Spring's <code>MockHttpServletResponse</code> class and has a number of useful methods for inspecting the state of the response.<p class="paragraph"/>For example to test a redirect you can use the <code>redirectedUrl</code> property:<p class="paragraph"/><div class="code"><pre>class SimpleController { |
| def index() { |
| redirect action: 'hello' |
| } |
| … |
| }</pre></div><p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test index'() { |
| when: |
| controller.index()<p class="paragraph"/> then: |
| response.redirectedUrl == '/simple/hello' |
| } |
| }</pre></div><p class="paragraph"/>Many actions make use of the parameter data associated with the request. For example, the 'sort', 'max', and 'offset' parameters are quite common. Providing these in the test is as simple as adding appropriate values to a special <code>params</code> variable:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(PersonController) |
| class PersonControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test list'() { |
| when: |
| params.sort = 'name' |
| params.max = 20 |
| params.offset = 0 |
| controller.list()<p class="paragraph"/> then: |
| // … |
| } |
| }</pre></div><p class="paragraph"/>You can even control what type of request the controller action sees by setting the <code>method</code> property of the mock request:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(PersonController) |
| class PersonControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test save'() { |
| when: |
| request.method = 'POST' |
| controller.save()<p class="paragraph"/> then: |
| // … |
| } |
| }</pre></div><p class="paragraph"/>This is particularly important if your actions do different things depending on the type of the request. Finally, you can mark a request as AJAX like so:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(PersonController) |
| class PersonControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test list'() { |
| when: |
| request.method = 'POST' |
| request.makeAjaxRequest() |
| controller.getPage()<p class="paragraph"/> then: |
| // … |
| } |
| }</pre></div><p class="paragraph"/>You only need to do this though if the code under test uses the <code>xhr</code> property on the request.<p class="paragraph"/><h4>Testing View Rendering</h4><p class="paragraph"/>To test view rendering you can inspect the state of the controller's <code>modelAndView</code> property (an instance of <code>org.springframework.web.servlet.ModelAndView</code>) or you can use the <code>view</code> and <code>model</code> properties provided by the mixin:<p class="paragraph"/><div class="code"><pre>class SimpleController { |
| def home() { |
| render view: <span class="java-quote">"homePage"</span>, model: [title: <span class="java-quote">"Hello World"</span>] |
| } |
| … |
| }</pre></div><p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test home'() { |
| when: |
| controller.home()<p class="paragraph"/> then: |
| view == '/simple/homePage' |
| model.title == 'Hello World' |
| } |
| }</pre></div><p class="paragraph"/>Note that the view string is the absolute view path, so it starts with a '/' and will include path elements, such as the directory named after the action's controller.<p class="paragraph"/><h4>Testing Template Rendering</h4><p class="paragraph"/>Unlike view rendering, template rendering will actually attempt to write the template directly to the response rather than returning a <code>ModelAndView</code> hence it requires a different approach to testing.<p class="paragraph"/>Consider the following controller action:<p class="paragraph"/><div class="code"><pre>class SimpleController { |
| def display() { |
| render template:<span class="java-quote">"snippet"</span> |
| } |
| }</pre></div><p class="paragraph"/>In this example the controller will look for a template in <code>grails-app/views/simple/_snippet.gsp</code>. You can test this as follows:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test display'() { |
| when: |
| controller.display()<p class="paragraph"/> then: |
| response.text == 'contents of the template' |
| } |
| }</pre></div><p class="paragraph"/>However, you may not want to render the real template, but just test that is was rendered. In this case you can provide mock Groovy Pages:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test display with mock template'() { |
| when: |
| views['/simple/_snippet.gsp'] = 'mock template contents' |
| controller.display()<p class="paragraph"/> then: |
| response.text == 'mock template contents' |
| } |
| }</pre></div><p class="paragraph"/><h4>Testing Actions Which Return A Map</h4><p class="paragraph"/>When a controller action returns a <code>java.util.Map</code> that <code>Map</code> may be inspected directly to assert that it contains the expected data:<p class="paragraph"/><div class="code"><pre>class SimpleController { |
| def showBookDetails() { |
| [title: 'The Nature Of Necessity', author: 'Alvin Plantinga'] |
| } |
| }</pre></div><p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test show book details'() { |
| when: |
| def model = controller.showBookDetails()<p class="paragraph"/> then: |
| model.author == 'Alvin Plantinga' |
| } |
| }</pre></div><p class="paragraph"/> |
| <h4>Testing XML and JSON Responses</h4><p class="paragraph"/>XML and JSON response are also written directly to the response. Grails' mocking capabilities provide some conveniences for testing XML and JSON response. For example consider the following action:<p class="paragraph"/><div class="code"><pre>def renderXml() { |
| render(contentType:<span class="java-quote">"text/xml"</span>) { |
| book(title:<span class="java-quote">"Great"</span>) |
| } |
| }</pre></div><p class="paragraph"/>This can be tested using the <code>xml</code> property of the response:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test render xml'() { |
| when: |
| controller.renderXml()<p class="paragraph"/> then: |
| response.text == <span class="java-quote">"<book title='Great'/>"</span> |
| response.xml.@title.text() == 'Great' |
| } |
| }</pre></div><p class="paragraph"/>The <code>xml</code> property is a parsed result from Groovy's <a href="http://groovy.codehaus.org/Reading+XML+using+Groovy's+XmlSlurper" target="blank">XmlSlurper</a> class which is very convenient for parsing XML.<p class="paragraph"/>Testing JSON responses is pretty similar, instead you use the <code>json</code> property:<p class="paragraph"/><div class="code"><pre>// controller action |
| def renderJson() { |
| render(contentType:<span class="java-quote">"application/json"</span>) { |
| book = <span class="java-quote">"Great"</span> |
| } |
| }</pre></div><p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test render json'() { |
| when: |
| controller.renderJson()<p class="paragraph"/> then: |
| response.text == '{<span class="java-quote">"book"</span>:<span class="java-quote">"Great"</span>}' |
| response.json.book == 'Great' |
| } |
| }</pre></div><p class="paragraph"/>The <code>json</code> property is an instance of <code>org.codehaus.groovy.grails.web.json.JSONElement</code> which is a map-like structure that is useful for parsing JSON responses.<p class="paragraph"/><h4>Testing XML and JSON Requests</h4><p class="paragraph"/>Grails provides various convenient ways to automatically parse incoming XML and JSON packets. For example you can bind incoming JSON or XML requests using Grails' data binding:<p class="paragraph"/><div class="code"><pre>def consumeBook(Book b) { |
| render <span class="java-quote">"The title is ${b.title}."</span> |
| }</pre></div><p class="paragraph"/>To test this Grails provides an easy way to specify an XML or JSON packet via the <code>xml</code> or <code>json</code> properties. For example the above action can be tested by specifying a String containing the XML:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| @Mock([Book]) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification { |
| void 'test consume book xml'() { |
| when: |
| request.xml = '<book><title>Wool</title></book>' |
| controller.consumeBook()<p class="paragraph"/> then: |
| response.text == 'The title is Wool.' |
| } |
| }</pre></div><p class="paragraph"/>Or alternatively a domain instance can be specified and it will be auto-converted into the appropriate XML request:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| @Mock([Book]) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test consume book xml'() { |
| when: |
| request.xml = <span class="java-keyword">new</span> Book(title: 'Shift') |
| controller.consumeBook()<p class="paragraph"/> then: |
| response.text == 'The title is Shift.' |
| } |
| }</pre></div><p class="paragraph"/>The same can be done for JSON requests:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| @Mock([Book]) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test consume book json'() { |
| when: |
| request.json = <span class="java-keyword">new</span> Book(title: 'Shift') |
| controller.consumeBook()<p class="paragraph"/> then: |
| response.text == 'The title is Shift.' |
| } |
| }</pre></div><p class="paragraph"/>If you prefer not to use Grails' data binding but instead manually parse the incoming XML or JSON that can be tested too. For example consider the controller action below:<p class="paragraph"/><div class="code"><pre>def consume() { |
| request.withFormat { |
| xml { |
| render <span class="java-quote">"The XML Title Is ${request.XML.@title}."</span> |
| } |
| json { |
| render <span class="java-quote">"The JSON Title Is ${request.JSON.title}."</span> |
| } |
| } |
| }</pre></div><p class="paragraph"/>To test the XML request you can specify the XML as a string:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test consume xml'() { |
| when: |
| request.xml = '<book title=<span class="java-quote">"The Stand"</span>/>' |
| controller.consume()<p class="paragraph"/> then: |
| response.text == 'The XML Title Is The Stand.' |
| }<p class="paragraph"/> void 'test consume json'() { |
| when: |
| request.json = '{title:<span class="java-quote">"The Stand"</span>}' |
| controller.consume()<p class="paragraph"/> then: |
| response.text == 'The JSON Title Is The Stand.' |
| } |
| }</pre></div><p class="paragraph"/><h4>Testing Mime Type Handling</h4><p class="paragraph"/>You can test mime type handling and the <code>withFormat</code> method quite simply by setting the request's <code>contentType</code> attribute:<p class="paragraph"/><div class="code"><pre>// controller action |
| def sayHello() { |
| def data = [Hello:<span class="java-quote">"World"</span>] |
| request.withFormat { |
| xml { render data as grails.converters.XML } |
| json { render data as grails.converters.JSON } |
| html data |
| } |
| }</pre></div><p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test say hello xml'() { |
| when: |
| request.contentType = 'application/xml' |
| controller.sayHello()<p class="paragraph"/> then: |
| response.text == '<?xml version=<span class="java-quote">"1.0"</span> encoding=<span class="java-quote">"UTF-8"</span>?><map><entry key=<span class="java-quote">"Hello"</span>>World</entry></map>' |
| }<p class="paragraph"/> void 'test say hello json'() { |
| when: |
| request.contentType = 'application/json' |
| controller.sayHello()<p class="paragraph"/> then: |
| response.text == '{<span class="java-quote">"Hello"</span>:<span class="java-quote">"World"</span>}' |
| } |
| }</pre></div><p class="paragraph"/>There are constants provided by <code>ControllerUnitTestMixin</code> for all of the common common content types as shown below:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test say hello xml'() { |
| when: |
| request.contentType = XML_CONTENT_TYPE |
| controller.sayHello()<p class="paragraph"/> then: |
| response.text == '<?xml version=<span class="java-quote">"1.0"</span> encoding=<span class="java-quote">"UTF-8"</span>?><map><entry key=<span class="java-quote">"Hello"</span>>World</entry></map>' |
| }<p class="paragraph"/> void 'test say hello json'() { |
| when: |
| request.contentType = JSON_CONTENT_TYPE |
| controller.sayHello()<p class="paragraph"/> then: |
| response.text == '{<span class="java-quote">"Hello"</span>:<span class="java-quote">"World"</span>}' |
| } |
| }</pre></div><p class="paragraph"/>The defined constants are listed below:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th><strong class="bold">Constant</strong></th><th><strong class="bold">Value</strong></th></tr><tr class="table-odd"><td>ALL_CONTENT_TYPE</td><td>*/*</td></tr><tr class="table-even"><td>FORM_CONTENT_TYPE</td><td>application/x-www-form-urlencoded</td></tr><tr class="table-odd"><td>MULTIPART_FORM_CONTENT_TYPE</td><td>multipart/form-data</td></tr><tr class="table-even"><td>HTML_CONTENT_TYPE</td><td>text/html</td></tr><tr class="table-odd"><td>XHTML_CONTENT_TYPE</td><td>application/xhtml+xml</td></tr><tr class="table-even"><td>XML_CONTENT_TYPE</td><td>application/xml</td></tr><tr class="table-odd"><td>JSON_CONTENT_TYPE</td><td>application/json</td></tr><tr class="table-even"><td>TEXT_XML_CONTENT_TYPE</td><td>text/xml</td></tr><tr class="table-odd"><td>TEXT_JSON_CONTENT_TYPE</td><td>text/json</td></tr><tr class="table-even"><td>HAL_JSON_CONTENT_TYPE</td><td>application/hal+json</td></tr><tr class="table-odd"><td>HAL_XML_CONTENT_TYPE</td><td>application/hal+xml</td></tr><tr class="table-even"><td>ATOM_XML_CONTENT_TYPE</td><td>application/atom+xml</td></tr></table><p class="paragraph"/><h4>Testing Duplicate Form Submissions</h4><p class="paragraph"/>Testing duplicate form submissions is a little bit more involved. For example if you have an action that handles a form such as:<p class="paragraph"/><div class="code"><pre>def handleForm() { |
| withForm { |
| render <span class="java-quote">"Good"</span> |
| }.invalidToken { |
| render <span class="java-quote">"Bad"</span> |
| } |
| }</pre></div><p class="paragraph"/>you want to verify the logic that is executed on a good form submission and the logic that is executed on a duplicate submission. Testing the bad submission is simple. Just invoke the controller:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test duplicate form submission'() { |
| when: |
| controller.handleForm()<p class="paragraph"/> then: |
| response.text == 'Bad' |
| } |
| }</pre></div><p class="paragraph"/>Testing the successful submission requires providing an appropriate <code>SynchronizerToken</code>:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/><span class="java-keyword">import</span> org.codehaus.groovy.grails.web.servlet.mvc.SynchronizerTokensHolder<p class="paragraph"/>@TestFor(SimpleController) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test valid form submission'() { |
| when: |
| def tokenHolder = SynchronizerTokensHolder.store(session)<p class="paragraph"/> params[SynchronizerTokensHolder.TOKEN_URI] = '/controller/handleForm' |
| params[SynchronizerTokensHolder.TOKEN_KEY] = tokenHolder.generateToken(params[SynchronizerTokensHolder.TOKEN_URI]) |
| controller.handleForm()<p class="paragraph"/> then: |
| response.text == 'Good' |
| } |
| }</pre></div><p class="paragraph"/>If you test both the valid and the invalid request in the same test be sure to reset the response between executions of the controller:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/><span class="java-keyword">import</span> org.codehaus.groovy.grails.web.servlet.mvc.SynchronizerTokensHolder<p class="paragraph"/>@TestFor(SimpleController) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test form submission'() { |
| when: |
| controller.handleForm()<p class="paragraph"/> then: |
| response.text == 'Bad'<p class="paragraph"/> when: |
| response.reset() |
| def tokenHolder = SynchronizerTokensHolder.store(session)<p class="paragraph"/> params[SynchronizerTokensHolder.TOKEN_URI] = '/controller/handleForm' |
| params[SynchronizerTokensHolder.TOKEN_KEY] = tokenHolder.generateToken(params[SynchronizerTokensHolder.TOKEN_URI]) |
| controller.handleForm()<p class="paragraph"/> then: |
| response.text == 'Good' |
| } |
| }</pre></div><p class="paragraph"/><h4>Testing File Upload</h4><p class="paragraph"/>You use the <code>GrailsMockMultipartFile</code> class to test file uploads. For example consider the following controller action:<p class="paragraph"/><div class="code"><pre>def uploadFile() { |
| MultipartFile file = request.getFile(<span class="java-quote">"myFile"</span>) |
| file.transferTo(<span class="java-keyword">new</span> File(<span class="java-quote">"/local/disk/myFile"</span>)) |
| }</pre></div><p class="paragraph"/>To test this action you can register a <code>GrailsMockMultipartFile</code> with the request:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/><span class="java-keyword">import</span> org.codehaus.groovy.grails.plugins.testing.GrailsMockMultipartFile<p class="paragraph"/>@TestFor(SimpleController) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test file upload'() { |
| when: |
| def file = <span class="java-keyword">new</span> GrailsMockMultipartFile('myFile', 'some file contents'.bytes) |
| request.addFile file |
| controller.uploadFile()<p class="paragraph"/> then: |
| file.targetFileLocation.path == '/local/disk/myFile' |
| } |
| }</pre></div><p class="paragraph"/>The <code>GrailsMockMultipartFile</code> constructor arguments are the name and contents of the file. It has a mock implementation of the <code>transferTo</code> method that simply records the <code>targetFileLocation</code> and doesn't write to disk.<p class="paragraph"/><h4>Testing Command Objects</h4><p class="paragraph"/>Special support exists for testing command object handling with the <code>mockCommandObject</code> method. For example consider the following action:<p class="paragraph"/><div class="code"><pre>class SimpleController { |
| def handleCommand(SimpleCommand simple) { |
| <span class="java-keyword">if</span>(simple.hasErrors()) { |
| render 'Bad' |
| } <span class="java-keyword">else</span> { |
| render 'Good' |
| } |
| } |
| }<p class="paragraph"/>class SimpleCommand { |
| <span class="java-object">String</span> name<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| name blank: <span class="java-keyword">false</span> |
| } |
| }</pre></div><p class="paragraph"/>To test this you mock the command object, populate it and then validate it as follows:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test valid command object'() { |
| given: |
| def simpleCommand = <span class="java-keyword">new</span> SimpleCommand(name: 'Hugh') |
| simpleCommand.validate()<p class="paragraph"/> when: |
| controller.handleCommand(simpleCommand)<p class="paragraph"/> then: |
| response.text == 'Good' |
| }<p class="paragraph"/> void 'test invalid command object'() { |
| given: |
| def simpleCommand = <span class="java-keyword">new</span> SimpleCommand(name: '') |
| simpleCommand.validate()<p class="paragraph"/> when: |
| controller.handleCommand(simpleCommand)<p class="paragraph"/> then: |
| response.text == 'Bad' |
| } |
| }</pre></div><p class="paragraph"/>The testing framework also supports allowing Grails to create the command object instance automatically. To test this invoke the no-arg version of the controller action method. Grails will create an instance of the command object, perform data binding on it using the request parameters and validate the object just like it does in when the application is running. See the test below.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test valid command object'() { |
| when: |
| params.name = 'Hugh' |
| controller.handleCommand()<p class="paragraph"/> then: |
| response.text == 'Good' |
| }<p class="paragraph"/> void 'test invalid command object'() { |
| when: |
| params.name = '' |
| controller.handleCommand()<p class="paragraph"/> then: |
| response.text == 'Bad' |
| } |
| }</pre></div><p class="paragraph"/><h4>Testing allowedMethods</h4><p class="paragraph"/>The unit testing environment respects the <a href="../ref/Controllers/allowedMethods.html" class="controllers">allowedMethods</a> property in controllers. If a controller action is limited to be accessed with certain request methods, the unit test must be constructed to deal with that.<p class="paragraph"/><div class="code"><pre>// grails-app/controllers/com/demo/DemoController.groovypackage com.demo<p class="paragraph"/>class DemoController {<p class="paragraph"/> <span class="java-keyword">static</span> allowedMethods = [save: 'POST', update: 'PUT', delete: 'DELETE']<p class="paragraph"/> def save() { |
| render 'Save was successful!' |
| }<p class="paragraph"/> // … |
| }</pre></div><p class="paragraph"/><div class="code"><pre>// test/unit/com/demo/DemoControllerSpec.groovy |
| <span class="java-keyword">package</span> com.demo<p class="paragraph"/><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification |
| <span class="java-keyword">import</span> <span class="java-keyword">static</span> javax.servlet.http.HttpServletResponse.*<p class="paragraph"/>@TestFor(DemoController) |
| class DemoControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void <span class="java-quote">"test a valid request method"</span>() { |
| when: |
| request.method = 'POST' |
| controller.save()<p class="paragraph"/> then: |
| response.status == SC_OK |
| response.text == 'Save was successful!' |
| }<p class="paragraph"/> void <span class="java-quote">"test an invalid request method"</span>() { |
| when: |
| request.method = 'DELETE' |
| controller.save()<p class="paragraph"/> then: |
| response.status == SC_METHOD_NOT_ALLOWED |
| } |
| }</pre></div><p class="paragraph"/><h4>Testing Calling Tag Libraries</h4><p class="paragraph"/>You can test calling tag libraries using <code>ControllerUnitTestMixin</code>, although the mechanism for testing the tag called varies from tag to tag. For example to test a call to the <code>message</code> tag, add a message to the <code>messageSource</code>. Consider the following action:<p class="paragraph"/><div class="code"><pre>def showMessage() { |
| render g.message(code: <span class="java-quote">"foo.bar"</span>) |
| }</pre></div><p class="paragraph"/>This can be tested as follows:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'test render message tag'() { |
| given: |
| messageSource.addMessage 'foo.bar', request.locale, 'Hello World'<p class="paragraph"/> when: |
| controller.showMessage()<p class="paragraph"/> then: |
| response.text == 'Hello World' |
| } |
| }</pre></div><p class="paragraph"/>See <a href="../guide/single.html#unitTestingTagLibraries" class="guide">unit testing tag libraries</a> for more information. |
| |
| |
| <a name="12.1.2 Unit Testing Tag Libraries"><!-- Legacy link --></a> |
| <h2 id="unitTestingTagLibraries">14.1.2 Unit Testing Tag Libraries</h2> |
| <h4>The Basics</h4><p class="paragraph"/>Tag libraries and GSP pages can be tested with the <code>grails.test.mixin.web.GroovyPageUnitTestMixin</code> mixin. To use the mixin declare which tag library is under test with the <code>TestFor</code> annotation:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleTagLib) |
| class SimpleTagLibSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void <span class="java-quote">"test something"</span>() { |
| } |
| }</pre></div><p class="paragraph"/>Adding the <code>TestFor</code> annotation to a TagLib class causes a new <code>tagLib</code> field to be automatically created for the TagLib class under test. |
| The tagLib field can be used to test calling tags as function calls. The return value of a function call is either a <a href="http://grails.org/doc/3.0.x/api/org/grails/buffer/StreamCharBuffer.html" class="api">StreamCharBuffer</a> instance or |
| the object returned from the tag closure when <a href="../guide/single.html#tagReturnValue" class="guide">returnObjectForTags</a> feature is used.<p class="paragraph"/>Note that if you are testing invocation of a custom tag from a controller you can combine the <code>ControllerUnitTestMixin</code> and the <code>GroovyPageUnitTestMixin</code> using the <code>Mock</code> annotation:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| @Mock(SimpleTagLib) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/>}</pre></div><p class="paragraph"/><h4>Testing Custom Tags</h4><p class="paragraph"/>The core Grails tags don't need to be enabled during testing, however custom tag libraries do. The <code>GroovyPageUnitTestMixin</code> class provides a <code>mockTagLib()</code> method that you can use to mock a custom tag library. For example consider the following tag library:<p class="paragraph"/><div class="code"><pre>class SimpleTagLib {<p class="paragraph"/> <span class="java-keyword">static</span> namespace = 's'<p class="paragraph"/> def hello = { attrs, body -> |
| out << <span class="java-quote">"Hello ${attrs.name ?: 'World'}"</span> |
| }<p class="paragraph"/> def bye = { attrs, body -> |
| out << <span class="java-quote">"Bye ${attrs.author.name ?: 'World'}"</span> |
| } |
| }</pre></div><p class="paragraph"/>You can test this tag library by using <code>TestFor</code> and supplying the name of the tag library:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleTagLib) |
| class SimpleTagLibSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void <span class="java-quote">"test hello tag"</span>() { |
| expect: |
| applyTemplate('<s:hello />') == 'Hello World' |
| applyTemplate('<s:hello name=<span class="java-quote">"Fred"</span> />') == 'Hello Fred' |
| applyTemplate('<s:bye author=<span class="java-quote">"${author}"</span> />', [author: <span class="java-keyword">new</span> Author(name: 'Fred')]) == 'Bye Fred' |
| }<p class="paragraph"/> void <span class="java-quote">"test tag calls"</span>() { |
| expect: |
| tagLib.hello().toString() == 'Hello World' |
| tagLib.hello(name: 'Fred').toString() == 'Hello Fred' |
| tagLib.bye(author: <span class="java-keyword">new</span> Author(name: 'Fred')).toString == 'Bye Fred' |
| } |
| }</pre></div><p class="paragraph"/>Alternatively, you can use the <code>TestMixin</code> annotation and mock multiple tag libraries using the <code>mockTagLib()</code> method:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> spock.lang.Specification |
| <span class="java-keyword">import</span> grails.test.mixin.TestMixin |
| <span class="java-keyword">import</span> grails.test.mixin.web.GroovyPageUnitTestMixin<p class="paragraph"/>@TestMixin(GroovyPageUnitTestMixin) |
| class MultipleTagLibSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void <span class="java-quote">"test multiple tags"</span>() { |
| given: |
| mockTagLib(SomeTagLib) |
| mockTagLib(SomeOtherTagLib)<p class="paragraph"/> expect: |
| // … |
| } |
| }</pre></div><p class="paragraph"/>The <code>GroovyPageUnitTestMixin</code> provides convenience methods for asserting that the template output equals or matches an expected value.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleTagLib) |
| class SimpleTagLibSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void <span class="java-quote">"test hello tag"</span>() { |
| expect: |
| assertOutputEquals ('Hello World', '<s:hello />') |
| assertOutputMatches (/.*Fred.*/, '<s:hello name=<span class="java-quote">"Fred"</span> />') |
| } |
| }</pre></div><p class="paragraph"/><h4>Testing View and Template Rendering</h4><p class="paragraph"/>You can test rendering of views and templates in <code>grails-app/views</code> via the <code>render(Map)</code> method provided by <code>GroovyPageUnitTestMixin</code> :<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> spock.lang.Specification |
| <span class="java-keyword">import</span> grails.test.mixin.TestMixin |
| <span class="java-keyword">import</span> grails.test.mixin.web.GroovyPageUnitTestMixin<p class="paragraph"/>@TestMixin(GroovyPageUnitTestMixin) |
| class RenderingSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void <span class="java-quote">"test rendering template"</span>() { |
| when: |
| def result = render(template: '/simple/hello')<p class="paragraph"/> then: |
| result == 'Hello World!' |
| } |
| }</pre></div><p class="paragraph"/>This will attempt to render a template found at the location <code>grails-app/views/simple/_hello.gsp</code>. Note that if the template depends on any custom tag libraries you need to call <code>mockTagLib</code> as described in the previous section.<p class="paragraph"/>Some core tags use the active controller and action as input. In GroovyPageUnitTestMixin tests, you can manually set the active controller and action name by setting controllerName and actionName properties on the webRequest object:<p class="paragraph"/><div class="code"><pre>webRequest.controllerName = 'simple' |
| webRequest.actionName = 'hello'</pre></div> |
| |
| |
| <a name="12.1.3 Unit Testing Domains"><!-- Legacy link --></a> |
| <h2 id="unitTestingDomains">14.1.3 Unit Testing Domains</h2> |
| <h4>Overview</h4><p class="paragraph"/>Domain class interaction can be tested without involving a real database connection using <code>DomainClassUnitTestMixin</code> or by using the <code>HibernateTestMixin</code>.<p class="paragraph"/>The GORM implementation in DomainClassUnitTestMixin is using a simple in-memory <code>ConcurrentHashMap</code> implementation. Note that this has limitations compared to a real GORM implementation.<p class="paragraph"/>A large, commonly-used portion of the GORM API can be mocked using <code>DomainClassUnitTestMixin</code> including: |
| <ul class="star"> |
| <li>Simple persistence methods like <code>save()</code>, <code>delete()</code> etc.</li> |
| <li>Dynamic Finders</li> |
| <li>Named Queries</li> |
| <li>Query-by-example</li> |
| <li>GORM Events</li> |
| </ul><p class="paragraph"/><code>HibernateTestMixin</code> uses Hibernate 4 and a H2 in-memory database. This makes it possible to use all GORM features also in Grails unit tests.<p class="paragraph"/>All features of GORM for Hibernate can be tested within a <code>HibernateTestMixin</code> unit test including: |
| <ul class="star"> |
| <li>String-based HQL queries</li> |
| <li>composite identifiers</li> |
| <li>dirty checking methods</li> |
| <li>any direct interaction with Hibernate</li> |
| </ul><p class="paragraph"/>The implementation behind <code>HibernateTestMixin</code> takes care of setting up the Hibernate with the in-memory H2 database. It only configures the given domain classes for use in a unit test. The @Domain annotation is used to tell which domain classes should be configured.<p class="paragraph"/> |
| <h4>DomainClassUnitTestMixin Basics</h4><p class="paragraph"/><code>DomainClassUnitTestMixin</code> is typically used in combination with testing either a controller, service or tag library where the domain is a mock collaborator defined by the <code>Mock</code> annotation:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(BookController) |
| @Mock(Book) |
| class BookControllerSpec <span class="java-keyword">extends</span> Specification { |
| // … |
| }</pre></div><p class="paragraph"/>The example above tests the <code>SimpleController</code> class and mocks the behavior of the <code>Simple</code> domain class as well. For example consider a typical scaffolded <code>save</code> controller action:<p class="paragraph"/><div class="code"><pre>class BookController { |
| def save() { |
| def book = <span class="java-keyword">new</span> Book(params) |
| <span class="java-keyword">if</span> (book.save(flush: <span class="java-keyword">true</span>)) { |
| flash.message = message( |
| code: '<span class="java-keyword">default</span>.created.message', |
| args: [message(code: 'book.label', <span class="java-keyword">default</span>: 'Book'), book.id]) |
| redirect(action: <span class="java-quote">"show"</span>, id: book.id) |
| } |
| <span class="java-keyword">else</span> { |
| render(view: <span class="java-quote">"create"</span>, model: [bookInstance: book]) |
| } |
| } |
| }</pre></div><p class="paragraph"/>Tests for this action can be written as follows:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(BookController) |
| @Mock(Book) |
| class BookControllerSpec <span class="java-keyword">extends</span> Specification { |
| void <span class="java-quote">"test saving an invalid book"</span>() { |
| when: |
| controller.save()<p class="paragraph"/> then: |
| model.bookInstance != <span class="java-keyword">null</span> |
| view == '/book/create' |
| }<p class="paragraph"/> void <span class="java-quote">"test saving a valid book"</span>() { |
| when: |
| params.title = <span class="java-quote">"The Stand"</span> |
| params.pages = <span class="java-quote">"500"</span><p class="paragraph"/> controller.save()<p class="paragraph"/> then: |
| response.redirectedUrl == '/book/show/1' |
| flash.message != <span class="java-keyword">null</span> |
| Book.count() == 1 |
| } |
| }</pre></div><p class="paragraph"/><code>Mock</code> annotation also supports a list of mock collaborators if you have more than one domain to mock:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(BookController) |
| @Mock([Book, Author]) |
| class BookControllerSpec <span class="java-keyword">extends</span> Specification { |
| // … |
| }</pre></div><p class="paragraph"/>Alternatively you can also use the <code>DomainClassUnitTestMixin</code> directly with the <code>TestMixin</code> annotation and then call the <code>mockDomain</code> method to mock domains during your test:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> grails.test.mixin.TestMixin |
| <span class="java-keyword">import</span> spock.lang.Specification |
| <span class="java-keyword">import</span> grails.test.mixin.domain.DomainClassUnitTestMixin<p class="paragraph"/>@TestFor(BookController) |
| @TestMixin(DomainClassUnitTestMixin) |
| class BookControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void setupSpec() { |
| mockDomain(Book) |
| }<p class="paragraph"/> void <span class="java-quote">"test saving an invalid book"</span>() { |
| when: |
| controller.save()<p class="paragraph"/> then: |
| model.bookInstance != <span class="java-keyword">null</span> |
| view == '/book/create' |
| }<p class="paragraph"/> void <span class="java-quote">"test saving a valid book"</span>() { |
| when: |
| params.title = <span class="java-quote">"The Stand"</span> |
| params.pages = <span class="java-quote">"500"</span><p class="paragraph"/> controller.save()<p class="paragraph"/> then: |
| response.redirectedUrl == '/book/show/1' |
| flash.message != <span class="java-keyword">null</span> |
| Book.count() == 1 |
| } |
| }</pre></div><p class="paragraph"/>The <code>mockDomain</code> method also includes an additional parameter that lets you pass a Map of Maps to configure a domain, which is useful for fixture-like data:<p class="paragraph"/><div class="code"><pre>mockDomain(Book, [ |
| [title: <span class="java-quote">"The Stand"</span>, pages: 1000], |
| [title: <span class="java-quote">"The Shining"</span>, pages: 400], |
| [title: <span class="java-quote">"Along Came a Spider"</span>, pages: 300] ])</pre></div><p class="paragraph"/><h4>Testing Constraints</h4><p class="paragraph"/>There are 3 types of validateable classes: |
| <ol> |
| <li>Domain classes</li> |
| <li>Classes which implement the <code>Validateable</code> trait</li> |
| <li>Command Objects which have been made validateable automatically</li> |
| </ol><p class="paragraph"/>These are all easily testable in a unit test with no special configuration necessary as long as the test method is marked with <code>TestFor</code> or explicitly applies the <code>GrailsUnitTestMixin</code> using <code>TestMixin</code>. See the examples below.<p class="paragraph"/><div class="code"><pre>// src/groovy/com/demo/MyValidateable.groovy |
| <span class="java-keyword">package</span> com.demo<p class="paragraph"/>class MyValidateable <span class="java-keyword">implements</span> grails.validation.Validateable { |
| <span class="java-object">String</span> name |
| <span class="java-object">Integer</span> age<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| name matches: /[A-Z].*/ |
| age range: 1..99 |
| } |
| }</pre></div><p class="paragraph"/><div class="code"><pre>// grails-app/domain/com/demo/Person.groovy |
| <span class="java-keyword">package</span> com.demo<p class="paragraph"/>class Person { |
| <span class="java-object">String</span> name<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| name matches: /[A-Z].*/ |
| } |
| }</pre></div><p class="paragraph"/><div class="code"><pre>// grails-app/controllers/com/demo/DemoController.groovy |
| <span class="java-keyword">package</span> com.demo<p class="paragraph"/>class DemoController {<p class="paragraph"/> def addItems(MyCommandObject co) { |
| <span class="java-keyword">if</span>(co.hasErrors()) { |
| render 'something went wrong' |
| } <span class="java-keyword">else</span> { |
| render 'items have been added' |
| } |
| } |
| }<p class="paragraph"/>class MyCommandObject { |
| <span class="java-object">Integer</span> numberOfItems<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| numberOfItems range: 1..10 |
| } |
| }</pre></div><p class="paragraph"/><div class="code"><pre>// test/unit/com/demo/PersonSpec.groovy |
| <span class="java-keyword">package</span> com.demo<p class="paragraph"/><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(Person) |
| class PersonSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void <span class="java-quote">"Test that name must begin with an upper <span class="java-keyword">case</span> letter"</span>() { |
| when: 'the name begins with a lower letter' |
| def p = <span class="java-keyword">new</span> Person(name: 'jeff')<p class="paragraph"/> then: 'validation should fail' |
| !p.validate()<p class="paragraph"/> when: 'the name begins with an upper <span class="java-keyword">case</span> letter' |
| p = <span class="java-keyword">new</span> Person(name: 'Jeff')<p class="paragraph"/> then: 'validation should pass' |
| p.validate() |
| } |
| }</pre></div><p class="paragraph"/><div class="code"><pre>// test/unit/com/demo/DemoControllerSpec.groovy |
| <span class="java-keyword">package</span> com.demo<p class="paragraph"/><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(DemoController) |
| class DemoControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'Test an invalid number of items'() { |
| when: |
| params.numberOfItems = 42 |
| controller.addItems()<p class="paragraph"/> then: |
| response.text == 'something went wrong' |
| }<p class="paragraph"/> void 'Test a valid number of items'() { |
| when: |
| params.numberOfItems = 8 |
| controller.addItems()<p class="paragraph"/> then: |
| response.text == 'items have been added' |
| } |
| }</pre></div><p class="paragraph"/><div class="code"><pre>// test/unit/com/demo/MyValidateableSpec.groovy |
| <span class="java-keyword">package</span> com.demo<p class="paragraph"/><span class="java-keyword">import</span> grails.test.mixin.TestMixin |
| <span class="java-keyword">import</span> grails.test.mixin.support.GrailsUnitTestMixin |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/> |
| @TestMixin(GrailsUnitTestMixin) |
| class MyValidateableSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'Test validate can be invoked in a unit test with no special configuration'() { |
| when: 'an object is valid' |
| def validateable = <span class="java-keyword">new</span> MyValidateable(name: 'Kirk', age: 47)<p class="paragraph"/> then: 'validate() returns <span class="java-keyword">true</span> and there are no errors' |
| validateable.validate() |
| !validateable.hasErrors() |
| validateable.errors.errorCount == 0<p class="paragraph"/> when: 'an object is invalid' |
| validateable.name = 'kirk'<p class="paragraph"/> then: 'validate() returns <span class="java-keyword">false</span> and the appropriate error is created' |
| !validateable.validate() |
| validateable.hasErrors() |
| validateable.errors.errorCount == 1 |
| validateable.errors['name'].code == 'matches.invalid'<p class="paragraph"/> when: 'the clearErrors() is called' |
| validateable.clearErrors()<p class="paragraph"/> then: 'the errors are gone' |
| !validateable.hasErrors() |
| validateable.errors.errorCount == 0<p class="paragraph"/> when: 'the object is put back in a valid state' |
| validateable.name = 'Kirk'<p class="paragraph"/> then: 'validate() returns <span class="java-keyword">true</span> and there are no errors' |
| validateable.validate() |
| !validateable.hasErrors() |
| validateable.errors.errorCount == 0 |
| } |
| }</pre></div><p class="paragraph"/><div class="code"><pre>// test/unit/com/demo/MyCommandObjectSpec.groovy |
| <span class="java-keyword">package</span> com.demo<p class="paragraph"/><span class="java-keyword">import</span> grails.test.mixin.TestMixin |
| <span class="java-keyword">import</span> grails.test.mixin.support.GrailsUnitTestMixin |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestMixin(GrailsUnitTestMixin) |
| class MyCommandObjectSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void 'Test that numberOfItems must be between 1 and 10'() { |
| when: 'numberOfItems is less than 1' |
| def co = <span class="java-keyword">new</span> MyCommandObject() |
| co.numberOfItems = 0<p class="paragraph"/> then: 'validation fails' |
| !co.validate() |
| co.hasErrors() |
| co.errors['numberOfItems'].code == 'range.toosmall'<p class="paragraph"/> when: 'numberOfItems is greater than 10' |
| co.numberOfItems = 11<p class="paragraph"/> then: 'validation fails' |
| !co.validate() |
| co.hasErrors() |
| co.errors['numberOfItems'].code == 'range.toobig'<p class="paragraph"/> when: 'numberOfItems is greater than 1' |
| co.numberOfItems = 1<p class="paragraph"/> then: 'validation succeeds' |
| co.validate() |
| !co.hasErrors()<p class="paragraph"/> when: 'numberOfItems is greater than 10' |
| co.numberOfItems = 10<p class="paragraph"/> then: 'validation succeeds' |
| co.validate() |
| !co.hasErrors() |
| } |
| }</pre></div><p class="paragraph"/>That's it for testing constraints. One final thing we would like to say is that testing the constraints in this way catches a common error: typos in the "constraints" property name which is a mistake that is easy to make and equally easy to overlook. A unit test for your constraints will highlight the problem straight away.<p class="paragraph"/> |
| <h4>HibernateTestMixin Basics</h4><p class="paragraph"/><code>HibernateTestMixin</code> allows Hibernate 4 to be used in Grails unit tests. It uses a H2 in-memory database.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestMixin |
| <span class="java-keyword">import</span> grails.test.mixin.gorm.Domain |
| <span class="java-keyword">import</span> grails.test.mixin.hibernate.HibernateTestMixin |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/> |
| @Domain(Person) |
| @TestMixin(HibernateTestMixin) |
| class PersonSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void <span class="java-quote">"Test count people"</span>() { |
| expect: <span class="java-quote">"Test execute Hibernate count query"</span> |
| Person.count() == 0 |
| sessionFactory != <span class="java-keyword">null</span> |
| transactionManager != <span class="java-keyword">null</span> |
| session != <span class="java-keyword">null</span> |
| } |
| }</pre></div><p class="paragraph"/>This library dependency is required in grails-app/conf/BuildConfig.groovy for adding support for <code>HibernateTestMixin</code>.<p class="paragraph"/><div class="code"><pre>dependencies { |
| test 'org.grails:grails-datastore-test-support:1.0-grails-2.4' |
| }</pre></div><p class="paragraph"/>HibernateTestMixin is only supported with hibernate4 plugin versions >= 4.3.5.4 . |
| <div class="code"><pre>plugins { |
| runtime ':hibernate4:4.3.5.4' |
| }</pre></div><p class="paragraph"/> |
| <h4>Configuring domain classes for HibernateTestMixin tests</h4><p class="paragraph"/>The <code>grails.test.mixin.gorm.Domain</code> annotation is used to configure the list of domain classes to configure for Hibernate sessionFactory instance that gets configured when the unit test runtime is initialized.<p class="paragraph"/><code>Domain</code> annotations will be collected from several locations: |
| <ul class="star"> |
| <li>the annotations on the test class</li> |
| <li>the package annotations in the package-info.java/package-info.groovy file in the package of the test class</li> |
| <li>each super class of the test class and their respective package annotations</li> |
| <li>the possible <code><a href="http://grails.org/doc/3.0.x/api/grails/test/runtime/SharedRuntime.html" class="api">SharedRuntime</a></code> class</li> |
| </ul><p class="paragraph"/><code>Domain</code> annotations can be shared by adding them as package annotations to package-info.java/package-info.groovy files or by adding them to a <code><a href="http://grails.org/doc/3.0.x/api/grails/test/runtime/SharedRuntime.html" class="api">SharedRuntime</a></code> class which has been added for the test.<p class="paragraph"/>It's not possible to use DomainClassUnitTestMixin's <code>Mock</code> annotation in HibernateTestMixin tests. Use the <code>Domain</code> annotation in the place of <code>Mock</code> in HibernateTestMixin tests. |
| |
| <a name="12.1.4 Unit Testing Filters"><!-- Legacy link --></a> |
| <h2 id="unitTestingFilters">14.1.4 Unit Testing Filters</h2> |
| Unit testing filters is typically a matter of testing a controller where a filter is a mock collaborator. For example consider the following filters class:<p class="paragraph"/><div class="code"><pre>class CancellingFilters { |
| def filters = { |
| all(controller:<span class="java-quote">"simple"</span>, action:<span class="java-quote">"list"</span>) { |
| before = { |
| redirect(controller:<span class="java-quote">"book"</span>) |
| <span class="java-keyword">return</span> <span class="java-keyword">false</span> |
| } |
| } |
| } |
| }</pre></div><p class="paragraph"/>This filter interceptors the <code>list</code> action of the <code>simple</code> controller and redirects to the <code>book</code> controller. To test this filter you start off with a test that targets the <code>SimpleController</code> class and add the <code>CancellingFilters</code> as a mock collaborator:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| @Mock(CancellingFilters) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> // ...<p class="paragraph"/>}</pre></div><p class="paragraph"/>You can then implement a test that uses the <code>withFilters</code> method to wrap the call to an action in filter execution:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SimpleController) |
| @Mock(CancellingFilters) |
| class SimpleControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void <span class="java-quote">"test list action is filtered"</span>() { |
| when: |
| withFilters(action:<span class="java-quote">"list"</span>) { |
| controller.list() |
| }<p class="paragraph"/> then: |
| response.redirectedUrl == '/book' |
| } |
| }</pre></div><p class="paragraph"/>Note that the <code>action</code> parameter is required because it is unknown what the action to invoke is until the action is actually called. The <code>controller</code> parameter is optional and taken from the controller under test. If it is another controller you are testing then you can specify it:<p class="paragraph"/><div class="code"><pre>withFilters(controller:<span class="java-quote">"book"</span>,action:<span class="java-quote">"list"</span>) { |
| controller.list() |
| }</pre></div> |
| |
| |
| <a name="12.1.5 Unit Testing URL Mappings"><!-- Legacy link --></a> |
| <h2 id="unitTestingURLMappings">14.1.5 Unit Testing URL Mappings</h2> |
| <h4>The Basics</h4><p class="paragraph"/>Testing URL mappings can be done with the <code>TestFor</code> annotation testing a particular URL mappings class. For example to test the default URL mappings you can do the following:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> com.demo.SimpleController |
| <span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(UrlMappings) |
| @Mock(SimpleController) |
| class UrlMappingsSpec <span class="java-keyword">extends</span> Specification { |
| // … |
| }</pre></div><p class="paragraph"/>As you can see, any controller that is the target of a URL mapping that you're testing <em class="italic">must</em> be added to the <code>@Mock</code> annotation.<p class="paragraph"/><blockquote class="note"> |
| Note that since the default <code>UrlMappings</code> class is in the default package your test must also be in the default package |
| </blockquote><p class="paragraph"/>With that done there are a number of useful methods that are defined by the <code>grails.test.mixin.web.UrlMappingsUnitTestMixin</code> for testing URL mappings. These include: |
| <ul class="star"> |
| <li><code>assertForwardUrlMapping</code> - Asserts a URL mapping is forwarded for the given controller class (note that controller will need to be defined as a mock collaborate for this to work)</li> |
| <li><code>assertReverseUrlMapping</code> - Asserts that the given URL is produced when reverse mapping a link to a given controller and action</li> |
| <li><code>assertUrlMapping</code> - Asserts a URL mapping is valid for the given URL. This combines the <code>assertForwardUrlMapping</code> and <code>assertReverseUrlMapping</code> assertions</li> |
| </ul><p class="paragraph"/><h4>Asserting Forward URL Mappings</h4><p class="paragraph"/>You use <code>assertForwardUrlMapping</code> to assert that a given URL maps to a given controller. For example, consider the following URL mappings:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/actionOne"</span>(controller: <span class="java-quote">"simple"</span>, action: <span class="java-quote">"action1"</span>) |
| <span class="java-quote">"/actionTwo"</span>(controller: <span class="java-quote">"simple"</span>, action: <span class="java-quote">"action2"</span>) |
| }</pre></div><p class="paragraph"/>The following test can be written to assert these URL mappings:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> com.demo.SimpleController |
| <span class="java-keyword">import</span> grails.test.mixin.TestFor |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(UrlMappings) |
| @Mock(SimpleController) |
| class UrlMappingsSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> void <span class="java-quote">"test forward mappings"</span>() { |
| expect: |
| assertForwardUrlMapping(<span class="java-quote">"/actionOne"</span>, controller: 'simple', action: <span class="java-quote">"action1"</span>) |
| assertForwardUrlMapping(<span class="java-quote">"/actionTwo"</span>, controller: 'simple', action: <span class="java-quote">"action2"</span>) |
| } |
| }</pre></div><p class="paragraph"/><h4>Assert Reverse URL Mappings</h4><p class="paragraph"/>You use <code>assertReverseUrlMapping</code> to check that correct links are produced for your URL mapping when using the <code>link</code> tag in GSP views. An example test is largely identical to the previous listing except you use <code>assertReverseUrlMapping</code> instead of <code>assertForwardUrlMapping</code>. Note that you can combine these 2 assertions with <code>assertUrlMapping</code>. |
| |
| |
| <a name="12.1.6 Mocking Collaborators"><!-- Legacy link --></a> |
| <h2 id="mockingCollaborators">14.1.6 Mocking Collaborators</h2> |
| The Spock Framework manual has a chapter on <a href="http://spock-framework.readthedocs.org/en/latest/interaction_based_testing.html" target="blank">Interaction Based Testing</a> which also explains mocking collaborators. |
| |
| <a name="12.1.7 Mocking Codecs"><!-- Legacy link --></a> |
| <h2 id="mockingCodecs">14.1.7 Mocking Codecs</h2> |
| The <code>GrailsUnitTestMixin</code> provides a <code>mockCodec</code> method for mocking <a href="../guide/single.html#codecs" class="guide">custom codecs</a> which may be invoked while a unit test is running.<p class="paragraph"/><div class="code"><pre>mockCodec(MyCustomCodec)</pre></div><p class="paragraph"/>Failing to mock a codec which is invoked while a unit test is running may result in a MissingMethodException. |
| |
| |
| <a name="12.1.8 Unit Test Metaprogramming"><!-- Legacy link --></a> |
| <h2 id="unitTestMetaprogramming">14.1.8 Unit Test Metaprogramming</h2> |
| If runtime metaprogramming needs to be done in a unit test it needs to be done early in the process before the unit testing environment is fully initialized. This should be done when the unit test class is being initialized. For a Spock based test this should be done in the <code>setupSpec()</code> method. For a JUnit test this should be done in a method marked with <code>@BeforeClass</code>.<p class="paragraph"/> |
| <div class="code"><pre><span class="java-keyword">package</span> myapp<p class="paragraph"/><span class="java-keyword">import</span> grails.test.mixin.* |
| <span class="java-keyword">import</span> spock.lang.Specification<p class="paragraph"/>@TestFor(SomeController) |
| class SomeControllerSpec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> |
| def setupSpec() { |
| SomeClass.metaClass.someMethod = { -> |
| // <span class="java-keyword">do</span> something here |
| } |
| }<p class="paragraph"/> // … |
| }</pre></div><p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> myapp<p class="paragraph"/><span class="java-keyword">import</span> grails.test.mixin.* |
| <span class="java-keyword">import</span> org.junit.*<p class="paragraph"/>@TestFor(SomeController) |
| class SomeControllerTests {<p class="paragraph"/> @BeforeClass |
| <span class="java-keyword">static</span> void metaProgramController() { |
| SomeClass.metaClass.someMethod = { -> |
| // <span class="java-keyword">do</span> something here |
| } |
| }<p class="paragraph"/> // ...<p class="paragraph"/>}</pre></div> |
| |
| |
| <a name="12.2 Integration Testing"><!-- Legacy link --></a> |
| <h2 id="integrationTesting">14.2 Integration Testing</h2> |
| Integration tests differ from unit tests in that you have full access to the Grails environment within the test. You can create an integration test using the <a href="../ref/Command Line/create-integration-test.html" class="commandLine">create-integration-test</a> command:<p class="paragraph"/><div class="code"><pre>$ grails create-integration-test Example</pre></div><p class="paragraph"/>The above command will create a new integration test at the location <code>src/integration-test/groovy/<PACKAGE>/ExampleSpec.groovy</code>.<p class="paragraph"/>Grails uses the test environment for integration tests and loads the application prior to the first test run. All tests use the same application state.<p class="paragraph"/><h4>Transactions</h4><p class="paragraph"/>Integration tests run inside a database transaction by default, which is rolled back at the end of the each test. This means that data saved during a test is not persisted to the database (which is shared across all tests). The default generated integration test template includes the <a href="http://grails.org/doc/3.0.x/api/grails/transaction/Rollback.html" class="api">Rollback</a> annotation:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.mixin.integration.Integration |
| <span class="java-keyword">import</span> grails.transaction.* |
| <span class="java-keyword">import</span> spock.lang.*<p class="paragraph"/>@Integration |
| @Rollback |
| class <code>artifact.name</code>Spec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> ...<p class="paragraph"/> void <span class="java-quote">"test something"</span>() { |
| expect:<span class="java-quote">"fix me"</span> |
| <span class="java-keyword">true</span> == <span class="java-keyword">false</span> |
| } |
| }</pre></div><p class="paragraph"/>The <code>Rollback</code> annotation ensures that each test methods runs in a transaction that is rolled back. Generally this is desirable because you do not want your tests depending on order or application state.<p class="paragraph"/>If you do have a series of tests that will share state you can remove the <code>Rollback</code> and the last test in the suite should feature the <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/test/annotation/DirtiesContext.html" class="api">DirtiesContext</a> annotation which will shutdown the environment and restart it fresh (note that this will have an impact on test run times).<p class="paragraph"/><h4>Autowiring</h4><p class="paragraph"/>To obtain a reference to a bean you can use the <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/beans/factory/annotation/Autowired.html" class="api">Autowired</a> annotation. For example:<p class="paragraph"/><div class="code"><pre>… |
| <span class="java-keyword">import</span> org.springframework.beans.factory.annotation.*<p class="paragraph"/>@Integration |
| @Rollback |
| class <code>artifact.name</code>Spec <span class="java-keyword">extends</span> Specification {<p class="paragraph"/> @Autowired |
| ExampleService exampleService |
| ...<p class="paragraph"/> void <span class="java-quote">"Test example service"</span>() { |
| expect: |
| exampleService.countExamples() == 0 |
| } |
| }</pre></div><p class="paragraph"/> |
| <h4>Testing Controllers</h4><p class="paragraph"/>To integration test controllers it is recommended you use <a href="../ref/Command Line/create-functional-test.html" class="commandLine">create-functional-test</a> command to create a Geb functional test. See the following section on functional testing for more information. |
| |
| |
| <a name="12.3 Functional Testing"><!-- Legacy link --></a> |
| <h2 id="functionalTesting">14.3 Functional Testing</h2> |
| Functional tests involve making HTTP requests against the running application and verifying the resultant behaviour. The functional testing phase differs from the integration phase in that the Grails application is now listening and responding to actual HTTP requests. This is useful for end-to-end testing scenarios, such as making REST calls against a JSON API.<p class="paragraph"/>Grails by default ships with support for writing functional tests using the <a href="http://www.gebish.org" target="blank">Geb framework</a>. To create a functional test you can use the <code>create-functional-test</code> command which will create a new functional test:<p class="paragraph"/><div class="code"><pre>$ grails create-functional-test MyFunctional</pre></div><p class="paragraph"/>The above command will create a new Spock spec called <code>MyFunctionalSpec.groovy</code> in the <code>src/test/groovy</code> directory. The test is annotated with the <a href="http://grails.org/doc/3.0.x/api/grails/test/mixin/integration/Integration.html" class="api">Integration</a> annotation to indicate it is a integration test and extends the <code>GebSpec</code> super class:<p class="paragraph"/><div class="code"><pre>@Integration |
| class HomeSpec <span class="java-keyword">extends</span> GebSpec {<p class="paragraph"/> def setup() { |
| }<p class="paragraph"/> def cleanup() { |
| }<p class="paragraph"/> void <span class="java-quote">"Test the home page renders correctly"</span>() { |
| when:<span class="java-quote">"The home page is visited"</span> |
| go '/'<p class="paragraph"/> then:<span class="java-quote">"The title is correct"</span> |
| $('title').text() == <span class="java-quote">"Welcome to Grails"</span> |
| } |
| }</pre></div><p class="paragraph"/>When the test is run the application container will be loaded up in the background and you can send requests to the running application using the Geb API.<p class="paragraph"/>Note that the application is only loaded once for the entire test run, so functional tests share the state of the application across the whole suite.<p class="paragraph"/>In addition the application is loaded in the JVM as the test, this means that the test has full access to the application state and can interact directly with data services such as GORM to setup and cleanup test data.<p class="paragraph"/>The <code>Integration</code> annotation supports an optional <code>applicationClass</code> attribute which may be used to specify the application class to use for the functional test. The class must extend <a href="http://grails.org/doc/3.0.x/api/grails/boot/config/GrailsAutoConfiguration.html" class="api">GrailsAutoConfiguration</a>.<p class="paragraph"/><div class="code"><pre>@Integration(applicationClass=com.demo.Application) |
| class HomeSpec <span class="java-keyword">extends</span> GebSpec {<p class="paragraph"/> // ...<p class="paragraph"/>}</pre></div><p class="paragraph"/>If the <code>applicationClass</code> is not specified then the test runtime environment will attempt to locate the application class dynamically which can be problematic in multiproject builds where multiple application classes may be present. |
| |
| |
| <a name="13. Internationalization"><!-- Legacy link --></a> |
| <h1 id="i18n">15 Internationalization</h1> |
| Grails supports Internationalization (i18n) out of the box by leveraging the underlying Spring MVC internationalization support. With Grails you are able to customize the text that appears in a view based on the user's Locale. To quote the javadoc for the <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Locale.html" class="api">Locale</a> class:<p class="paragraph"/><blockquote class="quote"> |
| A Locale object represents a specific geographical, political, or cultural region. An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user. For example, displaying a number is a locale-sensitive operation--the number should be formatted according to the customs/conventions of the user's native country, region, or culture. |
| </blockquote><p class="paragraph"/>A Locale is made up of a <a href="http://www.loc.gov/standards/iso639-2/php/English_list.php" target="blank">language code</a> and a <a href="http://www.iso.org/iso/country_codes/iso_3166_code_lists/country_names_and_code_elements.htm" target="blank">country code</a>. For example "en_US" is the code for US English, whilst "en_GB" is the code for British English. |
| |
| |
| <a name="13.1 Understanding Message Bundles"><!-- Legacy link --></a> |
| <h2 id="understandingMessageBundles">15.1 Understanding Message Bundles</h2> |
| Now that you have an idea of locales, to use them in Grails you create message bundle file containing the different languages that you wish to render. Message bundles in Grails are located inside the <code>grails-app/i18n</code> directory and are simple Java properties files.<p class="paragraph"/>Each bundle starts with the name <code>messages</code> by convention and ends with the locale. Grails ships with several message bundles for a whole range of languages within the <code>grails-app/i18n</code> directory. For example: |
| <ul class="star"> |
| <li>messages.properties</li> |
| <li>messages_da.properties</li> |
| <li>messages_de.properties</li> |
| <li>messages_es.properties</li> |
| <li>messages_fr.properties</li> |
| <li>...</li> |
| </ul><p class="paragraph"/>By default Grails looks in <code>messages.properties</code> for messages unless the user has specified a locale. You can create your own message bundle by simply creating a new properties file that ends with the locale you are interested. For example <code>messages_en_GB.properties</code> for British English. |
| |
| |
| <a name="13.2 Changing Locales"><!-- Legacy link --></a> |
| <h2 id="changingLocales">15.2 Changing Locales</h2> |
| By default the user locale is detected from the incoming <code>Accept-Language</code> header. However, you can provide users the capability to switch locales by simply passing a parameter called <code>lang</code> to Grails as a request parameter:<p class="paragraph"/><div class="code"><pre>/book/list?lang=es</pre></div><p class="paragraph"/>Grails will automatically switch the user's locale and store it in a cookie so subsequent requests will have the new header. |
| |
| |
| <a name="13.3 Reading Messages"><!-- Legacy link --></a> |
| <h2 id="readingMessages">15.3 Reading Messages</h2> |
| <h4>Reading Messages in the View</h4><p class="paragraph"/>The most common place that you need messages is inside the view. Use the <a href="../ref/Tags/message.html" class="tags">message</a> tag for this:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:message code=<span class="xml-quote">"my.localized.content"</span> /></span></pre></div><p class="paragraph"/>As long as you have a key in your <code>messages.properties</code> (with appropriate locale suffix) such as the one below then Grails will look up the message:<p class="paragraph"/><div class="code"><pre>my.localized.content=Hola, Me llamo John. Hoy es domingo.</pre></div><p class="paragraph"/>Messages can also include arguments, for example:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:message code=<span class="xml-quote">"my.localized.content"</span> args=<span class="xml-quote">"${ ['Juan', 'lunes'] }"</span> /></span></pre></div><p class="paragraph"/>The message declaration specifies positional parameters which are dynamically specified:<p class="paragraph"/><div class="code"><pre>my.localized.content=Hola, Me llamo {0}. Hoy es {1}.</pre></div><p class="paragraph"/><h4>Reading Messages in Controllers and Tag Libraries</h4><p class="paragraph"/>It's simple to read messages in a controller since you can invoke tags as methods:<p class="paragraph"/><div class="code"><pre>def show() { |
| def msg = message(code: <span class="java-quote">"my.localized.content"</span>, args: ['Juan', 'lunes']) |
| }</pre></div><p class="paragraph"/>The same technique can be used in <a href="../guide/single.html#taglibs" class="guide">tag libraries</a>, but if your tag library uses a custom <a href="../guide/single.html#namespaces" class="guide">namespace</a> then you must prefix the call with <code>g.</code>:<p class="paragraph"/><div class="code"><pre>def myTag = { attrs, body -> |
| def msg = g.message(code: <span class="java-quote">"my.localized.content"</span>, args: ['Juan', 'lunes']) |
| }</pre></div> |
| |
| |
| <a name="13.4 Scaffolding and i18n"><!-- Legacy link --></a> |
| <h2 id="scaffoldingAndI18n">15.4 Scaffolding and i18n</h2> |
| Grails <a href="../guide/single.html#scaffolding" class="guide">scaffolding</a> templates for controllers and views are fully i18n-aware. The GSPs use the <a href="../ref/Tags/message.html" class="tags">message</a> tag for labels, buttons etc. and controller <code>flash</code> messages use i18n to resolve locale-specific messages.<p class="paragraph"/>The scaffolding includes locale specific labels for domain classes and domain fields. For example, if you have a <code>Book</code> domain class with a <code>title</code> field:<p class="paragraph"/><div class="code"><pre>class Book { |
| <span class="java-object">String</span> title |
| }</pre></div><p class="paragraph"/>The scaffolding will use labels with the following keys:<p class="paragraph"/><div class="code"><pre>book.label = Libro |
| book.title.label = TÃtulo del libro</pre></div><p class="paragraph"/>You can use this property pattern if you'd like or come up with one of your own. There is nothing special about the use of the word <code>label</code> as part of the key other than it's the convention used by the scaffolding. |
| |
| |
| <a name="14. Security"><!-- Legacy link --></a> |
| <h1 id="security">16 Security</h1> |
| Grails is no more or less secure than Java Servlets. However, Java servlets (and hence Grails) are extremely secure and largely immune to common buffer overrun and malformed URL exploits due to the nature of the Java Virtual Machine underpinning the code.<p class="paragraph"/>Web security problems typically occur due to developer naivety or mistakes, and there is a little Grails can do to avoid common mistakes and make writing secure applications easier to write.<p class="paragraph"/><h4>What Grails Automatically Does</h4><p class="paragraph"/>Grails has a few built in safety mechanisms by default. |
| <ol> |
| <li>All standard database access via <a href="../guide/single.html#GORM" class="guide">GORM</a> domain objects is automatically SQL escaped to prevent SQL injection attacks</li> |
| <li>The default <a href="../guide/single.html#scaffolding" class="guide">scaffolding</a> templates HTML escape all data fields when displayed</li> |
| <li>Grails link creating tags (<a href="../ref/Tags/link.html" class="tags">link</a>, <a href="../ref/Tags/form.html" class="tags">form</a>, <a href="../ref/Tags/createLink.html" class="tags">createLink</a>, <a href="../ref/Tags/createLinkTo.html" class="tags">createLinkTo</a> and others) all use appropriate escaping mechanisms to prevent code injection</li> |
| <li>Grails provides <a href="../guide/single.html#codecs" class="guide">codecs</a> to let you trivially escape data when rendered as HTML, JavaScript and URLs to prevent injection attacks here.</li> |
| </ol><p class="paragraph"/> |
| |
| <a name="14.1 Securing Against Attacks"><!-- Legacy link --></a> |
| <h2 id="securingAgainstAttacks">16.1 Securing Against Attacks</h2> |
| <h4>SQL injection</h4><p class="paragraph"/>Hibernate, which is the technology underlying GORM domain classes, automatically escapes data when committing to database so this is not an issue. However it is still possible to write bad dynamic HQL code that uses unchecked request parameters. For example doing the following is vulnerable to HQL injection attacks:<p class="paragraph"/><div class="code"><pre>def vulnerable() { |
| def books = Book.find(<span class="java-quote">"from Book as b where b.title ='"</span> + params.title + <span class="java-quote">"'"</span>) |
| }</pre></div><p class="paragraph"/>or the analogous call using a GString:<p class="paragraph"/><div class="code"><pre>def vulnerable() { |
| def books = Book.find(<span class="java-quote">"from Book as b where b.title ='${params.title}'"</span>) |
| }</pre></div><p class="paragraph"/>Do <strong class="bold">not</strong> do this. Use named or positional parameters instead to pass in parameters:<p class="paragraph"/><div class="code"><pre>def safe() { |
| def books = Book.find(<span class="java-quote">"from Book as b where b.title = ?"</span>, |
| [params.title]) |
| }</pre></div><p class="paragraph"/>or<p class="paragraph"/><div class="code"><pre>def safe() { |
| def books = Book.find(<span class="java-quote">"from Book as b where b.title = :title"</span>, |
| [title: params.title]) |
| }</pre></div><p class="paragraph"/><h4>Phishing</h4><p class="paragraph"/>This really a public relations issue in terms of avoiding hijacking of your branding and a declared communication policy with your customers. Customers need to know how to identify valid emails.<p class="paragraph"/><h4>XSS - cross-site scripting injection</h4><p class="paragraph"/>It is important that your application verifies as much as possible that incoming requests were originated from your application and not from another site. It is also important to ensure that all data values rendered into views are escaped correctly. For example when rendering to HTML or XHTML you must ensure that people cannot maliciously inject JavaScript or other HTML into data or tags viewed by others.<p class="paragraph"/>Grails 2.3 and above include special support for automatically encoded data placed into GSP pages. See the documentation on <a href="../guide/single.html#xssPrevention" class="guide">Cross Site Scripting (XSS) prevention</a> for further information.<p class="paragraph"/>You must also avoid the use of request parameters or data fields for determining the next URL to redirect the user to. If you use a <code>successURL</code> parameter for example to determine where to redirect a user to after a successful login, attackers can imitate your login procedure using your own site, and then redirect the user back to their own site once logged in, potentially allowing JavaScript code to then exploit the logged-in account on the site.<p class="paragraph"/><h4>Cross-site request forgery</h4><p class="paragraph"/>CSRF involves unauthorized commands being transmitted from a user that a website trusts. A typical example would be another website embedding a link to perform an action on your website if the user is still authenticated.<p class="paragraph"/>The best way to decrease risk against these types of attacks is to use the <code>useToken</code> attribute on your forms. See <a href="../guide/single.html#formtokens" class="guide">Handling Duplicate Form Submissions</a> for more information on how to use it. An additional measure would be to not use remember-me cookies.<p class="paragraph"/><h4>HTML/URL injection</h4><p class="paragraph"/>This is where bad data is supplied such that when it is later used to create a link in a page, clicking it will not cause the expected behaviour, and may redirect to another site or alter request parameters.<p class="paragraph"/>HTML/URL injection is easily handled with the <a href="../guide/single.html#codecs" class="guide">codecs</a> supplied by Grails, and the tag libraries supplied by Grails all use <a href="../guide/single.html#codecs" class="guide">encodeAsURL</a> where appropriate. If you create your own tags that generate URLs you will need to be mindful of doing this too.<p class="paragraph"/><h4>Denial of service</h4><p class="paragraph"/>Load balancers and other appliances are more likely to be useful here, but there are also issues relating to excessive queries for example where a link is created by an attacker to set the maximum value of a result set so that a query could exceed the memory limits of the server or slow the system down. The solution here is to always sanitize request parameters before passing them to dynamic finders or other GORM query methods:<p class="paragraph"/><div class="code"><pre><span class="java-object">int</span> limit = 100 |
| def safeMax = <span class="java-object">Math</span>.min(params.max?.toInteger() ?: limit, limit) // limit to 100 results |
| <span class="java-keyword">return</span> Book.list(max:safeMax)</pre></div><p class="paragraph"/><h4>Guessable IDs</h4><p class="paragraph"/>Many applications use the last part of the URL as an "id" of some object to retrieve from GORM or elsewhere. Especially in the case of GORM these are easily guessable as they are typically sequential integers.<p class="paragraph"/>Therefore you must assert that the requesting user is allowed to view the object with the requested id before returning the response to the user.<p class="paragraph"/>Not doing this is "security through obscurity" which is inevitably breached, just like having a default password of "letmein" and so on.<p class="paragraph"/>You must assume that every unprotected URL is publicly accessible one way or another. |
| |
| |
| <a name="13.2 Cross Site Scripting (XSS) Prevention"><!-- Legacy link --></a> |
| <h2 id="xssPrevention">16.2 Cross Site Scripting (XSS) Prevention</h2> |
| Cross Site Scripting (XSS) attacks are a common attack vector for web applications. They typically involve submitting HTML or Javascript code in a form such that when that code is displayed, the browser does something nasty. It could be as simple as popping up an alert box, or it could be much worse. The solution is to escape all untrusted user input when it is displayed in a page. For example,<p class="paragraph"/><div class="code"><pre><script>alert('Got ya!');</script></pre></div><p class="paragraph"/>will become<p class="paragraph"/><div class="code"><pre>&lt;script&gt;alert('Got ya!');&lt;/script&gt;</pre></div><p class="paragraph"/>when rendered, nullifying the effects of the malicious input.<p class="paragraph"/>By default, Grails plays it safe and escapes all content in <code>${}</code> expressions in GSPs. All the standard GSP tags are also safe by default, escaping any relevant attribute values.<p class="paragraph"/>So what happens when you want to stop Grails from escaping some content? There are valid use cases for putting HTML into the database and rendering it as-is, as long as that content is <strong class="bold">trusted</strong>. In such cases, you can tell Grails that the content is safe as should be rendered raw, i.e. without any escaping:<p class="paragraph"/><div class="code"><pre><section>${raw(page.content)}</section></pre></div><p class="paragraph"/>The <code>raw()</code> method you see here is available from controllers, tag libraries and GSP pages.<p class="paragraph"/><strong class="bold">XSS prevention is hard and requires a lot of developer attention</strong><p class="paragraph"/><blockquote class="warning">Although Grails plays it safe by default, that is no guarantee that your application will be invulnerable to an XSS-style attack. Such an attack is less likely to succeed than would otherwise be the case, but developers should always be conscious of potential attack vectors and attempt to uncover vulnerabilities in the application during testing. It's also easy to switch to an unsafe default, thereby increasing the risk of a vulnerability being introduced.</blockquote><p class="paragraph"/>There are more details about the XSS in <a href="https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet#XSS_Prevention_Rules" target="blank">OWASP - XSS prevention rules</a> and <a href="https://www.owasp.org/index.php/Types_of_Cross-Site_Scripting" target="blank">OWASP - Types of Cross-Site Scripting</a>. Types of XSS are: <a href="https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)#Stored_XSS_Attacks" target="blank">Stored XSS</a>, <a href="https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)#Reflected_XSS_Attacks" target="blank">Reflected XSS</a> and <a href="https://www.owasp.org/index.php/DOM_Based_XSS" target="blank">DOM based XSS</a>. <a href="https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet" target="blank">DOM based XSS prevention</a> is coming more important because of the popularity of Javascript client side templating and Single Page Apps.<p class="paragraph"/>Grails codecs are mainly for preventing stored and reflected XSS type of attacks. Grails 2.4 includes HTMLJS codec that assists in preventing some DOM based XSS attacks.<p class="paragraph"/>It's difficult to make a solution that works for everyone, and so Grails provides a lot of flexibility with regard to fine-tuning how escaping works, allowing you to keep most of your application safe while switching off default escaping or changing the codec used for pages, tags, page fragments, and more.<p class="paragraph"/> |
| <h4>Configuration</h4><p class="paragraph"/>It is recommended that you review the configuration of a newly created Grails application to garner an understanding of XSS prevention works in Grails.<p class="paragraph"/>GSP features the ability to automatically HTML encode GSP expressions, and as of Grails 2.3 this is the default configuration. The default configuration (found in <code>Config.groovy</code>) for a newly created Grails application can be seen below:<p class="paragraph"/><div class="code"><pre>grails { |
| views { |
| gsp { |
| encoding = 'UTF-8' |
| htmlcodec = 'xml' // use xml escaping instead of HTML4 escaping |
| codecs { |
| expression = 'html' // escapes values inside ${} |
| scriptlet = 'html' // escapes output from scriptlets in GSPs |
| taglib = 'none' // escapes output from taglibs |
| staticparts = 'none' // escapes output from <span class="java-keyword">static</span> template parts |
| } |
| } |
| // escapes all not-encoded output at <span class="java-keyword">final</span> stage of outputting |
| // filteringCodecForContentType.'text/html' = 'html' |
| } |
| } |
| }</pre></div><p class="paragraph"/>GSP features several codecs that it uses when writing the page to the response. The codecs are configured in the <code>codecs</code> block and are described below: |
| <ul class="star"> |
| <li><code>expression</code> - The expression codec is used to encode any code found within ${..} expressions. The default for newly created application is <code>html</code> encoding.</li> |
| <li><code>scriptlet</code> - Used for output from GSP scriplets (<% %>, <%= %> blocks). The default for newly created applications is <code>html</code> encoding</li> |
| <li><code>taglib</code> - Used to encode output from GSP tag libraries. The default is <code>none</code> for new applications, as typically it is the responsibility of the tag author to define the encoding of a given tag and by specifying <code>none</code> Grails remains backwards compatible with older tag libraries.</li> |
| <li><code>staticparts</code> - Used to encode the raw markup output by a GSP page. The default is <code>none</code>.</li> |
| </ul><p class="paragraph"/><h4>Double Encoding Prevention</h4><p class="paragraph"/>Versions of Grails prior to 2.3, included the ability to set the default codec to <code>html</code>, however enabling this setting sometimes proved problematic when using existing plugins due to encoding being applied twice (once by the <code>html</code> codec and then again if the plugin manually called <code>encodeAsHTML</code>).<p class="paragraph"/>Grails 2.3 includes double encoding prevention so that when an expression is evaluated, it will not encode if the data has already been encoded (Example <code>${foo.encodeAsHTML()}</code>).<p class="paragraph"/><h4>Raw Output</h4><p class="paragraph"/>If you are 100% sure that the value you wish to present on the page has not been received from user input, and you do not wish the value to be encoded then you can use the <code>raw</code> method:<p class="paragraph"/><div class="code"><pre>${raw(book.title)}</pre></div><p class="paragraph"/>The 'raw' method is available in tag libraries, controllers and GSP pages.<p class="paragraph"/><h4>Per Plugin Encoding</h4><p class="paragraph"/>Grails also features the ability to control the codecs used on a per plugin basis. For example if you have a plugin named <code>foo</code> installed, then placing the following configuration in your application's <code>Config.groovy</code> will disable encoding for only the <code>foo</code> plugin<p class="paragraph"/><div class="code"><pre>foo.grails.views.gsp.codecs.expression = <span class="java-quote">"none"</span></pre></div><p class="paragraph"/><h4>Per Page Encoding</h4><p class="paragraph"/>You can also control the various codecs used to render a GSP page on a per page basis, using a page directive:<p class="paragraph"/><div class="code"><pre><%@page expressionCodec=<span class="java-quote">"none"</span> %></pre></div><p class="paragraph"/><h4>Per Tag Library Encoding</h4><p class="paragraph"/>Each tag library created has the opportunity to specify a default codec used to encode output from the tag library using the "defaultEncodeAs" property:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> defaultEncodeAs = 'html'</pre></div><p class="paragraph"/>Encoding can also be specified on a per tag basis using "encodeAsForTags":<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> encodeAsForTags = [tagName: 'raw']</pre></div><p class="paragraph"/><h4>Context Sensitive Encoding Switching</h4><p class="paragraph"/>Certain tags require certain encodings and Grails features the ability to enable a codec only a certain part of a tag's execution using the "withCodec" method. Consider for example the "<g:javascript>"" tag which allows you to embed JavaScript code in the page. This tag requires JavaScript encoding, not HTML coding for the execution of the body of the tag (but not for the markup that is output):<p class="paragraph"/><div class="code"><pre>out.println '<script type=<span class="java-quote">"text/javascript"</span>>' |
| withCodec(<span class="java-quote">"JavaScript"</span>) { |
| out << body() |
| } |
| out.println() |
| out.println '</script>'</pre></div><p class="paragraph"/><h4>Forced Encoding for Tags</h4><p class="paragraph"/>If a tag specifies a default encoding that differs from your requirements you can force the encoding for any tag by passing the optional 'encodeAs' attribute:<p class="paragraph"/><div class="code"><pre><g:message code=<span class="java-quote">"foo.bar"</span> encodeAs=<span class="java-quote">"JavaScript"</span> /></pre></div><p class="paragraph"/><h4>Default Encoding for All Output</h4><p class="paragraph"/>The default configuration for new applications is fine for most use cases, and backwards compatible with existing plugins and tag libraries. However, you can also make your application even more secure by configuring Grails to always encode all output at the end of a response. This is done using the <code>filteringCodecForContentType</code> configuration in <code>Config.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.views.gsp.filteringCodecForContentType.'text/html' = 'html'</pre></div><p class="paragraph"/>Note that, if activated, the <code>staticparts</code> codec typically needs to be set to <code>raw</code> so that static markup is not encoded:<p class="paragraph"/><div class="code"><pre>codecs { |
| expression = 'html' // escapes values inside ${} |
| scriptlet = 'html' // escapes output from scriptlets in GSPs |
| taglib = 'none' // escapes output from taglibs |
| staticparts = 'raw' // escapes output from <span class="java-keyword">static</span> template parts |
| }</pre></div> |
| |
| <a name="14.2 Encoding and Decoding Objects"><!-- Legacy link --></a> |
| <h2 id="codecs">16.3 Encoding and Decoding Objects</h2> |
| Grails supports the concept of dynamic encode/decode methods. A set of standard codecs are bundled with Grails. Grails also supports a simple mechanism for developers to contribute their own codecs that will be recognized at runtime.<p class="paragraph"/><h4>Codec Classes</h4><p class="paragraph"/>A Grails codec class is one that may contain an encode closure, a decode closure or both. When a Grails application starts up the Grails framework dynamically loads codecs from the <code>grails-app/utils/</code> directory.<p class="paragraph"/>The framework looks under <code>grails-app/utils/</code> for class names that end with the convention <code>Codec</code>. For example one of the standard codecs that ships with Grails is <code>HTMLCodec</code>.<p class="paragraph"/>If a codec contains an <code>encode</code> closure Grails will create a dynamic <code>encode</code> method and add that method to the <code>Object</code> class with a name representing the codec that defined the encode closure. For example, the <code>HTMLCodec</code> class defines an <code>encode</code> closure, so Grails attaches it with the name <code>encodeAsHTML</code>.<p class="paragraph"/>The <code>HTMLCodec</code> and <code>URLCodec</code> classes also define a <code>decode</code> closure, so Grails attaches those with the names <code>decodeHTML</code> and <code>decodeURL</code> respectively. Dynamic codec methods may be invoked from anywhere in a Grails application. For example, consider a case where a report contains a property called 'description' which may contain special characters that must be escaped to be presented in an HTML document. One way to deal with that in a GSP is to encode the description property using the dynamic encode method as shown below:<p class="paragraph"/><div class="code"><pre>${report.description.encodeAsHTML()}</pre></div><p class="paragraph"/>Decoding is performed using <code>value.decodeHTML()</code> syntax.<p class="paragraph"/><h4>Encoder and Decoder interfaces for staticly compiled code</h4><p class="paragraph"/>A preferred way to use codecs is to use the codecLookup bean to get hold of <code>Encoder</code> and <code>Decoder</code> instances .<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> org.grails.encoder;<p class="paragraph"/><span class="java-keyword">public</span> <span class="java-keyword">interface</span> CodecLookup { |
| <span class="java-keyword">public</span> Encoder lookupEncoder(<span class="java-object">String</span> codecName); |
| <span class="java-keyword">public</span> Decoder lookupDecoder(<span class="java-object">String</span> codecName); |
| }</pre></div><p class="paragraph"/>example of using <code>CodecLookup</code> and <code>Encoder</code> interface |
| <div class="code"><pre><span class="java-keyword">import</span> org.grails.encoder.CodecLookup<p class="paragraph"/>class CustomTagLib { |
| CodecLookup codecLookup<p class="paragraph"/> def myTag = { Map attrs, body -> |
| out << codecLookup.lookupEncoder('HTML').encode(attrs.something) |
| } |
| }</pre></div><p class="paragraph"/><h4>Standard Codecs</h4><p class="paragraph"/><strong class="bold">HTMLCodec</strong><p class="paragraph"/>This codec performs HTML escaping and unescaping, so that values can be rendered safely in an HTML page without creating any HTML tags or damaging the page layout. For example, given a value "Don't you know that 2 > 1?" you wouldn't be able to show this safely within an HTML page because the > will look like it closes a tag, which is especially bad if you render this data within an attribute, such as the value attribute of an input field.<p class="paragraph"/>Example of usage:<p class="paragraph"/><div class="code"><pre><input name=<span class="java-quote">"comment.message"</span> value=<span class="java-quote">"${comment.message.encodeAsHTML()}"</span>/></pre></div><p class="paragraph"/><blockquote class="note"> |
| Note that the HTML encoding does not re-encode apostrophe/single quote so you must use double quotes on attribute values to avoid text with apostrophes affecting your page. |
| </blockquote><p class="paragraph"/>HTMLCodec defaults to HTML4 style escaping (legacy HTMLCodec implementation in Grails versions before 2.3.0) which escapes non-ascii characters.<p class="paragraph"/>You can use plain XML escaping instead of HTML4 escaping by setting this config property in Config.groovy: |
| <div class="code"><pre>grails.views.gsp.htmlcodec = 'xml'</pre></div><p class="paragraph"/> |
| <strong class="bold">XMLCodec</strong><p class="paragraph"/>This codec performs XML escaping and unescaping. It escapes & , < , > , " , ' , \ , @ , ` , non breaking space (\u00a0), line separator (\u2028) and paragraph separator (\u2029).<p class="paragraph"/> |
| <strong class="bold">HTMLJSCodec</strong><p class="paragraph"/>This codec performs HTML and JS encoding. It is used for preventing some DOM-XSS vulnerabilities. See <a href="https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet#RULE_.231_-_HTML_Escape_then_JavaScript_Escape_Before_Inserting_Untrusted_Data_into_HTML_Subcontext_within_the_Execution_Context" target="blank">OWASP - DOM based XSS Prevention Cheat Sheet</a> for guidelines of preventing DOM based XSS attacks.<p class="paragraph"/><strong class="bold">URLCodec</strong><p class="paragraph"/>URL encoding is required when creating URLs in links or form actions, or any time data is used to create a URL. It prevents illegal characters from getting into the URL and changing its meaning, for example "Apple & Blackberry" is not going to work well as a parameter in a GET request as the ampersand will break parameter parsing.<p class="paragraph"/>Example of usage:<p class="paragraph"/><div class="code"><pre><a href=<span class="java-quote">"/mycontroller/find?searchKey=${lastSearch.encodeAsURL()}"</span>> |
| Repeat last search |
| </a></pre></div><p class="paragraph"/><strong class="bold">Base64Codec</strong><p class="paragraph"/>Performs Base64 encode/decode functions. Example of usage:<p class="paragraph"/><div class="code"><pre>Your registration code is: ${user.registrationCode.encodeAsBase64()}</pre></div><p class="paragraph"/><strong class="bold">JavaScriptCodec</strong><p class="paragraph"/>Escapes Strings so they can be used as valid JavaScript strings. For example:<p class="paragraph"/><div class="code"><pre>Element.update('${elementId}', |
| '${render(template: <span class="java-quote">"/common/message"</span>).encodeAsJavaScript()}')</pre></div><p class="paragraph"/><strong class="bold">HexCodec</strong><p class="paragraph"/>Encodes byte arrays or lists of integers to lowercase hexadecimal strings, and can decode hexadecimal strings into byte arrays. For example:<p class="paragraph"/><div class="code"><pre>Selected colour: #${[255,127,255].encodeAsHex()}</pre></div><p class="paragraph"/><strong class="bold">MD5Codec</strong><p class="paragraph"/>Uses the MD5 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encoding), as a lowercase hexadecimal string. Example of usage:<p class="paragraph"/><div class="code"><pre>Your API Key: ${user.uniqueID.encodeAsMD5()}</pre></div><p class="paragraph"/><strong class="bold">MD5BytesCodec</strong><p class="paragraph"/>Uses the MD5 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encoding), as a byte array. Example of usage:<p class="paragraph"/><div class="code"><pre><span class="java-object">byte</span>[] passwordHash = params.password.encodeAsMD5Bytes()</pre></div><p class="paragraph"/><strong class="bold">SHA1Codec</strong><p class="paragraph"/>Uses the SHA1 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encoding), as a lowercase hexadecimal string. Example of usage:<p class="paragraph"/><div class="code"><pre>Your API Key: ${user.uniqueID.encodeAsSHA1()}</pre></div><p class="paragraph"/><strong class="bold">SHA1BytesCodec</strong><p class="paragraph"/>Uses the SHA1 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encoding), as a byte array. Example of usage:<p class="paragraph"/><div class="code"><pre><span class="java-object">byte</span>[] passwordHash = params.password.encodeAsSHA1Bytes()</pre></div><p class="paragraph"/><strong class="bold">SHA256Codec</strong><p class="paragraph"/>Uses the SHA256 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encoding), as a lowercase hexadecimal string. Example of usage:<p class="paragraph"/><div class="code"><pre>Your API Key: ${user.uniqueID.encodeAsSHA256()}</pre></div><p class="paragraph"/><strong class="bold">SHA256BytesCodec</strong><p class="paragraph"/>Uses the SHA256 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encoding), as a byte array. Example of usage:<p class="paragraph"/><div class="code"><pre><span class="java-object">byte</span>[] passwordHash = params.password.encodeAsSHA256Bytes()</pre></div><p class="paragraph"/><h4>Custom Codecs</h4><p class="paragraph"/>Applications may define their own codecs and Grails will load them along with the standard codecs. A custom codec class must be defined in the <code>grails-app/utils/</code> directory and the class name must end with <code>Codec</code>. The codec may contain a <code>static</code> <code>encode</code> closure, a <code>static</code> <code>decode</code> closure or both. The closure must accept a single argument which will be the object that the dynamic method was invoked on. For Example:<p class="paragraph"/><div class="code"><pre>class PigLatinCodec { |
| <span class="java-keyword">static</span> encode = { str -> |
| // convert the string to pig latin and <span class="java-keyword">return</span> the result |
| } |
| }</pre></div><p class="paragraph"/>With the above codec in place an application could do something like this:<p class="paragraph"/><div class="code"><pre>${lastName.encodeAsPigLatin()}</pre></div> |
| |
| |
| <a name="14.3 Authentication"><!-- Legacy link --></a> |
| <h2 id="authentication">16.4 Authentication</h2> |
| Grails has no default mechanism for authentication as it is possible to implement authentication in many different ways. It is however, easy to implement a simple authentication mechanism using <a href="../guide/single.html#interceptors" class="guide">interceptors</a>. This is sufficient for simple use cases but it's highly preferable to use an established security framework, for example by using the <a href="../guide/single.html#springSecurity" class="guide">Spring Security</a> or the <a href="../guide/single.html#shiro" class="guide">Shiro</a> plugin.<p class="paragraph"/>Interceptors let you apply authentication across all controllers or across a URI space. For example you can create a new set of filters in a class called <code>grails-app/controllers/SecurityInterceptor.groovy</code> by running:<p class="paragraph"/><div class="code"><pre>grails create-interceptor security</pre></div><p class="paragraph"/>and implement your interception logic there:<p class="paragraph"/><div class="code"><pre>class SecurityInterceptor {<p class="paragraph"/> SecurityInterceptor() { |
| matchAll() |
| except(controller:'user', action:'login') |
| }<p class="paragraph"/> <span class="java-object">boolean</span> before() { |
| <span class="java-keyword">if</span> (!session.user && actionName != <span class="java-quote">"login"</span>) { |
| redirect(controller: <span class="java-quote">"user"</span>, action: <span class="java-quote">"login"</span>) |
| <span class="java-keyword">return</span> <span class="java-keyword">false</span> |
| } |
| <span class="java-keyword">return</span> <span class="java-keyword">true</span> |
| }<p class="paragraph"/>}</pre></div><p class="paragraph"/>Here the interceptor intercepts execution <em class="italic">before</em> all actions except <code>login</code> are executed, and if there is no user in the session then redirect to the <code>login</code> action.<p class="paragraph"/>The <code>login</code> action itself is simple too:<p class="paragraph"/><div class="code"><pre>def login() { |
| <span class="java-keyword">if</span> (request.get) { |
| <span class="java-keyword">return</span> // render the login view |
| }<p class="paragraph"/> def u = User.findByLogin(params.login) |
| <span class="java-keyword">if</span> (u) { |
| <span class="java-keyword">if</span> (u.password == params.password) { |
| session.user = u |
| redirect(action: <span class="java-quote">"home"</span>) |
| } |
| <span class="java-keyword">else</span> { |
| render(view: <span class="java-quote">"login"</span>, model: [message: <span class="java-quote">"Password incorrect"</span>]) |
| } |
| } |
| <span class="java-keyword">else</span> { |
| render(view: <span class="java-quote">"login"</span>, model: [message: <span class="java-quote">"User not found"</span>]) |
| } |
| }</pre></div> |
| |
| |
| <a name="14.4 Security Plug-ins"><!-- Legacy link --></a> |
| <h2 id="securityPlugins">16.5 Security Plugins</h2> |
| If you need more advanced functionality beyond simple authentication such as authorization, roles etc. then you should consider using one of the available security plugins. |
| |
| |
| <a name="14.4.1 Spring Security"><!-- Legacy link --></a> |
| <h2 id="springSecurity">16.5.1 Spring Security</h2> |
| The Spring Security plugins are built on the <a href="http://static.springsource.org/spring-security/site/" target="blank">Spring Security</a> project which provides a flexible, extensible framework for building all sorts of authentication and authorization schemes. The plugins are modular so you can install just the functionality that you need for your application. The Spring Security plugins are the official security plugins for Grails and are actively maintained and supported.<p class="paragraph"/>There is a <a href="http://grails.org/plugin/spring-security-core" target="blank">Core plugin</a> which supports form-based authentication, encrypted/salted passwords, HTTP Basic authentication, etc. and secondary dependent plugins provide alternate functionality such as <a href="http://grails.org/plugin/spring-security-openid" target="blank">OpenID authentication</a>, <a href="http://grails.org/plugin/spring-security-acl" target="blank">ACL support</a>, <a href="http://grails.org/plugin/spring-security-cas" target="blank">single sign-on with Jasig CAS</a>, <a href="http://grails.org/plugin/spring-security-ldap" target="blank">LDAP authentication</a>, <a href="http://grails.org/plugin/spring-security-kerberos" target="blank">Kerberos authentication</a>, and a plugin providing <a href="http://grails.org/plugin/spring-security-ui" target="blank">user interface extensions</a> and security workflows.<p class="paragraph"/>See the <a href="http://grails.org/plugin/spring-security-core" target="blank">Core plugin page</a> for basic information and the <a href="http://burtbeckwith.github.com/grails-spring-security-core/" target="blank">user guide</a> for detailed information. |
| |
| |
| <a name="14.4.2 Shiro"><!-- Legacy link --></a> |
| <h2 id="shiro">16.5.2 Shiro</h2> |
| <a href="http://shiro.apache.org/" target="blank">Shiro</a> is a Java POJO-oriented security framework that provides a default domain model that models realms, users, roles and permissions. With Shiro you extend a controller base class called <code>JsecAuthBase</code> in each controller you want secured and then provide an <code>accessControl</code> block to setup the roles. An example below:<p class="paragraph"/><div class="code"><pre>class ExampleController <span class="java-keyword">extends</span> JsecAuthBase { |
| <span class="java-keyword">static</span> accessControl = { |
| // All actions require the 'Observer' role. |
| role(name: 'Observer')<p class="paragraph"/> // The 'edit' action requires the 'Administrator' role. |
| role(name: 'Administrator', action: 'edit')<p class="paragraph"/> // Alternatively, several actions can be specified. |
| role(name: 'Administrator', only: [ 'create', 'edit', 'save', 'update' ]) |
| } |
| … |
| }</pre></div><p class="paragraph"/>For more information on the Shiro plugin refer to the <a href="http://grails.org/plugin/shiro" target="blank">documentation</a>. |
| |
| |
| <a name="15. Plug-ins"><!-- Legacy link --></a> |
| <h1 id="plugins">17 Plugins</h1> |
| Grails is first and foremost a web application framework, but it is also a platform. By exposing a number of extension points that let you extend anything from the command line interface to the runtime configuration engine, Grails can be customised to suit almost any needs. To hook into this platform, all you need to do is create a plugin.<p class="paragraph"/>Extending the platform may sound complicated, but plugins can range from trivially simple to incredibly powerful. If you know how to build a Grails application, you'll know how to create a plugin for <a href="../guide/single.html#providingBasicArtefacts" class="guide">sharing a data model</a> or some static resources. |
| |
| |
| <a name="15.1 Creating and Installing Plug-ins"><!-- Legacy link --></a> |
| <h2 id="creatingAndInstallingPlugins">17.1 Creating and Installing Plugins</h2> |
| <h4>Creating Plugins</h4><p class="paragraph"/>Creating a Grails plugin is a simple matter of running the command:<p class="paragraph"/><div class="code"><pre>grails create-plugin [PLUGIN NAME]</pre></div><p class="paragraph"/>This will create a plugin project for the name you specify. For example running <code>grails create-plugin example</code> would create a new plugin project called <code>example</code>.<p class="paragraph"/>In Grails 3.0 you should consider whether the plugin you create requires a web environment or whether the plugin can be used with other profiles. If you plugin does not require a web environment then use the "plugin" profile instead of the "web-plugin" profile:<p class="paragraph"/><div class="code"><pre>grails create-plugin [PLUGIN NAME] --profile=plugin</pre></div><p class="paragraph"/>Make sure the plugin name does not contain more than one capital in a row, or it won't work. Camel case is fine, though.<p class="paragraph"/>The structure of a Grails plugin is very nearly the same as a Grails application project's except that in the <code>src/main/groovy</code> directory under the plugin package structure you will find a plugin descriptor class (a class that ends in "GrailsPlugin").<p class="paragraph"/>Being a regular Grails project has a number of benefits in that you can immediately test your plugin by running (if the plugin targets the "web" profile):<p class="paragraph"/><div class="code"><pre>grails run-app</pre></div><p class="paragraph"/><blockquote class="note"> |
| Plugin projects don't provide an index.gsp by default since most plugins don't need it. So, if you try to view the plugin running in a browser right after creating it, you will receive a page not found error. You can easily create a <code>grails-app/views/index.gsp</code> for your plugin if you'd like. |
| </blockquote><p class="paragraph"/>The plugin descriptor name ends with the convention <code>GrailsPlugin</code> and is found in the root of the plugin project. For example:<p class="paragraph"/><div class="code"><pre>class ExampleGrailsPlugin { |
| … |
| }</pre></div><p class="paragraph"/>All plugins must have this class under the <code>src/main/groovy</code> directory, otherwise they are not regarded as a plugin. The plugin class defines metadata about the plugin, and optionally various hooks into plugin extension points (covered shortly).<p class="paragraph"/>You can also provide additional information about your plugin using several special properties: |
| <ul class="star"> |
| <li><code>title</code> - short one-sentence description of your plugin</li> |
| <li><code>grailsVersion</code> - The version of version range of Grails that the plugin supports. eg. "1.2 > *" (indicating 1.2 or higher)</li> |
| <li><code>author</code> - plugin author's name</li> |
| <li><code>authorEmail</code> - plugin author's contact e-mail</li> |
| <li><code>description</code> - full multi-line description of plugin's features</li> |
| <li><code>documentation</code> - URL of the plugin's documentation</li> |
| </ul><p class="paragraph"/>Here is an example from the <a href="http://grails.org/plugin/quartz" target="blank">Quartz Grails plugin</a>:<p class="paragraph"/><div class="code"><pre>class QuartzGrailsPlugin { |
| def grailsVersion = <span class="java-quote">"1.1 > *"</span> |
| def author = <span class="java-quote">"Sergey Nebolsin"</span> |
| def authorEmail = <span class="java-quote">"nebolsin@gmail.com"</span> |
| def title = <span class="java-quote">"Quartz Plugin"</span> |
| def description = '''\ |
| The Quartz plugin allows your Grails application to schedule jobs\ |
| to be executed using a specified interval or cron expression. The\ |
| underlying system uses the Quartz Enterprise Job Scheduler configured\ |
| via Spring, but is made simpler by the coding by convention paradigm.\ |
| ''' |
| def documentation = <span class="java-quote">"http://grails.org/plugin/quartz"</span><p class="paragraph"/> … |
| }</pre></div><p class="paragraph"/><h4>Installing Local Plugins</h4><p class="paragraph"/>To make your plugin available for use in a Grails application run the <code>install</code> command:<p class="paragraph"/><div class="code"><pre>grails install</pre></div><p class="paragraph"/>This will install the plugin into your local Maven cache. Then to use the plugin within an application declare a dependency on the plugin in your <code>build.gradle</code> file:<p class="paragraph"/><div class="code"><pre>compile <span class="java-quote">"org.grails.plugins:quartz:0.1"</span></pre></div><p class="paragraph"/><blockquote class="note"> |
| In Grails 2.x plugins were packaged as ZIP files, however in Grails 3.x plugins are simple JAR files that can be added to the classpath of the IDE. |
| </blockquote><p class="paragraph"/><h4>Notes on excluded Artefacts</h4><p class="paragraph"/>Although the <a href="../ref/Command Line/create-plugin.html" class="commandLine">create-plugin</a> command creates certain files for you so that the plugin can be run as a Grails application, not all of these files are included when packaging a plugin. The following is a list of artefacts created, but not included by <a href="../ref/Command Line/package-plugin.html" class="commandLine">package-plugin</a>: |
| <ul class="star"> |
| <li><code>grails-app/build.gradle</code> (although it is used to generate <code>dependencies.groovy</code>)</li> |
| <li><code>grails-app/conf/application.yml</code> (renamed to plugin.yml)</li> |
| <li><code>grails-app/conf/spring/resources.groovy</code></li> |
| <li><code>grails-app/conf/logback.groovy</code></li> |
| <li>Everything within <code>/src/test/**</code></li> |
| <li>SCM management files within <code>**/.svn/**</code> and <code>**/CVS/**</code></li> |
| </ul><p class="paragraph"/><h4>Customizing the plugin contents</h4><p class="paragraph"/>When developing a plugin you may create test classes and sources that are used during the development and testing of the plugin but should not be exported to the application.<p class="paragraph"/>To exclude test sources you need to modify the <code>pluginExcludes</code> property of the plugin descriptor AND exclude the resources inside your <code>build.gradle</code> file. For example say you have some classes under the <code>com.demo</code> package that are in your plugin source tree but should not be packaged in the application. In your plugin descriptor you should exclude these:<p class="paragraph"/><div class="code"><pre>// resources that should be loaded by the plugin once installed in the application |
| def pluginExcludes = [ |
| '**/com/demo/**' |
| ]</pre></div><p class="paragraph"/>And in your <code>build.gradle</code> you should exclude the compiled classes from the JAR file:<p class="paragraph"/><div class="code"><pre>jar { |
| exclude <span class="java-quote">"com/demo/**/**"</span> |
| }</pre></div><p class="paragraph"/> |
| <h4>Inline Plugins in Grails 3.0</h4><p class="paragraph"/>In Grails 2.x it was possible to specify inline plugins in <code>BuildConfig</code>, in Grails 3.x this functionality has been replaced by Gradle's multi-project build feature.<p class="paragraph"/>To set up a multi project build create an appliation and a plugin in a parent directory:<p class="paragraph"/><div class="code"><pre>$ grails create-app myapp |
| $ grails create-plugin myplugin</pre></div><p class="paragraph"/>Then create a <code>settings.gradle</code> file in the parent directory specifying the location of your application and plugin:<p class="paragraph"/><div class="code"><pre>include 'myapp', 'myplugin'</pre></div><p class="paragraph"/>Finally add a dependency in your application's <code>build.gradle</code> on the plugin:<p class="paragraph"/><div class="code"><pre>compile project(':myplugin')</pre></div><p class="paragraph"/>Using this technique you have achieved the equivalent of inline plugins from Grails 2.x. |
| |
| |
| <a name="15.2 Plugin Repositories"><!-- Legacy link --></a> |
| <h2 id="repositories">17.2 Plugin Repositories</h2> |
| <h4>Distributing Plugins in the Grails Central Plugin Repository</h4><p class="paragraph"/>The preferred way to distribute plugin is to publish to the official Grails Central Plugin Repository. This will make your plugin visible to the <a href="../ref/Command Line/list-plugins.html" class="commandLine">list-plugins</a> command:<p class="paragraph"/><div class="code"><pre>grails list-plugins</pre></div><p class="paragraph"/>which lists all plugins that are in the central repository. Your plugin will also be available to the <a href="../ref/Command Line/plugin-info.html" class="commandLine">plugin-info</a> command:<p class="paragraph"/><div class="code"><pre>grails plugin-info [plugin-name]</pre></div><p class="paragraph"/>which prints extra information about it, such as its description, who wrote, etc.<p class="paragraph"/><blockquote class="note"> |
| If you have created a Grails plugin and want it to be hosted in the central repository, you'll find instructions for getting an account on the <a href="http://grails.org/plugins" target="blank">plugin portal</a> website. |
| </blockquote> |
| |
| |
| <a name="15.4 Providing Basic Artefacts"><!-- Legacy link --></a> |
| <h2 id="providingBasicArtefacts">17.3 Providing Basic Artefacts</h2> |
| <h4>Add Command Line Commands</h4><p class="paragraph"/>A plugin can add new commands to the Grails 3.0 interactive shell in one of two ways. First, using the <a href="../ref/Command Line/create-script.html" class="commandLine">create-script</a> you can create a code generation script which will become available to the application. The <code>create-script</code> command will create the script in the <code>src/main/scripts</code> directory:<p class="paragraph"/><div class="code"><pre>+ src/main/scripts <-- additional scripts here |
| + grails-app |
| + controllers |
| + services |
| + etc.</pre></div><p class="paragraph"/>Code generation scripts can be used to create artefacts within the project tree and automate interactions with Gradle.<p class="paragraph"/>If you want to create a new shell command that interacts with a loaded Grails application instance then you should use the <code>create-command</code> command:<p class="paragraph"/><div class="code"><pre>$ grails create-command MyExampleCommand</pre></div><p class="paragraph"/>This will create a file called <code>grails-app/commands/PACKAGE_PATH/MyExampleCommand.groovy</code> that extends <a href="http://grails.org/doc/3.0.x/api/grails/dev/commands/ApplicationCommand.html" class="api">ApplicationCommand</a>:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.dev.commands.*<p class="paragraph"/>class MyExampleCommand <span class="java-keyword">implements</span> ApplicationCommand {<p class="paragraph"/> <span class="java-object">boolean</span> handle(ExecutionContext ctx) { |
| println <span class="java-quote">"Hello World"</span> |
| <span class="java-keyword">return</span> <span class="java-keyword">true</span> |
| } |
| }</pre></div><p class="paragraph"/>An <code>ApplicationCommand</code> has access to the <code>GrailsApplication</code> instance and is subject to autowiring like any other Spring bean.<p class="paragraph"/>For each <code>ApplicationCommand</code> present Grails will create a shell command and a Gradle task to invoke the <code>ApplicationCommand</code>. In the above example you can invoke the <code>MyExampleCommand</code> class using either:<p class="paragraph"/><div class="code"><pre>$ grails my-example</pre></div><p class="paragraph"/>Or<p class="paragraph"/><div class="code"><pre>$ gradle myExample</pre></div><p class="paragraph"/>The Grails version is all lower case hyphen separated and excludes the "Command" suffix.<p class="paragraph"/>The main difference between code generation scripts and <code>ApplicationCommand</code> instances is that the latter has full access to the Grails application state and hence can be used to perform tasks that interactive with the database, call into GORM etc.<p class="paragraph"/>In Grails 2.x Gant scripts could be used to perform both these tasks, in Grails 3.x code generation and interacting with runtime application state has been cleanly separated.<p class="paragraph"/><h4>Adding a new grails-app artifact (Controller, Tag Library, Service, etc.)</h4><p class="paragraph"/>A plugin can add new artifacts by creating the relevant file within the <code>grails-app</code> tree.<p class="paragraph"/><div class="code"><pre>+ grails-app |
| + controllers <-- additional controllers here |
| + services <-- additional services here |
| + etc. <-- additional XXX here</pre></div><p class="paragraph"/><h4>Providing Views, Templates and View resolution</h4><p class="paragraph"/>When a plugin provides a controller it may also provide default views to be rendered. This is an excellent way to modularize your application through plugins. Grails' view resolution mechanism will first look for the view in the application it is installed into and if that fails will attempt to look for the view within the plugin. This means that you can override views provided by a plugin by creating corresponding GSPs in the application's <code>grails-app/views</code> directory.<p class="paragraph"/>For example, consider a controller called <code>BookController</code> that's provided by an 'amazon' plugin. If the action being executed is <code>list</code>, Grails will first look for a view called <code>grails-app/views/book/list.gsp</code> then if that fails it will look for the same view relative to the plugin.<p class="paragraph"/>However if the view uses templates that are also provided by the plugin then the following syntax may be necessary:<p class="paragraph"/><div class="code"><pre><g:render template=<span class="java-quote">"fooTemplate"</span> plugin=<span class="java-quote">"amazon"</span>/></pre></div><p class="paragraph"/>Note the usage of the <code>plugin</code> attribute, which contains the name of the plugin where the template resides. If this is not specified then Grails will look for the template relative to the application.<p class="paragraph"/><h4>Excluded Artefacts</h4><p class="paragraph"/>By default Grails excludes the following files during the packaging process: |
| <ul class="star"> |
| <li><code>grails-app/conf/logback.groovy</code></li> |
| <li><code>grails-app/conf/application.yml</code> (renamed to <code>plugin.yml</code>)</li> |
| <li><code>grails-app/conf/spring/resources.groovy</code></li> |
| <li>Everything within <code>/src/test/**</code></li> |
| <li>SCM management files within <code>**/.svn/**</code> and <code>**/CVS/**</code></li> |
| </ul><p class="paragraph"/>In addition, the default <code>UrlMappings.groovy</code> file is excluded to avoid naming conflicts, however you are free to add a UrlMappings definition under a different name which <strong class="bold">will</strong> be included. For example a file called <code>grails-app/conf/BlogUrlMappings.groovy</code> is fine.<p class="paragraph"/>The list of excludes is extensible with the <code>pluginExcludes</code> property:<p class="paragraph"/><div class="code"><pre>// resources that are excluded from plugin packaging |
| def pluginExcludes = [ |
| <span class="java-quote">"grails-app/views/error.gsp"</span> |
| ]</pre></div><p class="paragraph"/>This is useful for example to include demo or test resources in the plugin repository, but not include them in the final distribution. |
| |
| |
| <a name="15.5 Evaluating Conventions"><!-- Legacy link --></a> |
| <h2 id="evaluatingConventions">17.4 Evaluating Conventions</h2> |
| Before looking at providing runtime configuration based on conventions you first need to understand how to evaluate those conventions from a plugin. Every plugin has an implicit <code>application</code> variable which is an instance of the <a href="http://grails.org/doc/3.0.x/api/grails/core/GrailsApplication.html" class="api">GrailsApplication</a> interface.<p class="paragraph"/>The <code>GrailsApplication</code> interface provides methods to evaluate the conventions within the project and internally stores references to all artifact classes within your application.<p class="paragraph"/>Artifacts implement the <a href="http://grails.org/doc/3.0.x/api/grails/core/GrailsClass.html" class="api">GrailsClass</a> interface, which represents a Grails resource such as a controller or a tag library. For example to get all <code>GrailsClass</code> instances you can do:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">for</span> (grailsClass in application.allClasses) { |
| println grailsClass.name |
| }</pre></div><p class="paragraph"/><code>GrailsApplication</code> has a few "magic" properties to narrow the type of artefact you are interested in. For example to access controllers you can use:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">for</span> (controllerClass in application.controllerClasses) { |
| println controllerClass.name |
| }</pre></div><p class="paragraph"/>The dynamic method conventions are as follows: |
| <ul class="star"> |
| <li><code>*Classes</code> - Retrieves all the classes for a particular artefact name. For example <code>application.controllerClasses</code>.</li> |
| <li><code>get*Class</code> - Retrieves a named class for a particular artefact. For example <code>application.getControllerClass("PersonController")</code></li> |
| <li><code>is*Class</code> - Returns <code>true</code> if the given class is of the given artefact type. For example <code>application.isControllerClass(PersonController)</code></li> |
| </ul><p class="paragraph"/>The <code>GrailsClass</code> interface has a number of useful methods that let you further evaluate and work with the conventions. These include: |
| <ul class="star"> |
| <li><code>getPropertyValue</code> - Gets the initial value of the given property on the class</li> |
| <li><code>hasProperty</code> - Returns <code>true</code> if the class has the specified property</li> |
| <li><code>newInstance</code> - Creates a new instance of this class.</li> |
| <li><code>getName</code> - Returns the logical name of the class in the application without the trailing convention part if applicable</li> |
| <li><code>getShortName</code> - Returns the short name of the class without package prefix</li> |
| <li><code>getFullName</code> - Returns the full name of the class in the application with the trailing convention part and with the package name</li> |
| <li><code>getPropertyName</code> - Returns the name of the class as a property name</li> |
| <li><code>getLogicalPropertyName</code> - Returns the logical property name of the class in the application without the trailing convention part if applicable</li> |
| <li><code>getNaturalName</code> - Returns the name of the property in natural terms (e.g. 'lastName' becomes 'Last Name')</li> |
| <li><code>getPackageName</code> - Returns the package name</li> |
| </ul><p class="paragraph"/>For a full reference refer to the <a href="http://grails.org/doc/3.0.x/api/grails/core/GrailsClass.html" class="api">javadoc API</a>. |
| |
| |
| <a name="15.7 Hooking into Runtime Configuration"><!-- Legacy link --></a> |
| <h2 id="hookingIntoRuntimeConfiguration">17.5 Hooking into Runtime Configuration</h2> |
| Grails provides a number of hooks to leverage the different parts of the system and perform runtime configuration by convention.<p class="paragraph"/><h4>Hooking into the Grails Spring configuration</h4><p class="paragraph"/>First, you can hook in Grails runtime configuration overriding the <code>doWithSpring</code> method from the <a href="http://grails.org/doc/3.0.x/api/grails/plugins/Plugin.html" class="api">Plugin</a> class and returning a closure that defines additional beans. For example the following snippet is from one of the core Grails plugins that provides <a href="../guide/single.html#i18n" class="guide">i18n</a> support:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.springframework.web.servlet.i18n.CookieLocaleResolver |
| <span class="java-keyword">import</span> org.springframework.web.servlet.i18n.LocaleChangeInterceptor |
| <span class="java-keyword">import</span> org.springframework.context.support.ReloadableResourceBundleMessageSource |
| <span class="java-keyword">import</span> grails.plugins.*<p class="paragraph"/>class I18nGrailsPlugin <span class="java-keyword">extends</span> Plugin {<p class="paragraph"/> def version = <span class="java-quote">"0.1"</span><p class="paragraph"/> Closure doWithSpring() {{-> |
| messageSource(ReloadableResourceBundleMessageSource) { |
| basename = <span class="java-quote">"WEB-INF/grails-app/i18n/messages"</span> |
| } |
| localeChangeInterceptor(LocaleChangeInterceptor) { |
| paramName = <span class="java-quote">"lang"</span> |
| } |
| localeResolver(CookieLocaleResolver) |
| }} |
| }</pre></div><p class="paragraph"/>This plugin configures the Grails <code>messageSource</code> bean and a couple of other beans to manage Locale resolution and switching. It using the <a href="../guide/single.html#spring" class="guide">Spring Bean Builder</a> syntax to do so.<p class="paragraph"/><h4>Customizing the Servlet Environment</h4><p class="paragraph"/>In previous versions of Grails it was possible to dynamically modify the generated <code>web.xml</code>. In Grails 3.x there is no <code>web.xml</code> file and it is not possible to programmatically modify the <code>web.xml</code> file anymore.<p class="paragraph"/>However, it is possible to perform the most commons tasks of modifying the Servlet environment in Grails 3.x.<p class="paragraph"/><h4>Adding New Servlets</h4><p class="paragraph"/>If you want to add a new Servlet instance the simplest way is simply to define a new Spring bean in the <code>doWithSpring</code> method:<p class="paragraph"/><div class="code"><pre>Closure doWithSpring() {{-> |
| myServlet(MyServlet) |
| }}</pre></div><p class="paragraph"/>If you need to customize the servlet you can use Spring Boot's <a href="http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/context/embedded/ServletRegistrationBean.html" class="api">ServletRegistrationBean</a>:<p class="paragraph"/><div class="code"><pre>Closure doWithSpring() {{-> |
| myServlet(ServletRegistrationBean, <span class="java-keyword">new</span> MyServlet(), <span class="java-quote">"/myServlet/*"</span>) { |
| loadOnStartup = 2 |
| } |
| }}</pre></div><p class="paragraph"/><h4>Adding New Servlet Filters</h4><p class="paragraph"/>Just like Servlets, the simplest way to configure a new filter is to simply define a Spring bean:<p class="paragraph"/><div class="code"><pre>Closure doWithSpring() {{-> |
| myFilter(MyFilter) |
| }}</pre></div><p class="paragraph"/>However, if you want to control the order of filter registrations you will need to use Spring Boot's <a href="http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/context/embedded/FilterRegistrationBean.html" class="api">FilterRegistrationBean</a>:<p class="paragraph"/><div class="code"><pre>myFilter(FilterRegistrationBean) { |
| filter = bean(MyFilter) |
| urlPatterns = ['/*'] |
| order = Ordered.HIGHEST_PRECEDENCE |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| Grails' internal registered filters (<code>GrailsWebRequestFilter</code>, <code>HiddenHttpMethodFilter</code> etc.) are defined by incrementing <code>HIGHEST_PRECEDENCE</code> by 10 thus allowing several filters to be inserted before or between Grails' filters. |
| </blockquote><p class="paragraph"/><h4>Doing Post Initialisation Configuration</h4><p class="paragraph"/>Sometimes it is useful to be able do some runtime configuration after the Spring <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/context/ApplicationContext.html" class="api">ApplicationContext</a> has been built. In this case you can define a <code>doWithApplicationContext</code> closure property.<p class="paragraph"/><div class="code"><pre>class SimplePlugin <span class="java-keyword">extends</span> Plugin{<p class="paragraph"/> def name = <span class="java-quote">"simple"</span> |
| def version = <span class="java-quote">"1.1"</span><p class="paragraph"/> @Override |
| void doWithApplicationContext() { |
| def sessionFactory = applicationContext.sessionFactory |
| // <span class="java-keyword">do</span> something here with session factory |
| } |
| }</pre></div> |
| |
| |
| |
| <h2 id="addingMethodsAtCompileTime">17.6 Adding Methods at Compile Time</h2> |
| Grails 3.0 makes it easy to add new traits to existing artefact types from a plugin. For example say you wanted to add methods for manipulating dates to controllers. This can be done by first defining a trait in <code>src/main/groovy</code>:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> myplugin<p class="paragraph"/>trait DateTrait { |
| Date currentDate() { |
| <span class="java-keyword">return</span> <span class="java-keyword">new</span> Date() |
| } |
| }</pre></div><p class="paragraph"/>Once you have a trait you must tell Grails which artefacts you want to inject the trait into at compile time. To do this you implement a <a href="http://grails.org/doc/3.0.x/api/grails/compiler/traits/TraitInjector.html" class="api">TraitInjector</a>:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> myplugin<p class="paragraph"/>@CompileStatic |
| class ControllerTraitInjector <span class="java-keyword">implements</span> TraitInjector {<p class="paragraph"/> @Override |
| <span class="java-object">Class</span> getTrait() { |
| DateTrait |
| }<p class="paragraph"/> @Override |
| <span class="java-object">String</span>[] getArtefactTypes() { |
| ['Controller'] as <span class="java-object">String</span>[] |
| } |
| }</pre></div><p class="paragraph"/>The above <code>TraitInjector</code> will add the <code>DateTrait</code> to all controllers. The <code>getArtefactTypes</code> method defines the types of artefacts that the trait should be applied to. |
| |
| |
| <a name="15.8 Adding Dynamic Methods at Runtime"><!-- Legacy link --></a> |
| <h2 id="addingDynamicMethodsAtRuntime">17.7 Adding Dynamic Methods at Runtime</h2> |
| <h4>The Basics</h4><p class="paragraph"/>Grails plugins let you register dynamic methods with any Grails-managed or other class at runtime. This work is done in a <code>doWithDynamicMethods</code> method.<p class="paragraph"/><blockquote class="note"> |
| Note that Grails 3.x features newer features such as traits that are usable from code compiled with <code>CompileStatic</code>. It is recommended that dynamic behavior is only added for cases that are not possible with traits. |
| </blockquote><p class="paragraph"/><div class="code"><pre>class ExamplePlugin <span class="java-keyword">extends</span> Plugin { |
| void doWithDynamicMethods() { |
| <span class="java-keyword">for</span> (controllerClass in grailsApplication.controllerClasses) { |
| controllerClass.metaClass.myNewMethod = {-> println <span class="java-quote">"hello world"</span> } |
| } |
| } |
| }</pre></div><p class="paragraph"/>In this case we use the implicit application object to get a reference to all of the controller classes' MetaClass instances and add a new method called <code>myNewMethod</code> to each controller. If you know beforehand the class you wish the add a method to you can simply reference its <code>metaClass</code> property.<p class="paragraph"/>For example we can add a new method <code>swapCase</code> to <code>java.lang.String</code>:<p class="paragraph"/><div class="code"><pre>class ExamplePlugin <span class="java-keyword">extends</span> Plugin {<p class="paragraph"/> @Override |
| void doWithDynamicMethods() { |
| <span class="java-object">String</span>.metaClass.swapCase = {-> |
| def sb = <span class="java-keyword">new</span> StringBuilder() |
| delegate.each { |
| sb << (<span class="java-object">Character</span>.isUpperCase(it as <span class="java-object">char</span>) ? |
| <span class="java-object">Character</span>.toLowerCase(it as <span class="java-object">char</span>) : |
| <span class="java-object">Character</span>.toUpperCase(it as <span class="java-object">char</span>)) |
| } |
| sb.toString() |
| }<p class="paragraph"/> assert <span class="java-quote">"UpAndDown"</span> == <span class="java-quote">"uPaNDdOWN"</span>.swapCase() |
| } |
| }</pre></div><p class="paragraph"/><h4>Interacting with the ApplicationContext</h4><p class="paragraph"/>The <code>doWithDynamicMethods</code> closure gets passed the Spring <code>ApplicationContext</code> instance. This is useful as it lets you interact with objects within it. For example if you were implementing a method to interact with Hibernate you could use the <code>SessionFactory</code> instance in combination with a <code>HibernateTemplate</code>:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.springframework.orm.hibernate3.HibernateTemplate<p class="paragraph"/>class ExampleHibernatePlugin <span class="java-keyword">extends</span> Plugin{<p class="paragraph"/> void doWithDynamicMethods() {<p class="paragraph"/> <span class="java-keyword">for</span> (domainClass in grailsApplication.domainClasses) {<p class="paragraph"/> domainClass.metaClass.<span class="java-keyword">static</span>.load = { <span class="java-object">Long</span> id-> |
| def sf = applicationContext.sessionFactory |
| def template = <span class="java-keyword">new</span> HibernateTemplate(sf) |
| template.load(delegate, id) |
| } |
| } |
| } |
| }</pre></div><p class="paragraph"/>Also because of the autowiring and dependency injection capability of the Spring container you can implement more powerful dynamic constructors that use the application context to wire dependencies into your object at runtime:<p class="paragraph"/><div class="code"><pre>class MyConstructorPlugin {<p class="paragraph"/> void doWithDynamicMethods() |
| <span class="java-keyword">for</span> (domainClass in grailsApplication.domainClasses) { |
| domainClass.metaClass.constructor = {-> |
| <span class="java-keyword">return</span> applicationContext.getBean(domainClass.name) |
| } |
| } |
| } |
| }</pre></div><p class="paragraph"/>Here we actually replace the default constructor with one that looks up prototyped Spring beans instead! |
| |
| |
| <a name="15.9 Participating in Auto Reload Events"><!-- Legacy link --></a> |
| <h2 id="participatingInAutoReloadEvents">17.8 Participating in Auto Reload Events</h2> |
| <h4>Monitoring Resources for Changes</h4><p class="paragraph"/>Often it is valuable to monitor resources for changes and perform some action when they occur. This is how Grails implements advanced reloading of application state at runtime. For example, consider this simplified snippet from the Grails <code>ServicesPlugin</code>:<p class="paragraph"/><div class="code"><pre>class ServicesGrailsPlugin <span class="java-keyword">extends</span> Plugin { |
| … |
| def watchedResources = <span class="java-quote">"file:./grails-app/services/*Service.groovy"</span><p class="paragraph"/> … |
| void onChange( Map<<span class="java-object">String</span>, <span class="java-object">Object</span>> event) { |
| <span class="java-keyword">if</span> (event.source) { |
| def serviceClass = grailsApplication.addServiceClass(event.source) |
| def serviceName = <span class="java-quote">"${serviceClass.propertyName}"</span> |
| beans { |
| <span class="java-quote">"$serviceName"</span>(serviceClass.getClazz()) { bean -> |
| bean.autowire = <span class="java-keyword">true</span> |
| } |
| } |
| } |
| } |
| }</pre></div><p class="paragraph"/>First it defines <code>watchedResources</code> as either a String or a List of strings that contain either the references or patterns of the resources to watch. If the watched resources specify a Groovy file, when it is changed it will automatically be reloaded and passed into the <code>onChange</code> closure in the <code>event</code> object.<p class="paragraph"/>The <code>event</code> object defines a number of useful properties: |
| <ul class="star"> |
| <li><code>event.source</code> - The source of the event, either the reloaded <code>Class</code> or a Spring <code>Resource</code></li> |
| <li><code>event.ctx</code> - The Spring <code>ApplicationContext</code> instance</li> |
| <li><code>event.plugin</code> - The plugin object that manages the resource (usually <code>this</code>)</li> |
| <li><code>event.application</code> - The <code>GrailsApplication</code> instance</li> |
| <li><code>event.manager</code> - The <code>GrailsPluginManager</code> instance</li> |
| </ul><p class="paragraph"/>These objects are available to help you apply the appropriate changes based on what changed. In the "Services" example above, a new service bean is re-registered with the <code>ApplicationContext</code> when one of the service classes changes.<p class="paragraph"/><h4>Influencing Other Plugins</h4><p class="paragraph"/>In addition to reacting to changes, sometimes a plugin needs to "influence" another.<p class="paragraph"/>Take for example the Services and Controllers plugins. When a service is reloaded, unless you reload the controllers too, problems will occur when you try to auto-wire the reloaded service into an older controller Class.<p class="paragraph"/>To get around this, you can specify which plugins another plugin "influences". This means that when one plugin detects a change, it will reload itself and then reload its influenced plugins. For example consider this snippet from the <code>ServicesGrailsPlugin</code>:<p class="paragraph"/><div class="code"><pre>def influences = ['controllers']</pre></div><p class="paragraph"/><h4>Observing other plugins</h4><p class="paragraph"/>If there is a particular plugin that you would like to observe for changes but not necessary watch the resources that it monitors you can use the "observe" property:<p class="paragraph"/><div class="code"><pre>def observe = [<span class="java-quote">"controllers"</span>]</pre></div><p class="paragraph"/>In this case when a controller is changed you will also receive the event chained from the controllers plugin.<p class="paragraph"/>It is also possible for a plugin to observe all loaded plugins by using a wildcard:<p class="paragraph"/><div class="code"><pre>def observe = [<span class="java-quote">"*"</span>]</pre></div><p class="paragraph"/>The Logging plugin does exactly this so that it can add the <code>log</code> property back to <em class="italic">any</em> artefact that changes while the application is running. |
| |
| |
| <a name="15.10 Understanding Plug-in Load Order"><!-- Legacy link --></a> |
| <h2 id="understandingPluginLoadOrder">17.9 Understanding Plugin Load Order</h2> |
| <h4>Controlling Plugin Dependencies</h4><p class="paragraph"/>Plugins often depend on the presence of other plugins and can adapt depending on the presence of others. This is implemented with two properties. The first is called <code>dependsOn</code>. For example, take a look at this snippet from the Hibernate plugin:<p class="paragraph"/><div class="code"><pre>class HibernateGrailsPlugin {<p class="paragraph"/> def version = <span class="java-quote">"1.0"</span><p class="paragraph"/> def dependsOn = [dataSource: <span class="java-quote">"1.0"</span>, |
| domainClass: <span class="java-quote">"1.0"</span>, |
| i18n: <span class="java-quote">"1.0"</span>, |
| core: <span class="java-quote">"1.0"</span>] |
| }</pre></div><p class="paragraph"/>The Hibernate plugin is dependent on the presence of four plugins: the <code>dataSource</code>, <code>domainClass</code>, <code>i18n</code> and <code>core</code> plugins.<p class="paragraph"/>The dependencies will be loaded before the Hibernate plugin and if all dependencies do not load, then the plugin will not load.<p class="paragraph"/>The <code>dependsOn</code> property also supports a mini expression language for specifying version ranges. A few examples of the syntax can be seen below:<p class="paragraph"/><div class="code"><pre>def dependsOn = [foo: <span class="java-quote">"* > 1.0"</span>] |
| def dependsOn = [foo: <span class="java-quote">"1.0 > 1.1"</span>] |
| def dependsOn = [foo: <span class="java-quote">"1.0 > *"</span>]</pre></div><p class="paragraph"/>When the wildcard * character is used it denotes "any" version. The expression syntax also excludes any suffixes such as -BETA, -ALPHA etc. so for example the expression "1.0 > 1.1" would match any of the following versions: |
| <ul class="star"> |
| <li>1.1</li> |
| <li>1.0</li> |
| <li>1.0.1</li> |
| <li>1.0.3-SNAPSHOT</li> |
| <li>1.1-BETA2</li> |
| </ul><p class="paragraph"/><h4>Controlling Load Order</h4><p class="paragraph"/>Using <code>dependsOn</code> establishes a "hard" dependency in that if the dependency is not resolved, the plugin will give up and won't load. It is possible though to have a weaker dependency using the <code>loadAfter</code> and <code>loadBefore</code> properties:<p class="paragraph"/><div class="code"><pre>def loadAfter = ['controllers']</pre></div><p class="paragraph"/>Here the plugin will be loaded after the <code>controllers</code> plugin if it exists, otherwise it will just be loaded. The plugin can then adapt to the presence of the other plugin, for example the Hibernate plugin has this code in its <code>doWithSpring</code> closure:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">if</span> (manager?.hasGrailsPlugin(<span class="java-quote">"controllers"</span>)) { |
| openSessionInViewInterceptor(OpenSessionInViewInterceptor) { |
| flushMode = HibernateAccessor.FLUSH_MANUAL |
| sessionFactory = sessionFactory |
| } |
| grailsUrlHandlerMapping.interceptors << openSessionInViewInterceptor |
| }</pre></div><p class="paragraph"/>Here the Hibernate plugin will only register an <code>OpenSessionInViewInterceptor</code> if the <code>controllers</code> plugin has been loaded. The <code>manager</code> variable is an instance of the <a href="http://grails.org/doc/3.0.x/api/grails/plugins/GrailsPluginManager.html" class="api">GrailsPluginManager</a> interface and it provides methods to interact with other plugins.<p class="paragraph"/>You can also use the <code>loadBefore</code> property to specify one or more plugins that your plugin should load before:<p class="paragraph"/><div class="code"><pre>def loadBefore = ['rabbitmq']</pre></div><p class="paragraph"/><h4>Scopes and Environments</h4><p class="paragraph"/>It's not only plugin load order that you can control. You can also specify which environments your plugin should be loaded in and which scopes (stages of a build). Simply declare one or both of these properties in your plugin descriptor:<p class="paragraph"/><div class="code"><pre>def environments = ['development', 'test', 'myCustomEnv'] |
| def scopes = [excludes:'war']</pre></div><p class="paragraph"/>In this example, the plugin will only load in the 'development' and 'test' environments. Nor will it be packaged into the WAR file, because it's excluded from the 'war' phase. This allows <code>development-only</code> plugins to not be packaged for production use.<p class="paragraph"/>The full list of available scopes are defined by the enum <a href="http://grails.org/doc/3.0.x/api/grails/util/BuildScope.html" class="api">BuildScope</a>, but here's a summary: |
| <ul class="star"> |
| <li><code>test</code> - when running tests</li> |
| <li><code>functional-test</code> - when running functional tests</li> |
| <li><code>run</code> - for run-app and run-war</li> |
| <li><code>war</code> - when packaging the application as a WAR file</li> |
| <li><code>all</code> - plugin applies to all scopes (default)</li> |
| </ul><p class="paragraph"/>Both properties can be one of: |
| <ul class="star"> |
| <li>a string - a sole inclusion</li> |
| <li>a list - a list of environments or scopes to include</li> |
| <li>a map - for full control, with 'includes' and/or 'excludes' keys that can have string or list values</li> |
| </ul><p class="paragraph"/>For example,<p class="paragraph"/><div class="code"><pre>def environments = <span class="java-quote">"test"</span></pre></div><p class="paragraph"/>will only include the plugin in the test environment, whereas<p class="paragraph"/><div class="code"><pre>def environments = [<span class="java-quote">"development"</span>, <span class="java-quote">"test"</span>]</pre></div><p class="paragraph"/>will include it in both the development <em class="italic">and</em> test environments. Finally,<p class="paragraph"/><div class="code"><pre>def environments = [includes: [<span class="java-quote">"development"</span>, <span class="java-quote">"test"</span>]]</pre></div><p class="paragraph"/>will do the same thing. |
| |
| |
| |
| <h2 id="artefactApi">17.10 The Artefact API</h2> |
| You should by now understand that Grails has the concept of artefacts: special types of classes that it knows about and can treat differently from normal Groovy and Java classes, for example by enhancing them with extra properties and methods. Examples of artefacts include domain classes and controllers. What you may not be aware of is that Grails allows application and plugin developers access to the underlying infrastructure for artefacts, which means you can find out what artefacts are available and even enhance them yourself. You can even provide your own custom artefact types. |
| |
| |
| |
| <h2 id="queryingArtefacts">17.10.1 Asking About Available Artefacts</h2> |
| As a plugin developer, it can be important for you to find out about what domain classes, controllers, or other types of artefact are available in an application. For example, the <a href="http://grails.org/plugin/searchable" target="blank">Searchable plugin</a> needs to know what domain classes exist so it can check them for any <code>searchable</code> properties and index the appropriate ones. So how does it do it? The answer lies with the <code>grailsApplication</code> object, and instance of <a href="http://grails.org/doc/3.0.x/api/grails/core/GrailsApplication.html" class="api">GrailsApplication</a> that's available automatically in controllers and GSPs and can be <a href="../guide/single.html#dependencyInjectionServices" class="guide">injected</a> everywhere else.<p class="paragraph"/>The <code>grailsApplication</code> object has several important properties and methods for querying artefacts. Probably the most common is the one that gives you all the classes of a particular artefact type:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">for</span> (cls in grailsApplication.<artefactType>Classes) { |
| … |
| }</pre></div><p class="paragraph"/>In this case, <code>artefactType</code> is the property name form of the artefact type. With core Grails you have: |
| <ul class="star"> |
| <li>domain</li> |
| <li>controller</li> |
| <li>tagLib</li> |
| <li>service</li> |
| <li>codec</li> |
| <li>bootstrap</li> |
| <li>urlMappings</li> |
| </ul><p class="paragraph"/>So for example, if you want to iterate over all the domain classes, you use:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">for</span> (cls in grailsApplication.domainClasses) { |
| … |
| }</pre></div><p class="paragraph"/>and for URL mappings:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">for</span> (cls in grailsApplication.urlMappingsClasses) { |
| … |
| }</pre></div><p class="paragraph"/>You need to be aware that the objects returned by these properties are not instances of <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html" class="api">Class</a>. Instead, they are instances of <a href="http://grails.org/doc/3.0.x/api/grails/core/GrailsClass.html" class="api">GrailsClass</a> that has some particularly useful properties and methods, including one for the underlying <code>Class</code>: |
| <ul class="star"> |
| <li><code>shortName</code> - the class name of the artefact without the package (equivalent of <code>Class.simpleName</code>).</li> |
| <li><code>logicalPropertyName</code> - the artefact name in property form without the 'type' suffix. So <code>MyGreatController</code> becomes 'myGreat'.</li> |
| <li><code>isAbstract()</code> - a boolean indicating whether the artefact class is abstract or not.</li> |
| <li><code>getPropertyValue(name)</code> - returns the value of the given property, whether it's a static or an instance one. This works best if the property is initialised on declaration, e.g. <code>static transactional = true</code>.</li> |
| </ul><p class="paragraph"/>The artefact API also allows you to fetch classes by name and check whether a class is an artefact: |
| <ul class="star"> |
| <li>get<type>Class(String name)</li> |
| <li>is<type>Class(Class clazz)</li> |
| </ul><p class="paragraph"/>The first method will retrieve the <code>GrailsClass</code> instance for the given name, e.g. 'MyGreatController'. The second will check whether a class is a particular type of artefact. For example, you can use <code>grailsApplication.isControllerClass(org.example.MyGreatController)</code> to check whether <code>MyGreatController</code> is in fact a controller. |
| |
| |
| |
| <h2 id="customArtefacts">17.10.2 Adding Your Own Artefact Types</h2> |
| Plugins can easily provide their own artefacts so that they can easily find out what implementations are available and take part in reloading. All you need to do is create an <code>ArtefactHandler</code> implementation and register it in your main plugin class:<p class="paragraph"/><div class="code"><pre>class MyGrailsPlugin { |
| def artefacts = [ org.somewhere.MyArtefactHandler ] |
| … |
| }</pre></div><p class="paragraph"/>The <code>artefacts</code> list can contain either handler classes (as above) or instances of handlers.<p class="paragraph"/>So, what does an artefact handler look like? Well, put simply it is an implementation of the <a href="http://grails.org/doc/3.0.x/api/grails/core/ArtefactHandler.html" class="api">ArtefactHandler</a> interface. To make life a bit easier, there is a skeleton implementation that can readily be extended: <a href="http://grails.org/doc/3.0.x/api/grails/core/ArtefactHandlerAdapter.html" class="api">ArtefactHandlerAdapter</a>.<p class="paragraph"/>In addition to the handler itself, every new artefact needs a corresponding wrapper class that implements <a href="http://grails.org/doc/3.0.x/api/grails/core/GrailsClass.html" class="api">GrailsClass</a>. Again, skeleton implementations are available such as <a href="http://grails.org/doc/3.0.x/api/org/grails/core/AbstractInjectableGrailsClass.html" class="api">AbstractInjectableGrailsClass</a>, which is particularly useful as it turns your artefact into a Spring bean that is auto-wired, just like controllers and services.<p class="paragraph"/>The best way to understand how both the handler and wrapper classes work is to look at the Quartz plugin: |
| <ul class="star"> |
| <li><a href="http://github.com/nebolsin/grails-quartz/blob/master/src/java/grails/plugins/quartz/GrailsJobClass.java" target="blank">GrailsJobClass</a></li> |
| <li><a href="http://github.com/nebolsin/grails-quartz/blob/master/src/java/grails/plugins/quartz/DefaultGrailsJobClass.java" target="blank">DefaultGrailsJobClass</a></li> |
| <li><a href="http://github.com/nebolsin/grails-quartz/blob/master/src/java/grails/plugins/quartz/JobArtefactHandler.java" target="blank">JobArtefactHandler</a></li> |
| </ul><p class="paragraph"/>Another example is the <a href="http://github.com/pledbrook/grails-shiro" target="blank">Shiro plugin</a> which adds a realm artefact. |
| |
| |
| <a name="16. Grails and Spring"><!-- Legacy link --></a> |
| <h1 id="spring">18 Grails and Spring</h1> |
| This section is for advanced users and those who are interested in how Grails integrates with and builds on the <a href="http://www.springframework.org/" target="blank">Spring Framework</a>. It is also useful for <a href="../guide/single.html#plugins" class="guide">plugin developers</a> considering doing runtime configuration Grails. |
| |
| |
| <a name="16.1 The Underpinnings of Grails"><!-- Legacy link --></a> |
| <h2 id="theUnderpinningsOfGrails">18.1 The Underpinnings of Grails</h2> |
| Grails is actually a <a href="http://www.springframework.org/docs/MVC-step-by-step/Spring-MVC-step-by-step.html" target="blank">Spring MVC</a> application in disguise. Spring MVC is the Spring framework's built-in MVC web application framework. Although Spring MVC suffers from some of the same difficulties as frameworks like Struts in terms of its ease of use, it is superbly designed and architected and was, for Grails, the perfect framework to build another framework on top of.<p class="paragraph"/>Grails leverages Spring MVC in the following areas: |
| <ul class="star"> |
| <li>Basic controller logic - Grails subclasses Spring's <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html" class="api">DispatcherServlet</a> and uses it to delegate to Grails <a href="../guide/single.html#controllers" class="guide">controllers</a></li> |
| <li>Data Binding and Validation - Grails' <a href="../guide/single.html#validation" class="guide">validation</a> and <a href="../guide/single.html#dataBinding" class="guide">data binding</a> capabilities are built on those provided by Spring</li> |
| <li>Runtime configuration - Grails' entire runtime convention based system is wired together by a Spring <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/context/ApplicationContext.html" class="api">ApplicationContext</a></li> |
| <li>Transactions - Grails uses Spring's transaction management in <a href="../guide/single.html#GORM" class="guide">GORM</a></li> |
| </ul><p class="paragraph"/>In other words Grails has Spring embedded running all the way through it.<p class="paragraph"/><h4>The Grails ApplicationContext</h4><p class="paragraph"/>Spring developers are often keen to understand how the Grails <code>ApplicationContext</code> instance is constructed. The basics of it are as follows. |
| <ul class="star"> |
| <li>Grails constructs a parent <code>ApplicationContext</code> from the <code>web-app/WEB-INF/applicationContext.xml</code> file. This <code>ApplicationContext</code> configures the <a href="http://grails.org/doc/3.0.x/api/grails/core/GrailsApplication.html" class="api">GrailsApplication</a> instance and the <a href="http://grails.org/doc/3.0.x/api/grails/plugins/GrailsPluginManager.html" class="api">GrailsPluginManager</a>.</li> |
| <li>Using this <code>ApplicationContext</code> as a parent Grails' analyses the conventions with the <code>GrailsApplication</code> instance and constructs a child <code>ApplicationContext</code> that is used as the root <code>ApplicationContext</code> of the web application</li> |
| </ul><p class="paragraph"/><h4>Configured Spring Beans</h4><p class="paragraph"/>Most of Grails' configuration happens at runtime. Each <a href="../guide/single.html#plugins" class="guide">plugin</a> may configure Spring beans that are registered in the <code>ApplicationContext</code>. For a reference as to which beans are configured, refer to the reference guide which describes each of the Grails plugins and which beans they configure. |
| |
| |
| <a name="16.2 Configuring Additional Beans"><!-- Legacy link --></a> |
| <h2 id="springdslAdditional">18.2 Configuring Additional Beans</h2> |
| <h4>Using the Spring Bean DSL</h4><p class="paragraph"/>You can easily register new (or override existing) beans by configuring them in <code>grails-app/conf/spring/resources.groovy</code> which uses the Grails <a href="../guide/single.html#springdsl" class="guide">Spring DSL</a>. Beans are defined inside a <code>beans</code> property (a Closure):<p class="paragraph"/><div class="code"><pre>beans = { |
| // beans here |
| }</pre></div><p class="paragraph"/>As a simple example you can configure a bean with the following syntax:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> my.company.MyBeanImpl<p class="paragraph"/>beans = { |
| myBean(MyBeanImpl) { |
| someProperty = 42 |
| otherProperty = <span class="java-quote">"blue"</span> |
| } |
| }</pre></div><p class="paragraph"/>Once configured, the bean can be auto-wired into Grails artifacts and other classes that support dependency injection (for example <code>BootStrap.groovy</code> and integration tests) by declaring a public field whose name is your bean's name (in this case <code>myBean</code>):<p class="paragraph"/><div class="code"><pre>class ExampleController {<p class="paragraph"/> def myBean |
| … |
| }</pre></div><p class="paragraph"/>Using the DSL has the advantage that you can mix bean declarations and logic, for example based on the <a href="../guide/single.html#environments" class="guide">environment</a>:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.util.Environment |
| <span class="java-keyword">import</span> my.company.mock.MockImpl |
| <span class="java-keyword">import</span> my.company.MyBeanImpl<p class="paragraph"/>beans = { |
| <span class="java-keyword">switch</span>(Environment.current) { |
| <span class="java-keyword">case</span> Environment.PRODUCTION: |
| myBean(MyBeanImpl) { |
| someProperty = 42 |
| otherProperty = <span class="java-quote">"blue"</span> |
| } |
| <span class="java-keyword">break</span><p class="paragraph"/> <span class="java-keyword">case</span> Environment.DEVELOPMENT: |
| myBean(MockImpl) { |
| someProperty = 42 |
| otherProperty = <span class="java-quote">"blue"</span> |
| } |
| <span class="java-keyword">break</span> |
| } |
| }</pre></div><p class="paragraph"/>The <code>GrailsApplication</code> object can be accessed with the <code>application</code> variable and can be used to access the Grails configuration (amongst other things):<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.util.Environment |
| <span class="java-keyword">import</span> my.company.mock.MockImpl |
| <span class="java-keyword">import</span> my.company.MyBeanImpl<p class="paragraph"/>beans = { |
| <span class="java-keyword">if</span> (application.config.my.company.mockService) { |
| myBean(MockImpl) { |
| someProperty = 42 |
| otherProperty = <span class="java-quote">"blue"</span> |
| } |
| } <span class="java-keyword">else</span> { |
| myBean(MyBeanImpl) { |
| someProperty = 42 |
| otherProperty = <span class="java-quote">"blue"</span> |
| } |
| } |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| If you define a bean in <code>resources.groovy</code> with the same name as one previously registered by Grails or an installed plugin, your bean will replace the previous registration. This is a convenient way to customize behavior without resorting to editing plugin code or other approaches that would affect maintainability. |
| </blockquote><p class="paragraph"/><h4>Using XML</h4><p class="paragraph"/>Beans can also be configured using a <code>grails-app/conf/spring/resources.xml</code>. In earlier versions of Grails this file was automatically generated for you by the <code>run-app</code> script, but the DSL in <code>resources.groovy</code> is the preferred approach now so it isn't automatically generated now. But it is still supported - you just need to create it yourself.<p class="paragraph"/>This file is typical Spring XML file and the Spring documentation has an <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-basics" target="blank">excellent reference</a> on how to configure Spring beans.<p class="paragraph"/>The <code>myBean</code> bean that we configured using the DSL would be configured with this syntax in the XML file:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><bean id=<span class="xml-quote">"myBean"</span> class=<span class="xml-quote">"my.company.MyBeanImpl"</span>></span> |
| <span class="xml-tag"><property name=<span class="xml-quote">"someProperty"</span> value=<span class="xml-quote">"42"</span> /></span> |
| <span class="xml-tag"><property name=<span class="xml-quote">"otherProperty"</span> value=<span class="xml-quote">"blue"</span> /></span> |
| <span class="xml-tag"></bean></span></pre></div><p class="paragraph"/>Like the other bean it can be auto-wired into any class that supports dependency injection:<p class="paragraph"/><div class="code"><pre>class ExampleController {<p class="paragraph"/> def myBean |
| }</pre></div><p class="paragraph"/><h4>Referencing Existing Beans</h4><p class="paragraph"/>Beans declared in <code>resources.groovy</code> or <code>resources.xml</code> can reference other beans by convention. For example if you had a <code>BookService</code> class its Spring bean name would be <code>bookService</code>, so your bean would reference it like this in the DSL:<p class="paragraph"/><div class="code"><pre>beans = { |
| myBean(MyBeanImpl) { |
| someProperty = 42 |
| otherProperty = <span class="java-quote">"blue"</span> |
| bookService = ref(<span class="java-quote">"bookService"</span>) |
| } |
| }</pre></div><p class="paragraph"/>or like this in XML:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><bean id=<span class="xml-quote">"myBean"</span> class=<span class="xml-quote">"my.company.MyBeanImpl"</span>></span> |
| <span class="xml-tag"><property name=<span class="xml-quote">"someProperty"</span> value=<span class="xml-quote">"42"</span> /></span> |
| <span class="xml-tag"><property name=<span class="xml-quote">"otherProperty"</span> value=<span class="xml-quote">"blue"</span> /></span> |
| <span class="xml-tag"><property name=<span class="xml-quote">"bookService"</span> ref=<span class="xml-quote">"bookService"</span> /></span> |
| <span class="xml-tag"></bean></span></pre></div><p class="paragraph"/>The bean needs a public setter for the bean reference (and also the two simple properties), which in Groovy would be defined like this:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> my.company<p class="paragraph"/>class MyBeanImpl { |
| <span class="java-object">Integer</span> someProperty |
| <span class="java-object">String</span> otherProperty |
| BookService bookService // or just <span class="java-quote">"def bookService"</span> |
| }</pre></div><p class="paragraph"/>or in Java like this:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> my.company;<p class="paragraph"/>class MyBeanImpl {<p class="paragraph"/> <span class="java-keyword">private</span> BookService bookService; |
| <span class="java-keyword">private</span> <span class="java-object">Integer</span> someProperty; |
| <span class="java-keyword">private</span> <span class="java-object">String</span> otherProperty;<p class="paragraph"/> <span class="java-keyword">public</span> void setBookService(BookService theBookService) { |
| <span class="java-keyword">this</span>.bookService = theBookService; |
| }<p class="paragraph"/> <span class="java-keyword">public</span> void setSomeProperty(<span class="java-object">Integer</span> someProperty) { |
| <span class="java-keyword">this</span>.someProperty = someProperty; |
| }<p class="paragraph"/> <span class="java-keyword">public</span> void setOtherProperty(<span class="java-object">String</span> otherProperty) { |
| <span class="java-keyword">this</span>.otherProperty = otherProperty; |
| } |
| }</pre></div><p class="paragraph"/>Using <code>ref</code> (in XML or the DSL) is very powerful since it configures a runtime reference, so the referenced bean doesn't have to exist yet. As long as it's in place when the final application context configuration occurs, everything will be resolved correctly.<p class="paragraph"/>For a full reference of the available beans see the plugin reference in the reference guide. |
| |
| |
| <a name="16.3 Runtime Spring with the Beans DSL"><!-- Legacy link --></a> |
| <h2 id="springdsl">18.3 Runtime Spring with the Beans DSL</h2> |
| This Bean builder in Grails aims to provide a simplified way of wiring together dependencies that uses Spring at its core.<p class="paragraph"/>In addition, Spring's regular way of configuration (via XML and annotations) is static and difficult to modify and configure at runtime, other than programmatic XML creation which is both error prone and verbose. Grails' <a href="http://grails.org/doc/3.0.x/api/grails/spring/BeanBuilder.html" class="api">BeanBuilder</a> changes all that by making it possible to programmatically wire together components at runtime, allowing you to adapt the logic based on system properties or environment variables.<p class="paragraph"/>This enables the code to adapt to its environment and avoids unnecessary duplication of code (having different Spring configs for test, development and production environments)<p class="paragraph"/><h4>The BeanBuilder class</h4><p class="paragraph"/>Grails provides a <a href="http://grails.org/doc/3.0.x/api/grails/spring/BeanBuilder.html" class="api">grails.spring.BeanBuilder</a> class that uses dynamic Groovy to construct bean definitions. The basics are as follows:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.apache.commons.dbcp.BasicDataSource |
| <span class="java-keyword">import</span> org.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean |
| <span class="java-keyword">import</span> org.springframework.context.ApplicationContext |
| <span class="java-keyword">import</span> grails.spring.BeanBuilder<p class="paragraph"/>def bb = <span class="java-keyword">new</span> BeanBuilder()<p class="paragraph"/>bb.beans {<p class="paragraph"/> dataSource(BasicDataSource) { |
| driverClassName = <span class="java-quote">"org.h2.Driver"</span> |
| url = <span class="java-quote">"jdbc:h2:mem:grailsDB"</span> |
| username = <span class="java-quote">"sa"</span> |
| password = <span class="java-quote">""</span> |
| }<p class="paragraph"/> sessionFactory(ConfigurableLocalSessionFactoryBean) { |
| dataSource = ref('dataSource') |
| hibernateProperties = [<span class="java-quote">"hibernate.hbm2ddl.auto"</span>: <span class="java-quote">"create-drop"</span>, |
| <span class="java-quote">"hibernate.show_sql"</span>: <span class="java-quote">"<span class="java-keyword">true</span>"</span>] |
| } |
| }<p class="paragraph"/>ApplicationContext appContext = bb.createApplicationContext()</pre></div><p class="paragraph"/><blockquote class="note"> |
| Within <a href="../guide/single.html#plugins" class="guide">plugins</a> and the <a href="../guide/single.html#springdslAdditional" class="guide">grails-app/conf/spring/resources.groovy</a> file you don't need to create a new instance of <code>BeanBuilder</code>. Instead the DSL is implicitly available inside the <code>doWithSpring</code> and <code>beans</code> blocks respectively. |
| </blockquote><p class="paragraph"/>This example shows how you would configure Hibernate with a data source with the <code>BeanBuilder</code> class.<p class="paragraph"/>Each method call (in this case <code>dataSource</code> and <code>sessionFactory</code> calls) maps to the name of the bean in Spring. The first argument to the method is the bean's class, whilst the last argument is a block. Within the body of the block you can set properties on the bean using standard Groovy syntax.<p class="paragraph"/>Bean references are resolved automatically using the name of the bean. This can be seen in the example above with the way the <code>sessionFactory</code> bean resolves the <code>dataSource</code> reference.<p class="paragraph"/>Certain special properties related to bean management can also be set by the builder, as seen in the following code:<p class="paragraph"/><div class="code"><pre>sessionFactory(ConfigurableLocalSessionFactoryBean) { bean -> |
| // Autowiring behaviour. The other option is 'byType'. [autowire] |
| bean.autowire = 'byName' |
| // Sets the initialisation method to 'init'. [init-method] |
| bean.initMethod = 'init' |
| // Sets the destruction method to 'destroy'. [destroy-method] |
| bean.destroyMethod = 'destroy' |
| // Sets the scope of the bean. [scope] |
| bean.scope = 'request' |
| dataSource = ref('dataSource') |
| hibernateProperties = [<span class="java-quote">"hibernate.hbm2ddl.auto"</span>: <span class="java-quote">"create-drop"</span>, |
| <span class="java-quote">"hibernate.show_sql"</span>: <span class="java-quote">"<span class="java-keyword">true</span>"</span>] |
| }</pre></div><p class="paragraph"/>The strings in square brackets are the names of the equivalent bean attributes in Spring's XML definition.<p class="paragraph"/><h4>Using BeanBuilder with Spring MVC</h4><p class="paragraph"/>Include the <code>grails-spring-<version>.jar</code> file in your classpath to use BeanBuilder in a regular Spring MVC application. Then add the following <code><context-param></code> values to your <code>/WEB-INF/web.xml</code> file:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><context-param></span> |
| <span class="xml-tag"><param-name></span>contextConfigLocation<span class="xml-tag"></param-name></span> |
| <span class="xml-tag"><param-value></span>/WEB-INF/applicationContext.groovy<span class="xml-tag"></param-value></span> |
| <span class="xml-tag"></context-param></span><p class="paragraph"/><span class="xml-tag"><context-param></span> |
| <span class="xml-tag"><param-name></span>contextClass<span class="xml-tag"></param-name></span> |
| <span class="xml-tag"><param-value></span> |
| grails.web.servlet.context.GrailsWebApplicationContext |
| <span class="xml-tag"></param-value></span> |
| <span class="xml-tag"></context-param></span></pre></div><p class="paragraph"/>Then create a <code>/WEB-INF/applicationContext.groovy</code> file that does the rest:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.apache.commons.dbcp.BasicDataSource<p class="paragraph"/>beans { |
| dataSource(BasicDataSource) { |
| driverClassName = <span class="java-quote">"org.h2.Driver"</span> |
| url = <span class="java-quote">"jdbc:h2:mem:grailsDB"</span> |
| username = <span class="java-quote">"sa"</span> |
| password = <span class="java-quote">""</span> |
| } |
| }</pre></div><p class="paragraph"/><h4>Loading Bean Definitions from the File System</h4><p class="paragraph"/>You can use the <code>BeanBuilder</code> class to load external Groovy scripts that define beans using the same path matching syntax defined here. For example:<p class="paragraph"/><div class="code"><pre>def bb = <span class="java-keyword">new</span> BeanBuilder() |
| bb.loadBeans(<span class="java-quote">"classpath:*SpringBeans.groovy"</span>)<p class="paragraph"/>def applicationContext = bb.createApplicationContext()</pre></div><p class="paragraph"/>Here the <code>BeanBuilder</code> loads all Groovy files on the classpath ending with <code>SpringBeans.groovy</code> and parses them into bean definitions. An example script can be seen below:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.apache.commons.dbcp.BasicDataSource |
| <span class="java-keyword">import</span> org.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean<p class="paragraph"/>beans {<p class="paragraph"/> dataSource(BasicDataSource) { |
| driverClassName = <span class="java-quote">"org.h2.Driver"</span> |
| url = <span class="java-quote">"jdbc:h2:mem:grailsDB"</span> |
| username = <span class="java-quote">"sa"</span> |
| password = <span class="java-quote">""</span> |
| }<p class="paragraph"/> sessionFactory(ConfigurableLocalSessionFactoryBean) { |
| dataSource = dataSource |
| hibernateProperties = [<span class="java-quote">"hibernate.hbm2ddl.auto"</span>: <span class="java-quote">"create-drop"</span>, |
| <span class="java-quote">"hibernate.show_sql"</span>: <span class="java-quote">"<span class="java-keyword">true</span>"</span>] |
| } |
| }</pre></div><p class="paragraph"/><h4>Adding Variables to the Binding (Context)</h4><p class="paragraph"/>If you're loading beans from a script you can set the binding to use by creating a Groovy <code>Binding</code>:<p class="paragraph"/><div class="code"><pre>def binding = <span class="java-keyword">new</span> Binding() |
| binding.maxSize = 10000 |
| binding.productGroup = 'finance'<p class="paragraph"/>def bb = <span class="java-keyword">new</span> BeanBuilder() |
| bb.binding = binding |
| bb.loadBeans(<span class="java-quote">"classpath:*SpringBeans.groovy"</span>)<p class="paragraph"/>def ctx = bb.createApplicationContext()</pre></div><p class="paragraph"/>Then you can access the <code>maxSize</code> and <code>productGroup</code> properties in your DSL files. |
| |
| |
| <a name="16.4 The BeanBuilder DSL Explained"><!-- Legacy link --></a> |
| <h2 id="theBeanBuilderDSLExplained">18.4 The BeanBuilder DSL Explained</h2> |
| <h4>Using Constructor Arguments</h4><p class="paragraph"/>Constructor arguments can be defined using parameters to each bean-defining method. Put them after the first argument (the Class): |
| <div class="code"><pre>bb.beans { |
| exampleBean(MyExampleBean, <span class="java-quote">"firstArgument"</span>, 2) { |
| someProperty = [1, 2, 3] |
| } |
| }</pre></div><p class="paragraph"/>This configuration corresponds to a <code>MyExampleBean</code> with a constructor that looks like this:<p class="paragraph"/><div class="code"><pre>MyExampleBean(<span class="java-object">String</span> foo, <span class="java-object">int</span> bar) { |
| … |
| }</pre></div><p class="paragraph"/><h4>Configuring the BeanDefinition (Using factory methods)</h4><p class="paragraph"/>The first argument to the closure is a reference to the bean configuration instance, which you can use to configure factory methods and invoke any method on the <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/beans/factory/support/AbstractBeanDefinition.html" class="api">AbstractBeanDefinition</a> class:<p class="paragraph"/><div class="code"><pre>bb.beans { |
| exampleBean(MyExampleBean) { bean -> |
| bean.factoryMethod = <span class="java-quote">"getInstance"</span> |
| bean.singleton = <span class="java-keyword">false</span> |
| someProperty = [1, 2, 3] |
| } |
| }</pre></div><p class="paragraph"/>As an alternative you can also use the return value of the bean defining method to configure the bean:<p class="paragraph"/><div class="code"><pre>bb.beans { |
| def example = exampleBean(MyExampleBean) { |
| someProperty = [1, 2, 3] |
| } |
| example.factoryMethod = <span class="java-quote">"getInstance"</span> |
| }</pre></div><p class="paragraph"/><h4>Using Factory beans</h4><p class="paragraph"/>Spring defines the concept of factory beans and often a bean is created not directly from a new instance of a Class, but from one of these factories. In this case the bean has no Class argument and instead you must pass the name of the factory bean to the bean defining method:<p class="paragraph"/><div class="code"><pre>bb.beans {<p class="paragraph"/> myFactory(ExampleFactoryBean) { |
| someProperty = [1, 2, 3] |
| }<p class="paragraph"/> myBean(myFactory) { |
| name = <span class="java-quote">"blah"</span> |
| } |
| }</pre></div><p class="paragraph"/>Another common approach is provide the name of the factory method to call on the factory bean. This can be done using Groovy's named parameter syntax:<p class="paragraph"/><div class="code"><pre>bb.beans {<p class="paragraph"/> myFactory(ExampleFactoryBean) { |
| someProperty = [1, 2, 3] |
| }<p class="paragraph"/> myBean(myFactory: <span class="java-quote">"getInstance"</span>) { |
| name = <span class="java-quote">"blah"</span> |
| } |
| }</pre></div><p class="paragraph"/>Here the <code>getInstance</code> method on the <code>ExampleFactoryBean</code> bean will be called to create the <code>myBean</code> bean.<p class="paragraph"/><h4>Creating Bean References at Runtime</h4><p class="paragraph"/>Sometimes you don't know the name of the bean to be created until runtime. In this case you can use a string interpolation to invoke a bean defining method dynamically:<p class="paragraph"/><div class="code"><pre>def beanName = <span class="java-quote">"example"</span> |
| bb.beans { |
| <span class="java-quote">"${beanName}Bean"</span>(MyExampleBean) { |
| someProperty = [1, 2, 3] |
| } |
| }</pre></div><p class="paragraph"/>In this case the <code>beanName</code> variable defined earlier is used when invoking a bean defining method. The example has a hard-coded value but would work just as well with a name that is generated programmatically based on configuration, system properties, etc.<p class="paragraph"/>Furthermore, because sometimes bean names are not known until runtime you may need to reference them by name when wiring together other beans, in this case using the <code>ref</code> method:<p class="paragraph"/><div class="code"><pre>def beanName = <span class="java-quote">"example"</span> |
| bb.beans {<p class="paragraph"/> <span class="java-quote">"${beanName}Bean"</span>(MyExampleBean) { |
| someProperty = [1, 2, 3] |
| }<p class="paragraph"/> anotherBean(AnotherBean) { |
| example = ref(<span class="java-quote">"${beanName}Bean"</span>) |
| } |
| }</pre></div><p class="paragraph"/>Here the example property of <code>AnotherBean</code> is set using a runtime reference to the <code>exampleBean</code>. The <code>ref</code> method can also be used to refer to beans from a parent <code>ApplicationContext</code> that is provided in the constructor of the <code>BeanBuilder</code>:<p class="paragraph"/><div class="code"><pre>ApplicationContext parent = ...// |
| def bb = <span class="java-keyword">new</span> BeanBuilder(parent) |
| bb.beans { |
| anotherBean(AnotherBean) { |
| example = ref(<span class="java-quote">"${beanName}Bean"</span>, <span class="java-keyword">true</span>) |
| } |
| }</pre></div><p class="paragraph"/>Here the second parameter <code>true</code> specifies that the reference will look for the bean in the parent context.<p class="paragraph"/><h4>Using Anonymous (Inner) Beans</h4><p class="paragraph"/>You can use anonymous inner beans by setting a property of the bean to a block that takes an argument that is the bean type:<p class="paragraph"/><div class="code"><pre>bb.beans {<p class="paragraph"/> marge(Person) { |
| name = <span class="java-quote">"Marge"</span> |
| husband = { Person p -> |
| name = <span class="java-quote">"Homer"</span> |
| age = 45 |
| props = [overweight: <span class="java-keyword">true</span>, height: <span class="java-quote">"1.8m"</span>] |
| } |
| children = [ref('bart'), ref('lisa')] |
| }<p class="paragraph"/> bart(Person) { |
| name = <span class="java-quote">"Bart"</span> |
| age = 11 |
| }<p class="paragraph"/> lisa(Person) { |
| name = <span class="java-quote">"Lisa"</span> |
| age = 9 |
| } |
| }</pre></div><p class="paragraph"/>In the above example we set the <code>marge</code> bean's husband property to a block that creates an inner bean reference. Alternatively if you have a factory bean you can omit the type and just use the specified bean definition instead to setup the factory:<p class="paragraph"/><div class="code"><pre>bb.beans {<p class="paragraph"/> personFactory(PersonFactory)<p class="paragraph"/> marge(Person) { |
| name = <span class="java-quote">"Marge"</span> |
| husband = { bean -> |
| bean.factoryBean = <span class="java-quote">"personFactory"</span> |
| bean.factoryMethod = <span class="java-quote">"newInstance"</span> |
| name = <span class="java-quote">"Homer"</span> |
| age = 45 |
| props = [overweight: <span class="java-keyword">true</span>, height: <span class="java-quote">"1.8m"</span>] |
| } |
| children = [ref('bart'), ref('lisa')] |
| } |
| }</pre></div><p class="paragraph"/><h4>Abstract Beans and Parent Bean Definitions</h4><p class="paragraph"/>To create an abstract bean definition define a bean without a <code>Class</code> parameter:<p class="paragraph"/><div class="code"><pre>class HolyGrailQuest { |
| def start() { println <span class="java-quote">"lets begin"</span> } |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class KnightOfTheRoundTable {<p class="paragraph"/> <span class="java-object">String</span> name |
| <span class="java-object">String</span> leader |
| HolyGrailQuest quest<p class="paragraph"/> KnightOfTheRoundTable(<span class="java-object">String</span> name) { |
| <span class="java-keyword">this</span>.name = name |
| }<p class="paragraph"/> def embarkOnQuest() { |
| quest.start() |
| } |
| }</pre></div><p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.spring.BeanBuilder<p class="paragraph"/>def bb = <span class="java-keyword">new</span> BeanBuilder() |
| bb.beans { |
| abstractBean { |
| leader = <span class="java-quote">"Lancelot"</span> |
| } |
| … |
| }</pre></div><p class="paragraph"/>Here we define an abstract bean that has a <code>leader</code> property with the value of <code>"Lancelot"</code>. To use the abstract bean set it as the parent of the child bean:<p class="paragraph"/><div class="code"><pre>bb.beans { |
| … |
| quest(HolyGrailQuest)<p class="paragraph"/> knights(KnightOfTheRoundTable, <span class="java-quote">"Camelot"</span>) { bean -> |
| bean.parent = abstractBean |
| quest = ref('quest') |
| } |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| When using a parent bean you must set the parent property of the bean before setting any other properties on the bean! |
| </blockquote><p class="paragraph"/>If you want an abstract bean that has a <code>Class</code> specified you can do it this way:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.spring.BeanBuilder<p class="paragraph"/>def bb = <span class="java-keyword">new</span> BeanBuilder() |
| bb.beans {<p class="paragraph"/> abstractBean(KnightOfTheRoundTable) { bean -> |
| bean.'<span class="java-keyword">abstract</span>' = <span class="java-keyword">true</span> |
| leader = <span class="java-quote">"Lancelot"</span> |
| }<p class="paragraph"/> quest(HolyGrailQuest)<p class="paragraph"/> knights(<span class="java-quote">"Camelot"</span>) { bean -> |
| bean.parent = abstractBean |
| quest = quest |
| } |
| }</pre></div><p class="paragraph"/>In this example we create an abstract bean of type <code>KnightOfTheRoundTable</code> and use the bean argument to set it to abstract. Later we define a knights bean that has no <code>Class</code> defined, but inherits the <code>Class</code> from the parent bean.<p class="paragraph"/><h4>Using Spring Namespaces</h4><p class="paragraph"/>Since Spring 2.0, users of Spring have had easier access to key features via XML namespaces. You can use a Spring namespace in BeanBuilder by declaring it with this syntax:<p class="paragraph"/><div class="code"><pre>xmlns context:<span class="java-quote">"http://www.springframework.org/schema/context"</span></pre></div><p class="paragraph"/>and then invoking a method that matches the names of the Spring namespace tag and its associated attributes:<p class="paragraph"/><div class="code"><pre>context.'component-scan'('base-<span class="java-keyword">package</span>': <span class="java-quote">"my.company.domain"</span>)</pre></div><p class="paragraph"/>You can do some useful things with Spring namespaces, such as looking up a JNDI resource:<p class="paragraph"/><div class="code"><pre>xmlns jee:<span class="java-quote">"http://www.springframework.org/schema/jee"</span><p class="paragraph"/>jee.'jndi-lookup'(id: <span class="java-quote">"dataSource"</span>, 'jndi-name': <span class="java-quote">"java:comp/env/myDataSource"</span>)</pre></div><p class="paragraph"/>This example will create a Spring bean with the identifier <code>dataSource</code> by performing a JNDI lookup on the given JNDI name. With Spring namespaces you also get full access to all of the powerful AOP support in Spring from BeanBuilder. For example given these two classes:<p class="paragraph"/><div class="code"><pre>class Person {<p class="paragraph"/> <span class="java-object">int</span> age |
| <span class="java-object">String</span> name<p class="paragraph"/> void birthday() { |
| ++age; |
| } |
| }</pre></div><p class="paragraph"/><div class="code"><pre>class BirthdayCardSender {<p class="paragraph"/> List peopleSentCards = []<p class="paragraph"/> void onBirthday(Person person) { |
| peopleSentCards << person |
| } |
| }</pre></div><p class="paragraph"/>You can define an aspect that uses a pointcut to detect whenever the <code>birthday()</code> method is called:<p class="paragraph"/><div class="code"><pre>xmlns aop:<span class="java-quote">"http://www.springframework.org/schema/aop"</span><p class="paragraph"/>fred(Person) { |
| name = <span class="java-quote">"Fred"</span> |
| age = 45 |
| }<p class="paragraph"/>birthdayCardSenderAspect(BirthdayCardSender)<p class="paragraph"/>aop { |
| config(<span class="java-quote">"proxy-target-class"</span>: <span class="java-keyword">true</span>) { |
| aspect(id: <span class="java-quote">"sendBirthdayCard"</span>, ref: <span class="java-quote">"birthdayCardSenderAspect"</span>) { |
| after method: <span class="java-quote">"onBirthday"</span>, |
| pointcut: <span class="java-quote">"execution(void ..Person.birthday()) and <span class="java-keyword">this</span>(person)"</span> |
| } |
| } |
| }</pre></div> |
| |
| |
| <a name="16.5 Property Placeholder Configuration"><!-- Legacy link --></a> |
| <h2 id="propertyPlaceholderConfiguration">18.5 Property Placeholder Configuration</h2> |
| Grails supports the notion of property placeholder configuration through an extended version of Spring's <a href="http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html" class="api">PropertyPlaceholderConfigurer</a>.<p class="paragraph"/>Settings defined in either <a href="http://groovy.codehaus.org/ConfigSlurper" target="blank">ConfigSlurper</a> scripts or Java properties files can be used as placeholder values for Spring configuration in <code>grails-app/conf/spring/resources.xml</code> and <code>grails-app/conf/spring/resources.groovy</code>. For example given the following entries in <code>grails-app/conf/Config.groovy</code> (or an externalized config):<p class="paragraph"/><div class="code"><pre>database.driver=<span class="java-quote">"com.mysql.jdbc.Driver"</span> |
| database.dbname=<span class="java-quote">"mysql:mydb"</span></pre></div><p class="paragraph"/>You can then specify placeholders in <code>resources.xml</code> as follows using the familiar ${..} syntax:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><bean id=<span class="xml-quote">"dataSource"</span> |
| class=<span class="xml-quote">"org.springframework.jdbc.datasource.DriverManagerDataSource"</span>></span> |
| <span class="xml-tag"><property name=<span class="xml-quote">"driverClassName"</span>></span> |
| <span class="xml-tag"><value></span>${database.driver}<span class="xml-tag"></value></span> |
| <span class="xml-tag"></property></span> |
| <span class="xml-tag"><property name=<span class="xml-quote">"url"</span>></span> |
| <span class="xml-tag"><value></span>jdbc:${database.dbname}<span class="xml-tag"></value></span> |
| <span class="xml-tag"></property></span> |
| <span class="xml-tag"></bean></span></pre></div><p class="paragraph"/>To specify placeholders in <code>resources.groovy</code> you need to use single quotes:<p class="paragraph"/><div class="code"><pre>dataSource(org.springframework.jdbc.datasource.DriverManagerDataSource) { |
| driverClassName = '${database.driver}' |
| url = 'jdbc:${database.dbname}' |
| }</pre></div><p class="paragraph"/>This sets the property value to a literal string which is later resolved against the config by Spring's PropertyPlaceholderConfigurer.<p class="paragraph"/>A better option for <code>resources.groovy</code> is to access properties through the <code>grailsApplication</code> variable:<p class="paragraph"/><div class="code"><pre>dataSource(org.springframework.jdbc.datasource.DriverManagerDataSource) { |
| driverClassName = grailsApplication.config.database.driver |
| url = <span class="java-quote">"jdbc:${grailsApplication.config.database.dbname}"</span> |
| }</pre></div><p class="paragraph"/>Using this approach will keep the types as defined in your config. |
| |
| |
| <a name="16.6 Property Override Configuration"><!-- Legacy link --></a> |
| <h2 id="propertyOverrideConfiguration">18.6 Property Override Configuration</h2> |
| Grails supports setting of bean properties via <a href="../guide/single.html#conf" class="guide">configuration</a>.<p class="paragraph"/>You define a <code>beans</code> block with the names of beans and their values:<p class="paragraph"/><div class="code"><pre>beans { |
| bookService { |
| webServiceURL = <span class="java-quote">"http://www.amazon.com"</span> |
| } |
| }</pre></div><p class="paragraph"/>The general format is:<p class="paragraph"/><div class="code"><pre>[bean name].[property name] = [value]</pre></div><p class="paragraph"/>The same configuration in a Java properties file would be:<p class="paragraph"/><div class="code"><pre>beans.bookService.webServiceURL=http://www.amazon.com</pre></div> |
| |
| |
| <a name="17. Grails and Hibernate"><!-- Legacy link --></a> |
| <h1 id="hibernate">19 Grails and Hibernate</h1> |
| If <a href="../guide/single.html#GORM" class="guide">GORM</a> (Grails Object Relational Mapping) is not flexible enough for your liking you can alternatively map your domain classes using Hibernate, either with XML mapping files or JPA annotations. You will be able to map Grails domain classes onto a wider range of legacy systems and have more flexibility in the creation of your database schema. Best of all, you will still be able to call all of the dynamic persistent and query methods provided by GORM! |
| |
| |
| <a name="17.1 Using Hibernate XML Mapping Files"><!-- Legacy link --></a> |
| <h2 id="usingHibernateXMLMappingFiles">19.1 Using Hibernate XML Mapping Files</h2> |
| Mapping your domain classes with XML is pretty straightforward. Simply create a <code>hibernate.cfg.xml</code> file in your project's <code>grails-app/conf/hibernate</code> directory, either manually or with the commandLine command, that contains the following:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><?xml version='1.0' encoding='UTF-8'?></span> |
| <!DOCTYPE hibernate-configuration PUBLIC |
| <span class="xml-quote">"-//Hibernate/Hibernate Configuration DTD 3.0//EN"</span> |
| <span class="xml-quote">"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"</span>> |
| <span class="xml-tag"><hibernate-configuration></span> |
| <span class="xml-tag"><session-factory></span> |
| <span class="xml-comment"><!-- Example mapping file inclusion --></span> |
| <span class="xml-tag"><mapping resource=<span class="xml-quote">"org.example.Book.hbm.xml"</span>/></span> |
| … |
| <span class="xml-tag"></session-factory></span> |
| <span class="xml-tag"></hibernate-configuration></span></pre></div><p class="paragraph"/>The individual mapping files, like 'org.example.Book.hbm.xml' in the above example, also go into the <code>grails-app/conf/hibernate</code> directory. To find out how to map domain classes with XML, check out the <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html" target="blank">Hibernate manual</a>.<p class="paragraph"/>If the default location of the <code>hibernate.cfg.xml</code> file doesn't suit you, you can change it by specifying an alternative location in <code>grails-app/conf/DataSource.groovy</code>:<p class="paragraph"/><div class="code"><pre>hibernate { |
| config.location = <span class="java-quote">"file:/path/to/my/hibernate.cfg.xml"</span> |
| }</pre></div><p class="paragraph"/>or even a list of locations:<p class="paragraph"/><div class="code"><pre>hibernate { |
| config.location = [<span class="java-quote">"file:/path/to/one/hibernate.cfg.xml"</span>, |
| <span class="java-quote">"file:/path/to/two/hibernate.cfg.xml"</span>] |
| }</pre></div><p class="paragraph"/>Grails also lets you write your domain model in Java or reuse an existing one that already has Hibernate mapping files. Simply place the mapping files into <code>grails-app/conf/hibernate</code> and either put the Java files in <code>src/java</code> or the classes in the project's <code>lib</code> directory if the domain model is packaged as a JAR. You still need the <code>hibernate.cfg.xml</code> though! |
| |
| |
| <a name="17.2 Mapping with Hibernate Annotations"><!-- Legacy link --></a> |
| <h2 id="mappingWithHibernateAnnotations">19.2 Mapping with Hibernate Annotations</h2> |
| To map a domain class with annotations, create a new class in <code>src/java</code> and use the annotations defined as part of the EJB 3.0 spec (for more info on this see the <a href="http://annotations.hibernate.org/" target="blank">Hibernate Annotations Docs</a>):<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> com.books;<p class="paragraph"/><span class="java-keyword">import</span> javax.persistence.Entity; |
| <span class="java-keyword">import</span> javax.persistence.GeneratedValue; |
| <span class="java-keyword">import</span> javax.persistence.Id;<p class="paragraph"/>@Entity |
| <span class="java-keyword">public</span> class Book { |
| <span class="java-keyword">private</span> <span class="java-object">Long</span> id; |
| <span class="java-keyword">private</span> <span class="java-object">String</span> title; |
| <span class="java-keyword">private</span> <span class="java-object">String</span> description; |
| <span class="java-keyword">private</span> Date date;<p class="paragraph"/> @Id |
| @GeneratedValue |
| <span class="java-keyword">public</span> <span class="java-object">Long</span> getId() { |
| <span class="java-keyword">return</span> id; |
| }<p class="paragraph"/> <span class="java-keyword">public</span> void setId(<span class="java-object">Long</span> id) { |
| <span class="java-keyword">this</span>.id = id; |
| }<p class="paragraph"/> <span class="java-keyword">public</span> <span class="java-object">String</span> getTitle() { |
| <span class="java-keyword">return</span> title; |
| }<p class="paragraph"/> <span class="java-keyword">public</span> void setTitle(<span class="java-object">String</span> title) { |
| <span class="java-keyword">this</span>.title = title; |
| }<p class="paragraph"/> <span class="java-keyword">public</span> <span class="java-object">String</span> getDescription() { |
| <span class="java-keyword">return</span> description; |
| }<p class="paragraph"/> <span class="java-keyword">public</span> void setDescription(<span class="java-object">String</span> description) { |
| <span class="java-keyword">this</span>.description = description; |
| } |
| }</pre></div><p class="paragraph"/>Then register the class with the Hibernate <code>sessionFactory</code> by adding relevant entries to the <code>grails-app/conf/hibernate/hibernate.cfg.xml</code> file as follows:<p class="paragraph"/><div class="code"><pre><!DOCTYPE hibernate-configuration SYSTEM |
| <span class="xml-quote">"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"</span>> |
| <span class="xml-tag"><hibernate-configuration></span> |
| <span class="xml-tag"><session-factory></span> |
| <span class="xml-tag"><mapping package=<span class="xml-quote">"com.books"</span> /></span> |
| <span class="xml-tag"><mapping class=<span class="xml-quote">"com.books.Book"</span> /></span> |
| <span class="xml-tag"></session-factory></span> |
| <span class="xml-tag"></hibernate-configuration></span></pre></div> |
| See the previous section for more information on the <code>hibernate.cfg.xml</code> file.<p class="paragraph"/>When Grails loads it will register the necessary dynamic methods with the class. To see what else you can do with a Hibernate domain class see the section on <a href="../guide/single.html#scaffolding" class="guide">Scaffolding</a>. |
| |
| |
| <a name="17.3 Adding Constraints"><!-- Legacy link --></a> |
| <h2 id="addingConstraints">19.3 Adding Constraints</h2> |
| You can still use GORM validation even if you use a Java domain model. Grails lets you define constraints through separate scripts in the <code>src/java</code> directory. The script must be in a directory that matches the package of the corresponding domain class and its name must have a <em class="italic">Constraints</em> suffix. For example, if you had a domain class <code>org.example.Book</code>, then you would create the script <code>src/java/org/example/BookConstraints.groovy</code>.<p class="paragraph"/>Add a standard GORM <code>constraints</code> block to the script: |
| <div class="code"><pre>constraints = { |
| title blank: <span class="java-keyword">false</span> |
| author blank: <span class="java-keyword">false</span> |
| }</pre></div><p class="paragraph"/>Once this is in place you can validate instances of your domain class! |
| |
| |
| <a name="18. Scaffolding"><!-- Legacy link --></a> |
| <h1 id="scaffolding">20 Scaffolding</h1> |
| Scaffolding lets you generate some basic CRUD interfaces for a domain class, including: |
| <ul class="star"> |
| <li>The necessary <a href="../guide/single.html#gsp" class="guide">views</a></li> |
| <li>Controller actions for create/read/update/delete (CRUD) operations</li> |
| </ul><p class="paragraph"/>As of Grails 2.3, the scaffolding feature has been moved to a plugin. By default this is configured for installation in new applications, but if you are upgrading from a previous version of Grails you will need to add the following configuration to your <code>BuildConfig.groovy</code> file:<p class="paragraph"/><div class="code"><pre>plugins { |
| … |
| compile <span class="java-quote">":scaffolding:2.0.0"</span> |
| … |
| }</pre></div><p class="paragraph"/>Version 1.0.0 of the plugin provides the same scaffolding seen in Grails 2.2.x and below. Version 2.0.x of the scaffolding plugin includes different scaffolding templates that are aligned with the new REST APIs introduced in Grails 2.3 and above.<p class="paragraph"/><h4>Dynamic Scaffolding</h4><p class="paragraph"/>The simplest way to get started with scaffolding is to enable it with the <code>scaffold</code> property. Set the <code>scaffold</code> property in the controller to <code>true</code> for the <code>Book</code> domain class:<p class="paragraph"/><div class="code"><pre>class BookController { |
| <span class="java-keyword">static</span> scaffold = <span class="java-keyword">true</span> |
| }</pre></div><p class="paragraph"/>This works because the <code>BookController</code> follows the same naming convention as the <code>Book</code> domain class. To scaffold a specific domain class we could reference the class directly in the scaffold property:<p class="paragraph"/><div class="code"><pre>class SomeController { |
| <span class="java-keyword">static</span> scaffold = Author |
| }</pre></div><p class="paragraph"/>With this configured, when you start your application the actions and views will be auto-generated at runtime. The following actions are dynamically implemented by default by the runtime scaffolding mechanism: |
| <ul class="star"> |
| <li>index</li> |
| <li>show</li> |
| <li>edit</li> |
| <li>delete</li> |
| <li>create</li> |
| <li>save</li> |
| <li>update</li> |
| </ul><p class="paragraph"/>A CRUD interface will also be generated. To access this open <code>http://localhost:8080/app/book</code> in a browser.<p class="paragraph"/>If you prefer to keep your domain model in Java and <a href="../guide/single.html#hibernate" class="guide">mapped with Hibernate</a> you can still use scaffolding, simply import the domain class and set its name as the <code>scaffold</code> argument.<p class="paragraph"/>You can add new actions to a scaffolded controller, for example:<p class="paragraph"/><div class="code"><pre>class BookController {<p class="paragraph"/> <span class="java-keyword">static</span> scaffold = Book<p class="paragraph"/> def changeAuthor() { |
| def b = Book.get(params.id) |
| b.author = Author.get(params[<span class="java-quote">"author.id"</span>]) |
| b.save()<p class="paragraph"/> // redirect to a scaffolded action |
| redirect(action:show) |
| } |
| }</pre></div><p class="paragraph"/>You can also override the scaffolded actions:<p class="paragraph"/><div class="code"><pre>class BookController {<p class="paragraph"/> <span class="java-keyword">static</span> scaffold = Book<p class="paragraph"/> // overrides scaffolded action to <span class="java-keyword">return</span> both authors and books |
| def index() { |
| [bookInstanceList: Book.list(), |
| bookInstanceTotal: Book.count(), |
| authorInstanceList: Author.list()] |
| }<p class="paragraph"/> def show() { |
| def book = Book.get(params.id) |
| log.error(book) |
| [bookInstance : book] |
| } |
| }</pre></div><p class="paragraph"/>All of this is what is known as "dynamic scaffolding" where the CRUD interface is generated dynamically at runtime.<p class="paragraph"/><blockquote class="note"> |
| By default, the size of text areas in scaffolded views is defined in the CSS, so adding 'rows' and 'cols' attributes will have no effect.<p class="paragraph"/>Also, the standard scaffold views expect model variables of the form <code><propertyName>InstanceList</code> for collections and <code><propertyName>Instance</code> for single instances. It's tempting to use properties like 'books' and 'book', but those won't work. |
| </blockquote><p class="paragraph"/><h4>Customizing the Generated Views</h4><p class="paragraph"/>The views adapt to <a href="../guide/single.html#constraints" class="guide">Validation constraints</a>. For example you can change the order that fields appear in the views simply by re-ordering the constraints in the builder:<p class="paragraph"/><div class="code"><pre>def constraints = { |
| title() |
| releaseDate() |
| }</pre></div><p class="paragraph"/>You can also get the generator to generate lists instead of text inputs if you use the <code>inList</code> constraint:<p class="paragraph"/><div class="code"><pre>def constraints = { |
| title() |
| category(inList: [<span class="java-quote">"Fiction"</span>, <span class="java-quote">"Non-fiction"</span>, <span class="java-quote">"Biography"</span>]) |
| releaseDate() |
| }</pre></div><p class="paragraph"/>Or if you use the <code>range</code> constraint on a number:<p class="paragraph"/><div class="code"><pre>def constraints = { |
| age(range:18..65) |
| }</pre></div><p class="paragraph"/>Restricting the size with a constraint also effects how many characters can be entered in the generated view:<p class="paragraph"/><div class="code"><pre>def constraints = { |
| name(size:0..30) |
| }</pre></div><p class="paragraph"/><h4>Static Scaffolding</h4><p class="paragraph"/>Grails also supports "static" scaffolding.<p class="paragraph"/>The above scaffolding features are useful but in real world situations it's likely that you will want to customize the logic and views. Grails lets you generate a controller and the views used to create the above interface from the command line. To generate a controller type:<p class="paragraph"/><div class="code"><pre>grails generate-controller Book</pre></div><p class="paragraph"/>or to generate the views:<p class="paragraph"/><div class="code"><pre>grails generate-views Book</pre></div><p class="paragraph"/>or to generate everything:<p class="paragraph"/><div class="code"><pre>grails generate-all Book</pre></div><p class="paragraph"/>If you have a domain class in a package or are generating from a <a href="../guide/single.html#hibernate" class="guide">Hibernate mapped class</a> remember to include the fully qualified package name:<p class="paragraph"/><div class="code"><pre>grails generate-all com.bookstore.Book</pre></div><p class="paragraph"/><h4>Customizing the Scaffolding templates</h4><p class="paragraph"/>The templates used by Grails to generate the controller and views can be customized by installing the templates with the commandLine command. |
| |
| |
| <a name="19. Deployment"><!-- Legacy link --></a> |
| <h1 id="deployment">21 Deployment</h1> |
| Grails applications can be deployed in a number of ways, each of which has its pros and cons.<p class="paragraph"/><h3>"grails run-app"</h3><p class="paragraph"/>You should be very familiar with this approach by now, since it is the most common method of running an application during the development phase. An embedded Tomcat server is launched that loads the web application from the development sources, thus allowing it to pick up an changes to application files.<p class="paragraph"/>This approach is not recommended at all for production deployment because the performance is poor. Checking for and loading changes places a sizable overhead on the server. Having said that, <code>grails prod run-app</code> removes the per-request overhead and lets you fine tune how frequently the regular check takes place.<p class="paragraph"/>Setting the system property "disable.auto.recompile" to <code>true</code> disables this regular check completely, while the property "recompile.frequency" controls the frequency. This latter property should be set to the number of seconds you want between each check. The default is currently 3.<p class="paragraph"/><h3>"grails run-war"</h3><p class="paragraph"/>This is very similar to the previous option, but Tomcat runs against the packaged WAR file rather than the development sources. Hot-reloading is disabled, so you get good performance without the hassle of having to deploy the WAR file elsewhere.<p class="paragraph"/><h3>WAR file</h3><p class="paragraph"/>When it comes down to it, current java infrastructures almost mandate that web applications are deployed as WAR files, so this is by far the most common approach to Grails application deployment in production. Creating a WAR file is as simple as executing the <a href="../ref/Command Line/war.html" class="commandLine">war</a> command:<p class="paragraph"/><div class="code"><pre>grails war</pre></div><p class="paragraph"/>There are also many ways in which you can customise the WAR file that is created. For example, you can specify a path (either absolute or relative) to the command that instructs it where to place the file and what name to give it:<p class="paragraph"/><div class="code"><pre>grails war /opt/java/tomcat-5.5.24/foobar.war</pre></div><p class="paragraph"/>Alternatively, you can add a line to <code>grails-app/conf/BuildConfig.groovy</code> that changes the default location and filename:<p class="paragraph"/><div class="code"><pre>grails.project.war.file = <span class="java-quote">"foobar-prod.war"</span></pre></div><p class="paragraph"/>Any command line argument that you provide overrides this setting.<p class="paragraph"/>It is also possible to control what libraries are included in the WAR file, for example to avoid conflicts with libraries in a shared directory. The default behavior is to include in the WAR file all libraries required by Grails, plus any libraries contained in plugin "lib" directories, plus any libraries contained in the application's "lib" directory. As an alternative to the default behavior you can explicitly specify the complete list of libraries to include in the WAR file by setting the property <code>grails.war.dependencies</code> in BuildConfig.groovy to either lists of Ant include patterns or closures containing AntBuilder syntax. Closures are invoked from within an Ant "copy" step, so only elements like "fileset" can be included, whereas each item in a pattern list is included. Any closure or pattern assigned to the latter property will be included in addition to <code>grails.war.dependencies</code>.<p class="paragraph"/>Be careful with these properties: if any of the libraries Grails depends on are missing, the application will almost certainly fail. Here is an example that includes a small subset of the standard Grails dependencies:<p class="paragraph"/><div class="code"><pre>def deps = [ |
| <span class="java-quote">"hibernate3.jar"</span>, |
| <span class="java-quote">"groovy-all-*.jar"</span>, |
| <span class="java-quote">"standard-${servletVersion}.jar"</span>, |
| <span class="java-quote">"jstl-${servletVersion}.jar"</span>, |
| <span class="java-quote">"oscache-*.jar"</span>, |
| <span class="java-quote">"commons-logging-*.jar"</span>, |
| <span class="java-quote">"sitemesh-*.jar"</span>, |
| <span class="java-quote">"spring-*.jar"</span>, |
| <span class="java-quote">"log4j-*.jar"</span>, |
| <span class="java-quote">"ognl-*.jar"</span>, |
| <span class="java-quote">"commons-*.jar"</span>, |
| <span class="java-quote">"xstream-1.2.1.jar"</span>, |
| <span class="java-quote">"xpp3_min-1.1.3.4.O.jar"</span> ]<p class="paragraph"/>grails.war.dependencies = { |
| fileset(dir: <span class="java-quote">"libs"</span>) { |
| <span class="java-keyword">for</span> (pattern in deps) { |
| include(name: pattern) |
| } |
| } |
| }</pre></div><p class="paragraph"/>This example only exists to demonstrate the syntax for the properties. If you attempt to use it as is in your own application, the application will probably not work. You can find a list of dependencies required by Grails in the "dependencies.txt" file in the root directory of the unpacked distribution. You can also find a list of the default dependencies included in WAR generation in the "War.groovy" script - see the <code>DEFAULT_DEPS</code> and <code>DEFAULT_J5_DEPS</code> variables.<p class="paragraph"/>The remaining two configuration options available to you are <code>grails.war.copyToWebApp</code> and <code>grails.war.resources</code>. The first of these lets you customise what files are included in the WAR file from the "web-app" directory. The second lets you do any extra processing you want before the WAR file is finally created.<p class="paragraph"/><div class="code"><pre>// This closure is passed the command line arguments used to start the |
| // war process. |
| grails.war.copyToWebApp = { args -> |
| fileset(dir:<span class="java-quote">"web-app"</span>) { |
| include(name: <span class="java-quote">"js/**"</span>) |
| include(name: <span class="java-quote">"css/**"</span>) |
| include(name: <span class="java-quote">"WEB-INF/**"</span>) |
| } |
| }<p class="paragraph"/>// This closure is passed the location of the staging directory that |
| // is zipped up to make the WAR file, and the command line arguments. |
| // Here we override the standard web.xml with our own. |
| grails.war.resources = { stagingDir, args -> |
| copy(file: <span class="java-quote">"grails-app/conf/custom-web.xml"</span>, |
| tofile: <span class="java-quote">"${stagingDir}/WEB-INF/web.xml"</span>) |
| }</pre></div><p class="paragraph"/><h2>Application servers</h2><p class="paragraph"/>Ideally you should be able to simply drop a WAR file created by Grails into any application server and it should work straight away. However, things are rarely ever this simple. The <a href="http://grails.org/Deployment" target="blank">Grails website</a> contains a list of application servers that Grails has been tested with, along with any additional steps required to get a Grails WAR file working. |
| |
| |
| |
| <h1 id="contributing">22 Contributing to Grails</h1> |
| Grails is an open source project with an active community and we rely heavily on that community to help make Grails better. As such, there are various ways in which people can contribute to Grails. One of these is by <a href="../guide/single.html#plugins" class="guide">writing useful plugins</a> and making them publicly available. In this chapter, we'll look at some of the other options. |
| |
| |
| |
| <h2 id="issues">22.1 Report Issues in JIRA</h2> |
| Grails uses <a href="http://jira.grails.org" target="blank">JIRA</a> to track issues in the core framework, its documentation, its website, and many of the public plugins. If you've found a bug or wish to see a particular feature added, this is the place to start. You'll need to create a (free) JIRA account in order to either submit an issue or comment on an existing one.<p class="paragraph"/>When submitting issues, please provide as much information as possible and in the case of bugs, make sure you explain which versions of Grails and various plugins you are using. Also, an issue is much more likely to be dealt with if you attach a reproducible sample application (which can be packaged up using the <code>grails bug-report</code> command).<p class="paragraph"/><h3>Reviewing issues</h3><p class="paragraph"/>There are quite a few old issues in JIRA, some of which may no longer be valid. The core team can't track down these alone, so a very simple contribution that you can make is to verify one or two issues occasionally.<p class="paragraph"/>Which issues need verification? A shared <a href="http://jira.grails.org/secure/IssueNavigator.jspa?reset=true&jqlQuery=project+%3D+GRAILS+AND+resolution+%3D+Unresolved+AND+%28cf%5B10310%5D+%3C%3D+%27-180d%27+OR+cf%5B10310%5D+is+EMPTY%29+AND+createdDate+%3C%3D+%27-180d%27" target="blank">JIRA filter</a> will display all issues that haven't been resolved and haven't been reviewed by someone else in the last 6 months. Just pick one or two of them and check whether they are still relevant.<p class="paragraph"/>Once you've verified an issue, simply edit it and set the "Last Reviewed" field to today. If you think the issue can be closed, then also check the "Flagged" field and add a short comment explaining why. Once those changes are saved, the issue will disappear from the results of the above filter. If you've flagged it, the core team will review and close if it really is no longer relevant.<p class="paragraph"/>One last thing: you can easily set the above filter as a favourite on <a href="http://jira.grails.org/secure/ManageFilters.jspa#filterView=popular" target="blank">this JIRA screen</a> so that it appears in the "Issues" drop down. Just click on the star next to a filter to make it a favourite. |
| |
| |
| |
| <h2 id="build">22.2 Build From Source and Run Tests</h2> |
| If you're interested in contributing fixes and features to the core framework, you will have to learn how to get hold of the project's source, build it and test it with your own applications. Before you start, make sure you have: |
| <ul class="star"> |
| <li>A JDK (1.6 or above)</li> |
| <li>A git client</li> |
| </ul><p class="paragraph"/>Once you have all the pre-requisite packages installed, the next step is to download the Grails source code, which is hosted at <a href="http://github.com" target="blank">GitHub</a> in several repositories owned by the <a href="http://github.com/grails" target="blank">"grails" GitHub user</a>. This is a simple case of cloning the repository you're interested in. For example, to get the core framework run:<p class="paragraph"/><div class="code"><pre>git clone http://github.com/grails/grails-core.git</pre></div><p class="paragraph"/>This will create a "grails-core" directory in your current working directory containing all the project source files. The next step is to get a Grails installation from the source.<p class="paragraph"/><h3>Creating a Grails installation</h3><p class="paragraph"/>If you look at the project structure, you'll see that it doesn't look much like a standard <code>GRAILS_HOME</code> installation. But, it's very simple to turn it into one. Just run this from the root directory of the project:<p class="paragraph"/><div class="code"><pre>./gradlew install</pre></div><p class="paragraph"/>This will fetch all the standard dependencies required by Grails and then build a <code>GRAILS_HOME</code> installation. Note that this target skips the extensive collection of Grails test classes, which can take some time to complete.<p class="paragraph"/>Once the above command has finished, simply set the <code>GRAILS_HOME</code> environment variable to the checkout directory and add the "bin" directory to your path. When you next type run the <code>grails</code> command, you'll be using the version you just built.<p class="paragraph"/><h3>Running the test suite</h3><p class="paragraph"/>All you have to do to run the full suite of tests is:<p class="paragraph"/><div class="code"><pre>./gradlew test</pre></div><p class="paragraph"/>These will take a while (15-30 mins), so consider running individual tests using the command line. For example, to run the test spec <code>BinaryPluginSpec</code> simply execute the following command: |
| <div class="code"><pre>./gradlew :grails-core:test --tests *.BinaryPluginSpec</pre></div><p class="paragraph"/>Note that you need to specify the sub-project that the test case resides in, because the top-level "test" target won't work....<p class="paragraph"/><h3>Developing in IntelliJ IDEA</h3><p class="paragraph"/>You need to run the following gradle task: |
| <div class="code"><pre>./gradlew idea</pre></div><p class="paragraph"/>Then open the project file which is generated in IDEA. Simple!<p class="paragraph"/><h3>Developing in STS / Eclipse</h3><p class="paragraph"/>You need to run the following gradle task: |
| <div class="code"><pre>./gradlew cleanEclipse eclipse</pre></div><p class="paragraph"/>Before importing projects to STS do the following action: |
| <ul class="star"> |
| <li>Edit grails-scripts/.classpath and remove the line "<classpathentry kind="src" path="../scripts"/>".</li> |
| </ul><p class="paragraph"/>Use "Import->General->Existing Projects into Workspace" to import all projects to STS. There will be a few build errors. To fix them do the following: |
| <ul class="star"> |
| <li>Add the springloaded-core JAR file in $GRAILS_HOME/lib/org.springsource.springloaded/springloaded-core/jars to grails-core's classpath.</li> |
| <li>Remove "src/test/groovy" from grails-plugin-testing's source path GRECLIPSE-1067</li> |
| <li>Add the jsp-api JAR file in $GRAILS_HOME/lib/javax.servlet.jsp/jsp-api/jars to the classpath of grails-web</li> |
| <li>Fix the source path of grails-scripts. Add linked source folder linking to "../scripts". If you get build errors in grails-scripts, do "../gradlew cleanEclipse eclipse" in that directory and edit the .classpath file again (remove the line "<classpathentry kind="src" path="../scripts"/>"). Remove possible empty "scripts" directory under grails-scripts if you are not able to add the linked folder.</li> |
| <li>Do a clean build for the whole workspace.</li> |
| <li>To use Eclipse GIT scm team provider: Select all projects (except "Servers") in the navigation and right click -> Team -> Share project (not "Share projects"). Choose "Git". Then check "Use or create repository in parent folder of project" and click "Finish".</li> |
| <li>Get the recommended code style settings from the <a href="http://grails.1312388.n4.nabble.com/Grails-development-code-style-IDE-formatting-settings-tp3854216p3854216.html" target="blank">mailing list thread</a> (final style not decided yet, currently <a href="http://grails.1312388.n4.nabble.com/attachment/3854262/0/profile.xml" target="blank">profile.xml</a>). Import the code style xml file to STS in Window->Preferences->Java->Code Style->Formatter->Import . Grails code uses spaces instead of tabs for indenting.</li> |
| </ul><p class="paragraph"/><h3>Debugging Grails or a Grails application</h3><p class="paragraph"/>To enable debugging, run: |
| <div class="code"><pre>grails --debug-fork run-app</pre></div><p class="paragraph"/>By default Grails forks a JVM to run the application in. The <code>--debug-fork</code> argument causes the debugger to be associated with the forked JVM. In order to instead attach the debugger to the build system which is going to fork the JVM use the <code>-debug</code> option:<p class="paragraph"/><div class="code"><pre>grails -debug run-app</pre></div> |
| |
| |
| |
| <h2 id="patchesCore">22.3 Submit Patches to Grails Core</h2> |
| If you want to submit patches to the project, you simply need to fork the repository on GitHub rather than clone it directly. Then you will commit your changes to your fork and send a pull request for a core team member to review.<p class="paragraph"/><h3>Forking and Pull Requests</h3> |
| One of the benefits of <a href="http://github.com" target="blank">GitHub</a> is the way that you can easily contribute to a project by <a href="http://help.github.com/fork-a-repo/" target="blank">forking the repository</a> and <a href="http://help.github.com/send-pull-requests/" target="blank">sending pull requests</a> with your changes.<p class="paragraph"/>What follows are some guidelines to help ensure that your pull requests are speedily dealt with and provide the information we need. They will also make your life easier!<p class="paragraph"/><h4>Create a local branch for your changes</h4><p class="paragraph"/>Your life will be greatly simplified if you create a local branch to make your changes on. For example, as soon as you fork a repository and clone the fork locally, execute |
| <div class="code"><pre>git checkout -b mine</pre></div><p class="paragraph"/>This will create a new local branch called "mine" based off the "master" branch. Of course, you can name the branch whatever you like - you don't have to use "mine".<p class="paragraph"/><h4>Create JIRAs for non-trivial changes</h4><p class="paragraph"/>For any non-trivial changes, raise a JIRA issue if one doesn't already exist. That helps us keep track of what changes go into each new version of Grails.<p class="paragraph"/><h4>Include JIRA issue ID in commit messages</h4><p class="paragraph"/>This may not seem particularly important, but having a JIRA issue ID in a commit message means that we can find out at a later date why a change was made. Include the ID in any and all commits that relate to that issue. If a commit isn't related to an issue, then there's no need to include an issue ID.<p class="paragraph"/><h4>Make sure your fork is up to date</h4><p class="paragraph"/>Since the core developers must merge your commits into the main repository, it makes life much easier if your fork on GitHub is up to date before you send a pull request.<p class="paragraph"/>Let's say you have the main repository set up as a remote called "upstream" and you want to submit a pull request. Also, all your changes are currently on the local "mine" branch but not on "master". The first step involves pulling any changes from the main repository that have been added since you last fetched and merged: |
| <div class="code"><pre>git checkout master |
| git pull upstream</pre></div><p class="paragraph"/>This should complete without any problems or conflicts. Next, rebase your local branch against the now up-to-date master: |
| <div class="code"><pre>git checkout mine |
| git rebase master</pre></div><p class="paragraph"/>What this does is rearrange the commits such that all of your changes come after the most recent one in master. Think adding some cards to the top of a deck rather than shuffling them into the pack.<p class="paragraph"/>You'll now be able to do a clean merge from your local branch to master: |
| <div class="code"><pre>git checkout master |
| git merge mine</pre></div><p class="paragraph"/>Finally, you must push your changes to your remote repository on GitHub, otherwise the core developers won't be able to pick them up: |
| <div class="code"><pre>git push</pre></div><p class="paragraph"/>You're now ready to send the pull request from the GitHub user interface.<p class="paragraph"/><h4>Say what your pull request is for</h4><p class="paragraph"/>A pull request can contain any number of commits and it may be related to any number of issues. In the pull request message, please specify the IDs of all issues that the request relates to. Also give a brief description of the work you have done, such as: "I refactored the data binder and added support for custom number editors (GRAILS-xxxx)". |
| |
| |
| <h2 id="patchesDoc">22.4 Submit Patches to Grails Documentation</h2> |
| Contributing to the documentation is simpler for the core framework because there is a public fork of the <a href="http://github.com/grails/grails-doc" target="blank">http://github.com/grails/grails-doc</a> project that anyone can request commit access to. So, if you want to submit patches to the documentation, simply request commit access to the following repository <a href="http://github.com/pledbrook/grails-doc" target="blank">http://github.com/pledbrook/grails-doc</a> by sending a GitHub message to 'pledbrook' and then commit your patches just as you would to any other GitHub repository.<p class="paragraph"/><h3>Building the Guide</h3><p class="paragraph"/>To build the documentation, simply type: |
| <div class="code"><pre>./gradlew docs</pre></div><p class="paragraph"/>Be warned: this command can take a while to complete and you should probably increase your Gradle memory settings by giving the <code>GRADLE_OPTS</code> environment variable a value like |
| <div class="code"><pre>export GRADLE_OPTS=<span class="java-quote">"-Xmx512m -XX:MaxPermSize=384m"</span></pre></div><p class="paragraph"/>Fortunately, you can reduce the overall build time with a couple of useful options. The first allows you to specify the location of the Grails source to use:<p class="paragraph"/><div class="code"><pre>./gradlew -Dgrails.home=/home/user/projects/grails-core docs</pre></div><p class="paragraph"/>The Grails source is required because the guide links to its API documentation and the build needs to ensure it's generated. If you don't specify a <code>grails.home</code> property, then the build will fetch the Grails source - a download of 10s of megabytes. It must then compile the Grails source which can take a while too.<p class="paragraph"/>Additionally you can create a local.properties file with this variable set: |
| <div class="code"><pre>grails.home=/home/user/projects/grails-core</pre></div> |
| or |
| <div class="code"><pre>grails.home=../grails-core</pre></div><p class="paragraph"/>The other useful option allows you to disable the generation of the API documentation, since you only need to do it once: |
| <div class="code"><pre>./gradlew -Ddisable.groovydocs=<span class="java-keyword">true</span> docs</pre></div><p class="paragraph"/>Again, this can save a significant amount of time and memory.<p class="paragraph"/>The main English user guide is generated in the <code>build/docs</code> directory, with the <code>guide</code> sub-directory containing the user guide part and the <code>ref</code> folder containing the reference material. To view the user guide, simply open <code>build/docs/index.html</code>.<p class="paragraph"/><h3>Publishing</h3><p class="paragraph"/>The publishing system for the user guide is the same as <a href="http://grails.org/doc/2.0.0.M1/guide/conf.html#docengine" target="blank">the one for Grails projects</a>. You write your chapters and sections in the gdoc wiki format which is then converted to HTML for the final guide. Each chapter is a top-level gdoc file in the <code>src/<lang>/guide</code> directory. Sections and sub-sections then go into directories with the same name as the chapter gdoc but without the suffix.<p class="paragraph"/>The structure of the user guide is defined in the <code>src/<lang>/guide/toc.yml</code> file, which is a YAML file. This file also defines the (language-specific) section titles. If you add or remove a gdoc file, you must update the TOC as well!<p class="paragraph"/>The <code>src/<lang>/ref</code> directory contains the source for the reference sidebar. Each directory is the name of a category, which also appears in the docs. Hence the directories need different names for the different languages. Inside the directories go the gdoc files, whose names match the names of the methods, commands, properties or whatever that the files describe.<p class="paragraph"/><h3>Translations</h3><p class="paragraph"/>This project can host multiple translations of the user guide, with <code>src/en</code> being the main one. To add another one, simply create a new language directory under <code>src</code> and copy into it all the files under <code>src/en</code>. The build will take care of the rest.<p class="paragraph"/>Once you have a copy of the original guide, you can use the <code>{hidden}</code> macro to wrap the English text that you have replaced, rather than remove it. This makes it easier to compare changes to the English guide against your translation. For example: |
| <div class="code"><pre>{hidden} |
| When you create a Grails application with the [create-app|commandLine] command, |
| Grails doesn't automatically create an Ant <code>build.xml</code> file but you can generate |
| one with the [integrate-with|commandLine] command: |
| {hidden}<p class="paragraph"/>Quando crias uma aplicação Grails com o comando [create-app|commandLine], Grails |
| não cria automaticamente um ficheiro de construção Ant <code>build.xml</code> mas podes gerar |
| um com o comando [integrate-with|commandLine]:</pre></div><p class="paragraph"/>Because the English text remains in your gdoc files, <code>diff</code> will show differences on the English lines. You can then use the output of <code>diff</code> to see which bits of your translation need updating. On top of that, the <code>{hidden}</code> macro ensures that the text inside it is not displayed in the browser, although you can display it by adding this URL as a bookmark: <code>javascript:toggleHidden();</code> (requires you to build the user guide with Grails 2.0 M2 or later).<p class="paragraph"/>Even better, you can use the <code>left_to_do.groovy</code> script in the root of the project to see what still needs translating. You run it like so: |
| <div class="code"><pre>./left_to_do.groovy es</pre></div><p class="paragraph"/>This will then print out a recursive diff of the given translation against the reference English user guide. Anything in <code>{hidden}</code> blocks that hasn't changed since being translated will <em class="italic">not</em> appear in the diff output. In other words, all you will see is content that hasn't been translated yet and content that has changed since it was translated. Note that <code>{code}</code> blocks are ignored, so you <em class="italic">don't</em> need to include them inside <code>{hidden}</code> macros.<p class="paragraph"/>To provide translations for the headers, such as the user guide title and subtitle, just add language specific entries in the 'resources/doc.properties' file like so: |
| <div class="code"><pre>es.title=El Grails Framework |
| es.subtitle=...</pre></div><p class="paragraph"/>For each language translation, properties beginning <code><lang></code>. will override the standard ones. In the above example, the user guide title will be El Grails Framework for the Spanish translation. Also, translators can be credited by adding a '<lang>.translators' property: |
| <div class="code"><pre>fr.translators=Stéphane Maldini</pre></div><p class="paragraph"/>This should be a comma-separated list of names (or the native language equivalent) and it will be displayed as a "Translated by" header in the user guide itself.<p class="paragraph"/>You can build specific translations very easily using the <code>publishGuide_*</code> and <code>publishPdf_*</code> tasks. For example, to build both the French HTML and PDF user guides, simply execute |
| <div class="code"><pre>./gradlew publishPdf_fr</pre></div><p class="paragraph"/>Each translation is generated in its own directory, so for example the French guide will end up in <code>build/docs/fr</code>. You can then view the translated guide by opening <code>build/docs/<lang>/index.html</code>.<p class="paragraph"/>All translations are created as part of the <a href="http://hudson.grails.org/job/grails_docs_2.0.x/lastSuccessfulBuild/artifact/build/docs/" target="blank">Hudson CI build for the grails-doc</a> project, so you can easily see what the current state is without having to build the docs yourself. |
| |
| |
| </div> |
| </td> |
| <td id="col2"> |
| <div class="local clearfix"> |
| <div class="local-title"> |
| <a href="../guide/index.html" target="mainFrame">Quick Reference</a> |
| <span class="toggle">(<a href="#" onclick="localToggle(); return false;">hide</a>)</span> |
| </div> |
| <div class="menu"> |
| |
| <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Command Line</h1><div class="menu-sub"> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/Usage.html">Usage</a></div> |
| |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/alias.html">alias</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/bug-report.html">bug-report</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/clean.html">clean</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/compile.html">compile</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/console.html">console</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/create-app.html">create-app</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/create-command.html">create-command</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/create-controller.html">create-controller</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/create-domain-class.html">create-domain-class</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/create-functional-test.html">create-functional-test</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/create-integration-test.html">create-integration-test</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/create-interceptor.html">create-interceptor</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/create-plugin.html">create-plugin</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/create-script.html">create-script</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/create-service.html">create-service</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/create-tag-lib.html">create-tag-lib</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/create-unit-test.html">create-unit-test</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/dependency-report.html">dependency-report</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/doc.html">doc</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/generate-all.html">generate-all</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/generate-controller.html">generate-controller</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/generate-views.html">generate-views</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/help.html">help</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/list-plugins.html">list-plugins</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/package-plugin.html">package-plugin</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/package.html">package</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/plugin-info.html">plugin-info</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/run-app.html">run-app</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/schema-export.html">schema-export</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/shell.html">shell</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/stats.html">stats</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/test-app.html">test-app</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Command%20Line/war.html">war</a> |
| </div> |
| |
| </div> |
| </div> |
| |
| <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Constraints</h1><div class="menu-sub"> |
| |
| <div class="menu-item"><a href="../ref/Constraints/Usage.html">Usage</a></div> |
| |
| |
| <div class="menu-item"><a href="../ref/Constraints/attributes.html">attributes</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Constraints/bindable.html">bindable</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Constraints/blank.html">blank</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Constraints/creditCard.html">creditCard</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Constraints/email.html">email</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Constraints/inList.html">inList</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Constraints/matches.html">matches</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Constraints/max.html">max</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Constraints/maxSize.html">maxSize</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Constraints/min.html">min</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Constraints/minSize.html">minSize</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Constraints/notEqual.html">notEqual</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Constraints/nullable.html">nullable</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Constraints/range.html">range</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Constraints/scale.html">scale</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Constraints/size.html">size</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Constraints/unique.html">unique</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Constraints/url.html">url</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Constraints/validator.html">validator</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Constraints/widget.html">widget</a> |
| </div> |
| |
| </div> |
| </div> |
| |
| <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Controllers</h1><div class="menu-sub"> |
| |
| <div class="menu-item"><a href="../ref/Controllers/Usage.html">Usage</a></div> |
| |
| |
| <div class="menu-item"><a href="../ref/Controllers/actionName.html">actionName</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/afterInterceptor.html">afterInterceptor</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/allowedMethods.html">allowedMethods</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/beforeInterceptor.html">beforeInterceptor</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/bindData.html">bindData</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/chain.html">chain</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/controllerName.html">controllerName</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/defaultAction.html">defaultAction</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/errors.html">errors</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/flash.html">flash</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/forward.html">forward</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/grailsApplication.html">grailsApplication</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/hasErrors.html">hasErrors</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/namespace.html">namespace</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/params.html">params</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/redirect.html">redirect</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/render.html">render</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/request.html">request</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/respond.html">respond</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/response.html">response</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/responseFormats.html">responseFormats</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/scope.html">scope</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/servletContext.html">servletContext</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/session.html">session</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/withForm.html">withForm</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Controllers/withFormat.html">withFormat</a> |
| </div> |
| |
| </div> |
| </div> |
| |
| <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Database Mapping</h1><div class="menu-sub"> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/Usage.html">Usage</a></div> |
| |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/autoImport.html">autoImport</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/autoTimestamp.html">autoTimestamp</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/batchSize.html">batchSize</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/cache.html">cache</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/cascade.html">cascade</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/column.html">column</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/comment.html">comment</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/discriminator.html">discriminator</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/dynamicInsert.html">dynamicInsert</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/dynamicUpdate.html">dynamicUpdate</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/fetch.html">fetch</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/id.html">id</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/ignoreNotFound.html">ignoreNotFound</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/indexColumn.html">indexColumn</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/insertable.html">insertable</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/joinTable.html">joinTable</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/lazy.html">lazy</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/order.html">order</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/sort.html">sort</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/table.html">table</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/type.html">type</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/updateable.html">updateable</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Database%20Mapping/version.html">version</a> |
| </div> |
| |
| </div> |
| </div> |
| |
| <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Domain Classes</h1><div class="menu-sub"> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/Usage.html">Usage</a></div> |
| |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/addTo.html">addTo</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/attach.html">attach</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/belongsTo.html">belongsTo</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/clearErrors.html">clearErrors</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/constraints.html">constraints</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/count.html">count</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/countBy.html">countBy</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/createCriteria.html">createCriteria</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/delete.html">delete</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/discard.html">discard</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/embedded.html">embedded</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/errors.html">errors</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/executeQuery.html">executeQuery</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/executeUpdate.html">executeUpdate</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/exists.html">exists</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/fetchMode.html">fetchMode</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/find.html">find</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/findAll.html">findAll</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/findAllBy.html">findAllBy</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/findAllWhere.html">findAllWhere</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/findBy.html">findBy</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/findOrCreateBy.html">findOrCreateBy</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/findOrCreateWhere.html">findOrCreateWhere</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/findOrSaveBy.html">findOrSaveBy</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/findOrSaveWhere.html">findOrSaveWhere</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/findWhere.html">findWhere</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/first.html">first</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/get.html">get</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/getAll.html">getAll</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/getDirtyPropertyNames.html">getDirtyPropertyNames</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/getPersistentValue.html">getPersistentValue</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/hasErrors.html">hasErrors</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/hasMany.html">hasMany</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/hasOne.html">hasOne</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/ident.html">ident</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/instanceOf.html">instanceOf</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/isAttached.html">isAttached</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/isDirty.html">isDirty</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/last.html">last</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/list.html">list</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/listOrderBy.html">listOrderBy</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/load.html">load</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/lock.html">lock</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/mapWith.html">mapWith</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/mappedBy.html">mappedBy</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/mapping.html">mapping</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/merge.html">merge</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/namedQueries.html">namedQueries</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/properties.html">properties</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/read.html">read</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/refresh.html">refresh</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/removeFrom.html">removeFrom</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/save.html">save</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/transients.html">transients</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/validate.html">validate</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/where.html">where</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/whereAny.html">whereAny</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/withCriteria.html">withCriteria</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/withNewSession.html">withNewSession</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/withSession.html">withSession</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Domain%20Classes/withTransaction.html">withTransaction</a> |
| </div> |
| |
| </div> |
| </div> |
| |
| <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Plug-ins</h1><div class="menu-sub"> |
| |
| <div class="menu-item"><a href="../ref/Plug-ins/Usage.html">Usage</a></div> |
| |
| |
| <div class="menu-item"><a href="../ref/Plug-ins/URL%20mappings.html">URL mappings</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Plug-ins/codecs.html">codecs</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Plug-ins/controllers.html">controllers</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Plug-ins/core.html">core</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Plug-ins/dataSource.html">dataSource</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Plug-ins/domainClasses.html">domainClasses</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Plug-ins/hibernate.html">hibernate</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Plug-ins/i18n.html">i18n</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Plug-ins/logging.html">logging</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Plug-ins/scaffolding.html">scaffolding</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Plug-ins/services.html">services</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Plug-ins/servlets.html">servlets</a> |
| </div> |
| |
| </div> |
| </div> |
| |
| <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Services</h1><div class="menu-sub"> |
| |
| <div class="menu-item"><a href="../ref/Services/Usage.html">Usage</a></div> |
| |
| |
| <div class="menu-item"><a href="../ref/Services/scope.html">scope</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Services/transactional.html">transactional</a> |
| </div> |
| |
| </div> |
| </div> |
| |
| <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Servlet API</h1><div class="menu-sub"> |
| |
| |
| <div class="menu-item"><a href="../ref/Servlet%20API/request.html">request</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Servlet%20API/response.html">response</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Servlet%20API/servletContext.html">servletContext</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Servlet%20API/session.html">session</a> |
| </div> |
| |
| </div> |
| </div> |
| |
| <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Tag Libraries</h1><div class="menu-sub"> |
| |
| <div class="menu-item"><a href="../ref/Tag%20Libraries/Usage.html">Usage</a></div> |
| |
| |
| <div class="menu-item"><a href="../ref/Tag%20Libraries/actionName.html">actionName</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tag%20Libraries/controllerName.html">controllerName</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tag%20Libraries/flash.html">flash</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tag%20Libraries/pageScope.html">pageScope</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tag%20Libraries/params.html">params</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tag%20Libraries/request.html">request</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tag%20Libraries/response.html">response</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tag%20Libraries/servletContext.html">servletContext</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tag%20Libraries/session.html">session</a> |
| </div> |
| |
| </div> |
| </div> |
| |
| <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Tags</h1><div class="menu-sub"> |
| |
| |
| <div class="menu-item"><a href="../ref/Tags/actionSubmit.html">actionSubmit</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/actionSubmitImage.html">actionSubmitImage</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/applyLayout.html">applyLayout</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/checkBox.html">checkBox</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/collect.html">collect</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/cookie.html">cookie</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/country.html">country</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/countrySelect.html">countrySelect</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/createLink.html">createLink</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/createLinkTo.html">createLinkTo</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/currencySelect.html">currencySelect</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/datePicker.html">datePicker</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/each.html">each</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/eachError.html">eachError</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/else.html">else</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/elseif.html">elseif</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/external.html">external</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/field.html">field</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/fieldValue.html">fieldValue</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/findAll.html">findAll</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/form.html">form</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/formatBoolean.html">formatBoolean</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/formatDate.html">formatDate</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/formatNumber.html">formatNumber</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/grep.html">grep</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/hasErrors.html">hasErrors</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/header.html">header</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/hiddenField.html">hiddenField</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/if.html">if</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/img.html">img</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/include.html">include</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/isAvailable.html">isAvailable</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/isNotAvailable.html">isNotAvailable</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/javascript.html">javascript</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/join.html">join</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/layoutBody.html">layoutBody</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/layoutHead.html">layoutHead</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/layoutTitle.html">layoutTitle</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/link.html">link</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/localeSelect.html">localeSelect</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/message.html">message</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/meta.html">meta</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/pageProperty.html">pageProperty</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/paginate.html">paginate</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/passwordField.html">passwordField</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/radio.html">radio</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/radioGroup.html">radioGroup</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/render.html">render</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/renderErrors.html">renderErrors</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/resource.html">resource</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/select.html">select</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/set.html">set</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/sortableColumn.html">sortableColumn</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/submitButton.html">submitButton</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/textArea.html">textArea</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/textField.html">textField</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/timeZoneSelect.html">timeZoneSelect</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/unless.html">unless</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/uploadForm.html">uploadForm</a> |
| </div> |
| |
| <div class="menu-item"><a href="../ref/Tags/while.html">while</a> |
| </div> |
| |
| </div> |
| </div> |
| |
| </div> |
| </div> |
| </td> |
| </tr> |
| </table> |
| |
| <div id="footer"> |
| Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically. |
| |
| </div> |
| |
| |
| |
| <script type="text/javascript" src="../js/docs.js"></script> |
| |
| </body> |
| </html> |