blob: f6030f1fda5bb1545dc9fb83c0e620def02c1c6f [file]
<!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 2.0.1</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="#conf"><strong>3</strong><span>Configuration</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#commandLine"><strong>4</strong><span>The Command Line</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#GORM"><strong>5</strong><span>Object Relational Mapping (GORM)</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#theWebLayer"><strong>6</strong><span>The Web Layer</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#validation"><strong>7</strong><span>Validation</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#services"><strong>8</strong><span>The Service Layer</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#testing"><strong>9</strong><span>Testing</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#i18n"><strong>10</strong><span>Internationalization</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#security"><strong>11</strong><span>Security</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#plugins"><strong>12</strong><span>Plugins</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#webServices"><strong>13</strong><span>Web Services</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#spring"><strong>14</strong><span>Grails and Spring</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#hibernate"><strong>15</strong><span>Grails and Hibernate</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#scaffolding"><strong>16</strong><span>Scaffolding</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#deployment"><strong>17</strong><span>Deployment</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#contributing"><strong>18</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>
<span id="sponsor"><a href="http://springsource.com" target="_blank"><img alt="SpringSource Logo" title="SpringSource - Weapons for the War on Java Complexity" src="../img/springsource-logo.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</p>
<p><strong>Version:</strong> 2.0.1</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 2.0?</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#developmentEnvironmentFeatures"><strong>1.1.1</strong><span>Development Environment Features</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#coreFeatures"><strong>1.1.2</strong><span>Core Features</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#webFeatures"><strong>1.1.3</strong><span>Web Features</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#persistenceFeatures"><strong>1.1.4</strong><span>Persistence Features</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#testingFeatures"><strong>1.1.5</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="#upgradingFromPreviousVersionsOfGrails"><strong>2.3</strong><span>Upgrading from previous versions of Grails</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#creatingAnApplication"><strong>2.4</strong><span>Creating an Application</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#aHelloWorldExample"><strong>2.5</strong><span>A Hello World Example</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#usingInteractiveMode"><strong>2.6</strong><span>Using Interactive Mode</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#ide"><strong>2.7</strong><span>Getting Set Up in an IDE</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#conventionOverConfiguration"><strong>2.8</strong><span>Convention over Configuration</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#runningAnApplication"><strong>2.9</strong><span>Running an Application</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#testingAnApplication"><strong>2.10</strong><span>Testing an Application</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#deployingAnApplication"><strong>2.11</strong><span>Deploying an Application</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#supportedJavaEEContainers"><strong>2.12</strong><span>Supported Java EE Containers</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:10px"><a href="#creatingArtefacts"><strong>2.14</strong><span>Creating Artefacts</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#conf"><strong>3</strong><span>Configuration</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#config"><strong>3.1</strong><span>Basic Configuration</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#builtInOptions"><strong>3.1.1</strong><span>Built in options</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#logging"><strong>3.1.2</strong><span>Logging</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#configGORM"><strong>3.1.3</strong><span>GORM</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#environments"><strong>3.2</strong><span>Environments</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#dataSource"><strong>3.3</strong><span>The DataSource</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#dataSourcesAndEnvironments"><strong>3.3.1</strong><span>DataSources and Environments</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#JNDIDataSources"><strong>3.3.2</strong><span>JNDI DataSources</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#automaticDatabaseMigration"><strong>3.3.3</strong><span>Automatic Database Migration</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#transactionAwareDataSourceProxy"><strong>3.3.4</strong><span>Transaction-aware DataSource Proxy</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#databaseConsole"><strong>3.3.5</strong><span>Database Console</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#multipleDatasources"><strong>3.3.6</strong><span>Multiple Datasources</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#configExternalized"><strong>3.4</strong><span>Externalized Configuration</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#versioning"><strong>3.5</strong><span>Versioning</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#docengine"><strong>3.6</strong><span>Project Documentation</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#ivy"><strong>3.7</strong><span>Dependency Resolution</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#configurationsAndDependencies"><strong>3.7.1</strong><span>Configurations and Dependencies</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#dependencyRepositories"><strong>3.7.2</strong><span>Dependency Repositories</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#debuggingResolution"><strong>3.7.3</strong><span>Debugging Resolution</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#inheritedDependencies"><strong>3.7.4</strong><span>Inherited Dependencies</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#providingDefaultDependencies"><strong>3.7.5</strong><span>Providing Default Dependencies</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#changingDependencies"><strong>3.7.6</strong><span>Snapshots and Other Changing Dependencies</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#dependencyReports"><strong>3.7.7</strong><span>Dependency Reports</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#pluginJARDependencies"><strong>3.7.8</strong><span>Plugin JAR Dependencies</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#mavenIntegration"><strong>3.7.9</strong><span>Maven Integration</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#mavendeploy"><strong>3.7.10</strong><span>Deploying to a Maven Repository</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#pluginDependencies"><strong>3.7.11</strong><span>Plugin Dependencies</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#commandLine"><strong>4</strong><span>The Command Line</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#interactiveMode"><strong>4.1</strong><span>Interactive Mode</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#creatingGantScripts"><strong>4.2</strong><span>Creating Gant Scripts</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#reusingGrailsScripts"><strong>4.3</strong><span>Re-using Grails scripts</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#events"><strong>4.4</strong><span>Hooking into Events</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#buildCustomising"><strong>4.5</strong><span>Customising the build</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#antAndMaven"><strong>4.6</strong><span>Ant and Maven</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#GORM"><strong>5</strong><span>Object Relational Mapping (GORM)</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#quickStartGuide"><strong>5.1</strong><span>Quick Start Guide</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#basicCRUD"><strong>5.1.1</strong><span>Basic CRUD</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#domainClasses"><strong>5.2</strong><span>Domain Modelling in GORM</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#gormAssociation"><strong>5.2.1</strong><span>Association in GORM</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#manyToOneAndOneToOne"><strong>5.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>5.2.1.2</strong><span>One-to-many</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#manyToMany"><strong>5.2.1.3</strong><span>Many-to-many</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#basicCollectionTypes"><strong>5.2.1.4</strong><span>Basic Collection Types</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#gormComposition"><strong>5.2.2</strong><span>Composition in GORM</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#inheritanceInGORM"><strong>5.2.3</strong><span>Inheritance in GORM</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#sets,ListsAndMaps"><strong>5.2.4</strong><span>Sets, Lists and Maps</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#persistenceBasics"><strong>5.3</strong><span>Persistence Basics</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#savingAndUpdating"><strong>5.3.1</strong><span>Saving and Updating</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#deletingObjects"><strong>5.3.2</strong><span>Deleting Objects</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#cascades"><strong>5.3.3</strong><span>Understanding Cascading Updates and Deletes</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#fetching"><strong>5.3.4</strong><span>Eager and Lazy Fetching</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#locking"><strong>5.3.5</strong><span>Pessimistic and Optimistic Locking</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#modificationChecking"><strong>5.3.6</strong><span>Modification Checking</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#querying"><strong>5.4</strong><span>Querying with GORM</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#finders"><strong>5.4.1</strong><span>Dynamic Finders</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#whereQueries"><strong>5.4.2</strong><span>Where Queries</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#criteria"><strong>5.4.3</strong><span>Criteria</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#detachedCriteria"><strong>5.4.4</strong><span>Detached Criteria</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#hql"><strong>5.4.5</strong><span>Hibernate Query Language (HQL)</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#advancedGORMFeatures"><strong>5.5</strong><span>Advanced GORM Features</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#eventsAutoTimestamping"><strong>5.5.1</strong><span>Events and Auto Timestamping</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#ormdsl"><strong>5.5.2</strong><span>Custom ORM Mapping</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#tableAndColumnNames"><strong>5.5.2.1</strong><span>Table and Column Names</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#caching"><strong>5.5.2.2</strong><span>Caching Strategy</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#inheritanceStrategies"><strong>5.5.2.3</strong><span>Inheritance Strategies</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#identity"><strong>5.5.2.4</strong><span>Custom Database Identity</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#compositePrimaryKeys"><strong>5.5.2.5</strong><span>Composite Primary Keys</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#databaseIndices"><strong>5.5.2.6</strong><span>Database Indices</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#optimisticLockingAndVersioning"><strong>5.5.2.7</strong><span>Optimistic Locking and Versioning</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#fetchingDSL"><strong>5.5.2.8</strong><span>Eager and Lazy Fetching</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#customCascadeBehaviour"><strong>5.5.2.9</strong><span>Custom Cascade Behaviour</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#customHibernateTypes"><strong>5.5.2.10</strong><span>Custom Hibernate Types</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#derivedProperties"><strong>5.5.2.11</strong><span>Derived Properties</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#customNamingStrategy"><strong>5.5.2.12</strong><span>Custom Naming Strategy</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#defaultSortOrder"><strong>5.5.3</strong><span>Default Sort Order</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#programmaticTransactions"><strong>5.6</strong><span>Programmatic Transactions</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#gormConstraints"><strong>5.7</strong><span>GORM and Constraints</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#theWebLayer"><strong>6</strong><span>The Web Layer</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#controllers"><strong>6.1</strong><span>Controllers</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#understandingControllersAndActions"><strong>6.1.1</strong><span>Understanding Controllers and Actions</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#controllersAndScopes"><strong>6.1.2</strong><span>Controllers and Scopes</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#modelsAndViews"><strong>6.1.3</strong><span>Models and Views</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#redirectsAndChaining"><strong>6.1.4</strong><span>Redirects and Chaining</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#interceptors"><strong>6.1.5</strong><span>Controller Interceptors</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#dataBinding"><strong>6.1.6</strong><span>Data Binding</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#xmlAndJSON"><strong>6.1.7</strong><span>XML and JSON Responses</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#moreOnJSONBuilder"><strong>6.1.8</strong><span>More on JSONBuilder</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#uploadingFiles"><strong>6.1.9</strong><span>Uploading Files</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#commandObjects"><strong>6.1.10</strong><span>Command Objects</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#formtokens"><strong>6.1.11</strong><span>Handling Duplicate Form Submissions</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#typeConverters"><strong>6.1.12</strong><span>Simple Type Converters</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#asynchronousRequestProcessing"><strong>6.1.13</strong><span>Asynchronous Request Processing</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#gsp"><strong>6.2</strong><span>Groovy Server Pages</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#GSPBasics"><strong>6.2.1</strong><span>GSP Basics</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#variablesAndScopes"><strong>6.2.1.1</strong><span>Variables and Scopes</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#logicAndIteration"><strong>6.2.1.2</strong><span>Logic and Iteration</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#pageDirectives"><strong>6.2.1.3</strong><span>Page Directives</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#expressions"><strong>6.2.1.4</strong><span>Expressions</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#tags"><strong>6.2.2</strong><span>GSP Tags</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#tagVariablesAndScopes"><strong>6.2.2.1</strong><span>Variables and Scopes</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#tagLogicAndIteration"><strong>6.2.2.2</strong><span>Logic and Iteration</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#searchAndFiltering"><strong>6.2.2.3</strong><span>Search and Filtering</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#linksAndResources"><strong>6.2.2.4</strong><span>Links and Resources</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#formsAndFields"><strong>6.2.2.5</strong><span>Forms and Fields</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#tagsAsMethodCalls"><strong>6.2.2.6</strong><span>Tags as Method Calls</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#viewsAndTemplates"><strong>6.2.3</strong><span>Views and Templates</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#layouts"><strong>6.2.4</strong><span>Layouts with Sitemesh</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#resources"><strong>6.2.5</strong><span>Static Resources</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#includingResourcesUsingTheResourceTags"><strong>6.2.5.1</strong><span>Including resources using the resource tags</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#otherResourceTags"><strong>6.2.5.2</strong><span>Other resource tags</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#declaringResources"><strong>6.2.5.3</strong><span>Declaring resources</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#overridingPluginResources"><strong>6.2.5.4</strong><span>Overriding plugin resources</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#optimizingYourResources"><strong>6.2.5.5</strong><span>Optimizing your resources</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#debugging"><strong>6.2.5.6</strong><span>Debugging</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#preventingProcessingOfResources"><strong>6.2.5.7</strong><span>Preventing processing of resources</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#otherResourcesPlugins"><strong>6.2.5.8</strong><span>Other Resources-aware plugins</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#sitemeshContentBlocks"><strong>6.2.6</strong><span>Sitemesh Content Blocks</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#makingChangesToADeployedApplication"><strong>6.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>6.2.8</strong><span>GSP Debugging</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#taglibs"><strong>6.3</strong><span>Tag Libraries</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#taglibVariablesAndScopes"><strong>6.3.1</strong><span>Variables and Scopes</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#simpleTags"><strong>6.3.2</strong><span>Simple Tags</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#logicalTags"><strong>6.3.3</strong><span>Logical Tags</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#iterativeTags"><strong>6.3.4</strong><span>Iterative Tags</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#namespaces"><strong>6.3.5</strong><span>Tag Namespaces</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#usingJSPTagLibraries"><strong>6.3.6</strong><span>Using JSP Tag Libraries</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#tagReturnValue"><strong>6.3.7</strong><span>Tag return value</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#urlmappings"><strong>6.4</strong><span>URL Mappings</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#mappingToControllersAndActions"><strong>6.4.1</strong><span>Mapping to Controllers and Actions</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#embeddedVariables"><strong>6.4.2</strong><span>Embedded Variables</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#mappingToViews"><strong>6.4.3</strong><span>Mapping to Views</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#mappingToResponseCodes"><strong>6.4.4</strong><span>Mapping to Response Codes</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#mappingHTTP"><strong>6.4.5</strong><span>Mapping to HTTP methods</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#mappingWildcards"><strong>6.4.6</strong><span>Mapping Wildcards</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#automaticLinkRewriting"><strong>6.4.7</strong><span>Automatic Link Re-Writing</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#applyingConstraints"><strong>6.4.8</strong><span>Applying Constraints</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#namedMappings"><strong>6.4.9</strong><span>Named URL Mappings</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#customizingUrlFormat"><strong>6.4.10</strong><span>Customizing URL Formats</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#webflow"><strong>6.5</strong><span>Web Flow</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#startAndEndStates"><strong>6.5.1</strong><span>Start and End States</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#actionStatesAndViewStates"><strong>6.5.2</strong><span>Action States and View States</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#flowExecutionEvents"><strong>6.5.3</strong><span>Flow Execution Events</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#flowScopes"><strong>6.5.4</strong><span>Flow Scopes</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#dataBindingAndValidation"><strong>6.5.5</strong><span>Data Binding and Validation</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#subflowsAndConversations"><strong>6.5.6</strong><span>Subflows and Conversations</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#filters"><strong>6.6</strong><span>Filters</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#applyingFilters"><strong>6.6.1</strong><span>Applying Filters</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#filterTypes"><strong>6.6.2</strong><span>Filter Types</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#filterVariablesAndScopes"><strong>6.6.3</strong><span>Variables and Scopes</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#filterDependencies"><strong>6.6.4</strong><span>Filter Dependencies</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#ajax"><strong>6.7</strong><span>Ajax</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#ajaxSupport"><strong>6.7.1</strong><span>Ajax Support</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#remotingLinking"><strong>6.7.1.1</strong><span>Remoting Linking</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#updatingContent"><strong>6.7.1.2</strong><span>Updating Content</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#remoteFormSubmission"><strong>6.7.1.3</strong><span>Remote Form Submission</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#ajaxEvents"><strong>6.7.1.4</strong><span>Ajax Events</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#ajaxWithPrototype"><strong>6.7.2</strong><span>Ajax with Prototype</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#ajaxWithDojo"><strong>6.7.3</strong><span>Ajax with Dojo</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#ajaxWithGWT"><strong>6.7.4</strong><span>Ajax with GWT</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#ajaxOnTheServer"><strong>6.7.5</strong><span>Ajax on the Server</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#contentNegotiation"><strong>6.8</strong><span>Content Negotiation</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#validation"><strong>7</strong><span>Validation</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#constraints"><strong>7.1</strong><span>Declaring Constraints</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#validatingConstraints"><strong>7.2</strong><span>Validating Constraints</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#validationOnTheClient"><strong>7.3</strong><span>Validation on the Client</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#validationAndInternationalization"><strong>7.4</strong><span>Validation and Internationalization</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#validationNonDomainAndCommandObjectClasses"><strong>7.5</strong><span>Validation Non Domain and Command Object Classes</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#services"><strong>8</strong><span>The Service Layer</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#declarativeTransactions"><strong>8.1</strong><span>Declarative Transactions</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#transactionsRollbackAndTheSession"><strong>8.1.1</strong><span>Transactions Rollback and the Session</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#scopedServices"><strong>8.2</strong><span>Scoped Services</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#dependencyInjectionServices"><strong>8.3</strong><span>Dependency Injection and Services</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#usingServicesFromJava"><strong>8.4</strong><span>Using Services from Java</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#testing"><strong>9</strong><span>Testing</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#unitTesting"><strong>9.1</strong><span>Unit Testing</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#unitTestingControllers"><strong>9.1.1</strong><span>Unit Testing Controllers</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#unitTestingTagLibraries"><strong>9.1.2</strong><span>Unit Testing Tag Libraries</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#unitTestingDomains"><strong>9.1.3</strong><span>Unit Testing Domains</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#unitTestingFilters"><strong>9.1.4</strong><span>Unit Testing Filters</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#unitTestingURLMappings"><strong>9.1.5</strong><span>Unit Testing URL Mappings</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#mockingCollaborators"><strong>9.1.6</strong><span>Mocking Collaborators</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#integrationTesting"><strong>9.2</strong><span>Integration Testing</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#functionalTesting"><strong>9.3</strong><span>Functional Testing</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#i18n"><strong>10</strong><span>Internationalization</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#understandingMessageBundles"><strong>10.1</strong><span>Understanding Message Bundles</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#changingLocales"><strong>10.2</strong><span>Changing Locales</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#readingMessages"><strong>10.3</strong><span>Reading Messages</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#scaffoldingAndI18n"><strong>10.4</strong><span>Scaffolding and i18n</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#security"><strong>11</strong><span>Security</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#securingAgainstAttacks"><strong>11.1</strong><span>Securing Against Attacks</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#codecs"><strong>11.2</strong><span>Encoding and Decoding Objects</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#authentication"><strong>11.3</strong><span>Authentication</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#securityPlugins"><strong>11.4</strong><span>Security Plugins</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#springSecurity"><strong>11.4.1</strong><span>Spring Security</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#shiro"><strong>11.4.2</strong><span>Shiro</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#plugins"><strong>12</strong><span>Plugins</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#creatingAndInstallingPlugins"><strong>12.1</strong><span>Creating and Installing Plugins</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#repositories"><strong>12.2</strong><span>Plugin Repositories</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#understandingPluginStructure"><strong>12.3</strong><span>Understanding a Plugin's Structure</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#providingBasicArtefacts"><strong>12.4</strong><span>Providing Basic Artefacts</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#evaluatingConventions"><strong>12.5</strong><span>Evaluating Conventions</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#hookingIntoBuildEvents"><strong>12.6</strong><span>Hooking into Build Events</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#hookingIntoRuntimeConfiguration"><strong>12.7</strong><span>Hooking into Runtime Configuration</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#addingDynamicMethodsAtRuntime"><strong>12.8</strong><span>Adding Dynamic Methods at Runtime</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#participatingInAutoReloadEvents"><strong>12.9</strong><span>Participating in Auto Reload Events</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#understandingPluginLoadOrder"><strong>12.10</strong><span>Understanding Plugin Load Order</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#artefactApi"><strong>12.11</strong><span>The Artefact API</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#queryingArtefacts"><strong>12.11.1</strong><span>Asking About Available Artefacts</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#customArtefacts"><strong>12.11.2</strong><span>Adding Your Own Artefact Types</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#binaryPlugins"><strong>12.12</strong><span>Binary Plugins</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#webServices"><strong>13</strong><span>Web Services</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#REST"><strong>13.1</strong><span>REST</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#SOAP"><strong>13.2</strong><span>SOAP</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#RSSAndAtom"><strong>13.3</strong><span>RSS and Atom</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#spring"><strong>14</strong><span>Grails and Spring</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#theUnderpinningsOfGrails"><strong>14.1</strong><span>The Underpinnings of Grails</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#springdslAdditional"><strong>14.2</strong><span>Configuring Additional Beans</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#springdsl"><strong>14.3</strong><span>Runtime Spring with the Beans DSL</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#theBeanBuilderDSLExplained"><strong>14.4</strong><span>The BeanBuilder DSL Explained</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#propertyPlaceholderConfiguration"><strong>14.5</strong><span>Property Placeholder Configuration</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#propertyOverrideConfiguration"><strong>14.6</strong><span>Property Override Configuration</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#hibernate"><strong>15</strong><span>Grails and Hibernate</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#usingHibernateXMLMappingFiles"><strong>15.1</strong><span>Using Hibernate XML Mapping Files</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#mappingWithHibernateAnnotations"><strong>15.2</strong><span>Mapping with Hibernate Annotations</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#addingConstraints"><strong>15.3</strong><span>Adding Constraints</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#scaffolding"><strong>16</strong><span>Scaffolding</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#deployment"><strong>17</strong><span>Deployment</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#contributing"><strong>18</strong><span>Contributing to Grails</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#issues"><strong>18.1</strong><span>Report Issues in JIRA</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#build"><strong>18.2</strong><span>Build From Source and Run Tests</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#patchesCore"><strong>18.3</strong><span>Submit Patches to Grails Core</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#patchesDoc"><strong>18.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.springframework.org" target="blank">Spring</a> MVC</li>
<li>A command line scripting environment built on the Groovy-powered <a href="http://groovy.codehaus.org/Gant" target="blank">Gant</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.codehaus.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 2.0?</h2>
This section covers the new features that are present in 2.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.1 Development Environment Features"><!-- Legacy link --></a>
<h2 id="developmentEnvironmentFeatures">1.1.1 Development Environment Features</h2>
<h4>Interactive Mode and Console Enhancements</h4><p class="paragraph"/>Grails 2.0 features brand new console output that is more concise and user friendly to consume. An example of the new output when running tests can be seen below:<p class="paragraph"/><img border="0" class="center" src="../img/test-output.png"></img><p class="paragraph"/>In general Grails makes its best effort to display update information on a single line and only present the information that is crucial. This means that while in previous versions of Grails the <a href="../ref/Command Line/war.html" class="commandLine">war</a> command produced many lines of output, in Grails 2.0 only 1 line of output is produced:<p class="paragraph"/><img border="0" class="center" src="../img/war-output.png"></img><p class="paragraph"/>In addition simply typing 'grails' at the command line activates the new interactive mode which features TAB completion, command history and keeps the JVM running to ensure commands execute much quicker than otherwise<p class="paragraph"/><img border="0" class="center" src="../img/interactive-output.png"></img><p class="paragraph"/>For more information on the new features of the console refer to the section of the user guide that covers the <a href="../guide/single.html#interactiveMode" class="guide">console and interactive mode</a>.<p class="paragraph"/><h4>Reloading Agent</h4><p class="paragraph"/>Grails 2.0 reloading mechanism no longer uses class loaders, but instead uses a JVM agent to reload changes to class files. This results in greatly improved reliability when reloading changes and also ensures that the class files stored in disk remain consistent with the class files loaded in memory, which reduces the need to run the <a href="../ref/Command Line/clean.html" class="commandLine">clean</a> command.<p class="paragraph"/><h4>New Test Report and Documentation Templates</h4><p class="paragraph"/>There are new templates for displaying test results that are clearer and more user friendly than the previous reports:<p class="paragraph"/><img border="0" class="center" src="../img/test-template.png"></img><p class="paragraph"/>In addition, the Grails documentation engine has received a facelift with a new template for presenting Grails application and plugin documentation:<p class="paragraph"/><img border="0" class="center" src="../img/doc-template.png"></img><p class="paragraph"/>See the section on the <a href="../guide/single.html#docengine" class="guide">documentation engine</a> for more usage info.<p class="paragraph"/><h4>Use a TOC for Project Docs</h4><p class="paragraph"/>The old documentation engine relied on you putting section numbers into the gdoc filenames. Although convenient, this effectively made it difficult to restructure your user guide by inserting new chapters and sections. In addition, any such restructuring or renaming of section titles resulted in breaking changes to the URLs.<p class="paragraph"/>You can now use logical names for your gdoc files and define the structure and section titles in a YAML table-of-contents file, as described in the section on the <a href="../guide/single.html#docengine" class="guide">documentation engine</a>. The logical names appear in the URLs, so as long as you don't change those, your URLs will always remain the same no matter how much restructuring or changing of titles you do.<p class="paragraph"/>Grails 2.0 even provides a <a href="../ref/Command Line/migrate-docs.html" class="commandLine">migrate-docs</a> command to aid you in migrating existing gdoc user guides.<p class="paragraph"/><h4>Enhanced Error Reporting and Diagnosis</h4><p class="paragraph"/>Error reporting and problem diagnosis has been greatly improved with a new errors view that analyses stack traces and recursively displays problem areas in your code:<p class="paragraph"/><img border="0" class="center" src="../img/errors-view.png"></img><p class="paragraph"/>In addition stack trace filtering has been further enhanced to display only relevant trace information:<p class="paragraph"/><div class="code"><pre>Line | Method
&#45;&#62;&#62; 9 | getValue in Book.groovy
&#45; &#45; &#45; &#45; &#45; &#45; &#45; &#45; &#45; &#45; &#45; &#45; &#45; &#45; &#45; &#45; &#45; &#45; &#45; &#45; &#45; &#45; &#45; &#45; &#45;
| 7 | getBookValue in BookService.groovy
| 886 | runTask . . in ThreadPoolExecutor.java
| 908 | run in ''
^ 662 | run . . . . in <span class="java&#45;object">Thread</span>.java</pre></div><p class="paragraph"/><h4>H2 Database and Console</h4><p class="paragraph"/>Grails 2.0 now uses the H2 database instead of HSQLDB, and enables the H2 database console in development mode (at the URI /dbconsole) so that the in-memory database can be easily queried from the browser:<p class="paragraph"/><img border="0" class="center" src="../img/h2-console.png"></img><p class="paragraph"/><h4>Plugin Usage Tracking</h4><p class="paragraph"/>To enhance community awareness of the most popular plugins an opt-in plugin usage tracking system has been included where users can participate in providing feedback to the plugin community on which plugins are most popular.<p class="paragraph"/>This will help drive the roadmap and increase support of key plugins while reducing the need to support older or less popular plugins thus helping plugin development teams focus their efforts.<p class="paragraph"/>
<h4>Dependency Resolution Improvements</h4><p class="paragraph"/>There are numerous improvements to dependency resolution handling via Ivy including:
<ul class="star">
<li>Grails now makes a best effort to cache the previous resolve and avoid resolving again unless you change <code>BuildConfig.groovy</code>.</li>
<li>Plugins dependencies now appear in the dependency report generated by <code>grails dependency-report</code></li>
<li>Plugins published with the release plugin now publish their transitive plugin dependencies in the generated POM which are later resolved.</li>
<li>It is now possible to customize the ivy cache directory via <code>BuildConfig.groovy</code></li>
</ul><p class="paragraph"/><div class="code"><pre>grails.project.dependency.resolution = &#123;
cacheDir <span class="java&#45;quote">"target/ivy&#45;cache"</span>
&#125;</pre></div>
<ul class="star">
<li>You can change the ivy cache directory for all projects via <code>settings.groovy</code></li>
</ul><p class="paragraph"/><div class="code"><pre>grails.dependency.cache.dir = <span class="java&#45;quote">"$&#123;userHome&#125;/.ivy2/cache"</span></pre></div>
<ul class="star">
<li>It is now possible to completely disable resolution from inherited repositories (repositories defined by other plugins):</li>
</ul><p class="paragraph"/><div class="code"><pre>grails.project.dependency.resolution = &#123;<p class="paragraph"/> repositories &#123;
inherits <span class="java&#45;keyword">false</span> // Whether to inherit repository definitions from plugins
&#8230;
&#125;
&#8230;
&#125;</pre></div>
<ul class="star">
<li>It is now possible to easily disable checksum validation errors:</li>
</ul><p class="paragraph"/><div class="code"><pre>grails.project.dependency.resolution = &#123;
checksums <span class="java&#45;keyword">false</span> // whether to verify checksums or not
&#125;</pre></div>
<a name="1.1.2 Core Features"><!-- Legacy link --></a>
<h2 id="coreFeatures">1.1.2 Core Features</h2>
<h4>Binary Plugins</h4><p class="paragraph"/>Grails plugins can now be packaged as JAR files and published to standard maven repositories. This even works for GSP and static resources (with resources plugin 1.0.1). See the section on <a href="../guide/single.html#binaryPlugins" class="guide">Binary plugins</a> for more information.<p class="paragraph"/><h4>Groovy 1.8</h4><p class="paragraph"/>Grails 2.0 comes with Groovy 1.8 which includes many new <a href="http://docs.codehaus.org/display/GROOVY/Groovy+1.8+release+notes" target="blank">features and enhancements</a><p class="paragraph"/><h4>Spring 3.1 Profile Support</h4><p class="paragraph"/>Grails' existing environment support has been bridged into the Spring 3.1 profile support. For example when running with a custom Grails environment called "production", a Spring profile of "production" is activated so that you can use Spring's bean configuration APIs to configure beans for a specific profile.
<a name="1.1.3 Web Features"><!-- Legacy link --></a>
<h2 id="webFeatures">1.1.3 Web Features</h2>
<h4>Controller Actions as Methods</h4><p class="paragraph"/>It is now possible to define controller actions as methods instead of using closures as in previous versions of Grails. In fact this is now the preferred way of expressing an action. For example:<p class="paragraph"/><div class="code"><pre>// action as a method
def index() &#123;<p class="paragraph"/>&#125;
// action as a closure
def index = &#123;<p class="paragraph"/>&#125;</pre></div><p class="paragraph"/><h4>Binding Primitive Method Action Arguments</h4><p class="paragraph"/>It is now possible to bind form parameters to action arguments where the name of the form element matches the argument name. For example given the following form:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:form name=<span class="xml&#45;quote">"myForm"</span> action=<span class="xml&#45;quote">"save"</span>&#62;</span>
<span class="xml&#45;tag">&#60;input name=<span class="xml&#45;quote">"name"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;input name=<span class="xml&#45;quote">"age"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;/g:form&#62;</span></pre></div><p class="paragraph"/>You can define an action that declares arguments for each input and automatically converts the parameters to the appropriate type:<p class="paragraph"/><div class="code"><pre>def save(<span class="java&#45;object">String</span> name, <span class="java&#45;object">int</span> age) &#123;
// remaining
&#125;</pre></div><p class="paragraph"/><h4>Static Resource Abstraction</h4><p class="paragraph"/>A new <a href="../guide/single.html#resources" class="guide">static resource abstraction</a> is included that allows declarative handling of JavaScript, CSS and image resources including automatic ordering, compression, caching and gzip handling.<p class="paragraph"/><h4>Servlet 3.0 Async Features</h4><p class="paragraph"/>Grails now supports Servlet 3.0 including the Asynchronous programming model defined by the specification:<p class="paragraph"/><div class="code"><pre>def index() &#123;
def ctx = startAsync()
ctx.start &#123;
<span class="java&#45;keyword">new</span> Book(title:<span class="java&#45;quote">"The Stand"</span>).save()
render template:<span class="java&#45;quote">"books"</span>, model:&#91;books:Book.list()&#93;
ctx.complete()
&#125;
&#125;</pre></div><p class="paragraph"/><h4>Link Generation API</h4><p class="paragraph"/>A general purpose <code>LinkGenerator</code> class is now available that is usable anywhere within a Grails application and not just within the context of a controller. For example if you need to generate links in a service or an asynchronous background job outside the scope of a request:<p class="paragraph"/><div class="code"><pre>LinkGenerator grailsLinkGenerator<p class="paragraph"/>def generateLink() &#123;
grailsLinkGenerator.link(controller:<span class="java&#45;quote">"book"</span>, action:<span class="java&#45;quote">"list"</span>)
&#125;</pre></div><p class="paragraph"/><h4>Page Rendering API</h4><p class="paragraph"/>Like the <code>LinkGenerator</code> the new <code>PageRenderer</code> can be used to render GSP pages outside the scope of a web request, such as in a scheduled job or web service. The <code>PageRenderer</code> class features a very similar API to the <code>render</code> method found within controllers:<p class="paragraph"/><div class="code"><pre>grails.gsp.PageRenderer groovyPageRenderer<p class="paragraph"/>void welcomeUser(User user) &#123;
def contents = groovyPageRenderer.render(view:<span class="java&#45;quote">"/emails/welcomeLetter"</span>, model:&#91;user: user&#93;)
sendEmail &#123;
to user.email
body contents
&#125;
&#125;</pre></div><p class="paragraph"/>The <code>PageRenderer</code> service also allows you to pre-process GSPs into HTML templates:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">new</span> File(<span class="java&#45;quote">"/path/to/welcome.html"</span>).withWriter &#123; w &#45;&#62;
groovyPageRenderer.renderTo(view:<span class="java&#45;quote">"/page/content"</span>, w)
&#125;</pre></div><p class="paragraph"/><h4>Filter Exclusions</h4><p class="paragraph"/>Filters may now express controller, action and uri exclusions to offer more options for expressing to which requests a particular filter should be applied.<p class="paragraph"/><div class="code"><pre>filter1(actionExclude: 'log&#42;') &#123;
before = &#123;
// …
&#125;
&#125;
filter2(controllerExclude: 'auth') &#123;
before = &#123;
// …
&#125;
&#125;<p class="paragraph"/>filter3(uriExclude: '/secure&#42;') &#123;
before = &#123;
// …
&#125;
&#125;</pre></div><p class="paragraph"/><h4>Performance Improvements</h4><p class="paragraph"/>Performance of GSP page rendering has once again been improved by optimizing the GSP compiler to inline method calls where possible.<p class="paragraph"/><h4>HTML5 Scaffolding</h4><p class="paragraph"/>There is a new HTML5-based scaffolding UI:<p class="paragraph"/><img border="0" class="center" src="../img/scaffolding-ui.png"></img><p class="paragraph"/><h4>jQuery by Default</h4><p class="paragraph"/>The jQuery plugin is now the default JavaScript library installed into a Grails application. For backwards compatibility a <a href="http://grails.org/plugin/prototype" target="blank">Prototype plugin</a> is available. Refer to the <a href="http://grails.org/plugin/prototype" target="blank">documentation</a> on the Prototype plugin for installation instructions.<p class="paragraph"/><h4>Easy Date Parsing</h4><p class="paragraph"/>A new <code>date</code> method has been added to the <code>params</code> object to allow easy, null-safe parsing of dates:<p class="paragraph"/><div class="code"><pre>def val = params.date('myDate', 'dd&#45;MM&#45;yyyy')<p class="paragraph"/>// or a list <span class="java&#45;keyword">for</span> formats
def val = params.date('myDate', &#91;'yyyy&#45;MM&#45;dd', 'yyyyMMdd', 'yyMMdd'&#93;)<p class="paragraph"/>// or the format read from messages.properties via the key 'date.myDate.format'
def val = params.date('myDate')</pre></div><p class="paragraph"/><h4>Customizable URL Formats</h4><p class="paragraph"/>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&#45;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="../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&#45;keyword">package</span> com.myapplication<p class="paragraph"/>class MyUrlConverterImpl <span class="java&#45;keyword">implements</span> grails.web.UrlConverter &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> toUrlElement(<span class="java&#45;object">String</span> propertyOrClassName) &#123;
// <span class="java&#45;keyword">return</span> some representation of a property or class name that should be used in URLs&#8230;
&#125;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>// grails&#45;app/conf/spring/resources.groovy<p class="paragraph"/>beans = &#123;
<span class="java&#45;quote">"$&#123;grails.web.UrlConverter.BEAN_NAME&#125;"</span>(com.myapplication.MyUrlConverterImpl)
&#125;</pre></div><p class="paragraph"/><h4>Web Flow input and output</h4>
It is now possible to provide input arguments when calling a subflow. Flows can also return output values that can be used in a calling flow.
<a name="1.1.4 Persistence Features"><!-- Legacy link --></a>
<h2 id="persistenceFeatures">1.1.4 Persistence Features</h2>
<h4>The GORM API</h4><p class="paragraph"/>The GORM API has been formalized into a set of classes (<code>GormStaticApi</code>, <code>GormInstanceApi</code> and <code>GormValidationApi</code>) that get statically wired into every domain class at the byte code level. The result is better code completion for IDEs, better integration with Java and the potential for more GORM implementations for other types of data stores.<p class="paragraph"/><h4>Detached Criteria and Where Queries</h4><p class="paragraph"/>Grails 2.0 features support for <a href="../guide/single.html#detachedCriteria" class="guide">DetachedCriteria</a> which are criteria queries that are not associated with any session or connection and thus can be more easily reused and composed:<p class="paragraph"/><div class="code"><pre>def criteria = <span class="java&#45;keyword">new</span> DetachedCriteria(Person).build &#123;
eq 'lastName', 'Simpson'
&#125;
def results = criteria.list(max:4, sort:<span class="java&#45;quote">"firstName"</span>)</pre></div><p class="paragraph"/>To support the addition of <a href="../guide/single.html#detachedCriteria" class="guide">DetachedCriteria</a> queries and encourage their use a new <code>where</code> method and DSL has been introduced to greatly reduce the complexity of criteria queries:<p class="paragraph"/><div class="code"><pre>def query = Person.where &#123;
(lastName != <span class="java&#45;quote">"Simpson"</span> &#38;&#38; firstName != <span class="java&#45;quote">"Fred"</span>) || (firstName == <span class="java&#45;quote">"Bart"</span> &#38;&#38; age &#62; 9)
&#125;
def results = query.list(sort:<span class="java&#45;quote">"firstName"</span>)</pre></div><p class="paragraph"/>See the documentation on <a href="../guide/single.html#detachedCriteria" class="guide">DetachedCriteria</a> and <a href="../guide/single.html#whereQueries" class="guide">Where Queries</a> for more information.<p class="paragraph"/><h4>New findOrCreate and findOrSave Methods</h4><p class="paragraph"/>Domain classes have support for the findOrCreateWhere, findOrSaveWhere, findOrCreateBy and findOrSaveBy query methods which behave just like findWhere and findBy methods except that they should never return null. If a matching instance cannot be found in the database then a new instance is created, populated with values represented in the query parameters and returned. In the case of findOrSaveWhere and findOrSaveBy, the instance is saved before being returned.<p class="paragraph"/><div class="code"><pre>def book = Book.findOrCreateWhere(author: 'Douglas Adams', title: <span class="java&#45;quote">"The Hitchiker's Guide To The Galaxy"</span>)
def book = Book.findOrSaveWhere(author: 'Daniel Suarez', title: 'Daemon')
def book = Book.findOrCreateByAuthorAndTitle('Daniel Suarez', 'Daemon')
def book = Book.findOrSaveByAuthorAndTitle('Daniel Suarez', 'Daemon')</pre></div><p class="paragraph"/><h4>Abstract Inheritance</h4><p class="paragraph"/>GORM now supports abstract inheritance trees which means you can define queries and associations linking to abstract classes:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">abstract</span> class Media &#123;
<span class="java&#45;object">String</span> title
&#125;
class Book <span class="java&#45;keyword">extends</span> Media &#123;
&#125;
class Album <span class="java&#45;keyword">extends</span> Media &#123;<p class="paragraph"/>&#125;
class Account &#123;
<span class="java&#45;keyword">static</span> hasMany = &#91;purchasedMedia:Media&#93;
&#125;<p class="paragraph"/>..<p class="paragraph"/>def allMedia = Media.list()</pre></div><p class="paragraph"/><h4>Multiple Data Sources Support</h4><p class="paragraph"/>It is now possible to define multiple datasources in <code>DataSource.groovy</code> and declare one or more datasources a particular domain uses by default:<p class="paragraph"/><div class="code"><pre>class ZipCode &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> code<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
datasource 'ZIP_CODES'
&#125;
&#125;</pre></div><p class="paragraph"/>If multiple datasources are specified for a domain then you can use the name of a particular datasource as a namespace in front of any regular GORM method:<p class="paragraph"/><div class="code"><pre>def zipCode = ZipCode.auditing.get(42)</pre></div><p class="paragraph"/>For more information see the section on <a href="../guide/single.html#multipleDatasources" class="guide">Multiple Data Sources</a> in the user guide.<p class="paragraph"/><h4>Database Migrations</h4><p class="paragraph"/>A new <a href="http://grails.org/plugin/database-migration" target="blank">database migration plugin</a> has been designed and built for Grails 2.0 allowing you to apply migrations to your database, rollback changes and diff your domain model with the current state of the database.<p class="paragraph"/><h4>Database Reverse Engineering</h4><p class="paragraph"/>A new <a href="http://www.grails.org/plugin/db-reverse-engineer" target="blank">database reverse engineering</a> plugin has been designed and built for Grails 2.0 that allows you to generate a domain model from an existing database schema.<p class="paragraph"/><h4>Hibernate 3.6</h4><p class="paragraph"/>Grails 2.0 is now built on Hibernate 3.6<p class="paragraph"/><h4>Bag Collections</h4><p class="paragraph"/>You can now use Hibernate <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/collections.html" target="blank">Bag</a>s for mapped collections to avoid the memory and performance issues of loading large collections to enforce <code>Set</code> uniqueness or <code>List</code> order.<p class="paragraph"/>For more information see the section on <a href="../guide/single.html#sets,ListsAndMaps" class="guide">Sets, Lists and Maps</a> in the user guide.<p class="paragraph"/>
<a name="1.1.5 Testing Features"><!-- Legacy link --></a>
<h2 id="testingFeatures">1.1.5 Testing Features</h2>
<h4>New Unit Testing Console Output</h4><p class="paragraph"/>Test output from the test-app command has been improved:<p class="paragraph"/><img border="0" class="center" src="../img/test-output.png"></img><p class="paragraph"/><h4>New Unit Testing API</h4><p class="paragraph"/>There is a new unit testing API based on mixins that supports JUnit 3, 4 and Spock style tests (with Spock 0.6 and above). Example:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> grails.test.mixin.TestFor<p class="paragraph"/>@TestFor(SimpleController)
class SimpleControllerTests &#123;
void testIndex() &#123;
controller.home()<p class="paragraph"/> assert view == <span class="java&#45;quote">"/simple/homePage"</span>
assert model.title == <span class="java&#45;quote">"Hello World"</span>
&#125;
&#125;</pre></div><p class="paragraph"/>The <a href="../guide/single.html#testing" class="guide">documentation on testing</a> has also been re-written around this new framework.<p class="paragraph"/><h4>Unit Testing GORM</h4><p class="paragraph"/>A new in-memory GORM implementation is present that supports many more features of the GORM API making unit testing of criteria queries, named queries and other previously unsupported methods possible.<p class="paragraph"/><h4>Faster Unit Testing with Interactive Mode</h4><p class="paragraph"/>The new interactive mode (activated by typing 'grails') greatly improves the execution time of running unit and integration tests.<p class="paragraph"/><h4>Unit Test Scaffolding</h4><p class="paragraph"/>A unit test is now generated for scaffolded controllers
<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 you will as a minimum need a Java Development Kit (JDK) installed version 1.6 or above and environment variable called <code>JAVA_HOME</code> pointing to the location of this installation. 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&#45;quote">"$PATH:$JAVA_HOME/bin"</span></pre></div><p class="paragraph"/>Note that although JDK 1.6 is required to use Grails at development time it is possible to deploy Grails to JDK 1.5 VMs by setting the <code>grails.project.source.level</code> and <code>grails.project.target.level</code> settings to "1.5" in <code>grails-app/conf/BuildConfig.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.project.source.level = 1.5
grails.project.target.level = 1.5</pre></div><p class="paragraph"/>In addition, Grails supports Servlet versions 2.5 and above. If you wish to use newer features of the Servlet API (such as 3.0) you should configure the <code>grails.servlet.version</code> in <code>BuildConfig.groovy</code> appropriately:<p class="paragraph"/><div class="code"><pre>grails.servlet.version = <span class="java&#45;quote">"3.0"</span></pre></div><p class="paragraph"/>
<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. To do so 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: 2.0.0</code></pre><p class="paragraph"/>
<a name="2.2 Upgrading from previous versions of Grails"><!-- Legacy link --></a>
<h2 id="upgradingFromPreviousVersionsOfGrails">2.3 Upgrading from previous versions of Grails</h2>
Although the Grails development team have tried to keep breakages to a minimum there are a number of items to consider when upgrading a Grails 1.0.x, 1.1.x, 1.2.x, or 1.3.x applications to Grails 2.0. The major changes are described in more detail below, but here's a brief summary of what you might encounter when upgrading from Grails 1.3.x:
<ul class="star">
<li><code>environment</code> bean added by Spring 3.1, which will be auto-wired into properties of the same name.</li>
<li>Logging by convention packages have changed, so you may not see the logging output you expect. Update your logging configuration as described below.</li>
<li>HSQLDB has been replaced with H2 as default in-memory database. If you use the former, either change your data source to H2 or add HSQLDB as a runtime dependency.</li>
<li>The <code>release-plugin</code> command has been removed. You must now install the <a href="http://grails.org/plugin/release" target="blank">Release plugin</a> and use its <a href="../guide/single.html#repositories" class="guide"><code>publish-plugin</code> command</a> instead.</li>
<li>The <code>redirect()</code> method no longer commits the response, so <code>isCommitted()</code> will return <code>false</code>. If you use that method, then call <code>request.isRedirected()</code> instead.</li>
<li>The <code>redirect()</code> method now uses the grails.serverURL config setting to generate the redirect URL. You may need to remove the setting, particularly from the development and test environments.</li>
<li><code>withFormat()</code> no longer takes account of the request content type. If you want to do something based on the request content type, use <code>request.withFormat()</code>.</li>
<li>Adaptive AJAX tags using Prototype will break. In this situation you must install the new Prototype plugin.</li>
<li>If you install Resources (or it is installed automatically), tags like <code>&#60;g:javascript&#62;</code> won't write anything to the page until you add the <code>&#60;r:layoutResources/&#62;</code> tags to your layout.</li>
<li>Resources adds a '/static' URL, so you may have to update your access control rules accordingly.</li>
<li>Some plugins may fail to install because one or more of their dependencies can not be found. If this happens, the plugin probably has a custom repository URL that you need to add to your project's <code>BuildConfig.groovy</code>.</li>
<li>The behaviour of abstract domain classes has changed, so if you use them you will either have to move the abstract classes to 'src/groovy' or migrate your database schema and data.</li>
<li>Criteria queries default to INNER_JOIN for associations rather than OUTER_JOIN. This may affect some of your result data.</li>
<li>Constraints declared for non-existent properties will now throw an exception.</li>
<li><code>beforeValidate()</code> may be called two or more times during a request, for example once on save() and once just before the view is rendered.</li>
<li>Public methods in controllers will now be treated as actions. If you don't want this, make them protected or private.</li>
<li>The new unit testing framework won't work with the old <code>GrailsUnitTestCase</code> class hierarchy. Your old tests will continue to work, but if you wish to use the new annotations, do not extend any of the <code>&#42;UnitTestCase</code> classes.</li>
<li>Output from Ant tasks is now hidden by default. If your scripts are using <code>ant.echo()</code>, <code>ant.input()</code>, etc. you might want to use alternative mechanisms for output.</li>
<li>Domain properties of type java.net.URL may no longer work with your existing data. The serialisation mechanism for them appears to have changed. Consider migrating your data and domain models to String.</li>
<li>The Ivy cache location has changed. If you want to use the old location, configure the appropriate global setting (see below) but be aware that you may run into problems running Grails 1.3.x and 2.x projects side by side.</li>
<li>With new versions of various dependencies, some APIs (such as the Servlet API) may have changed. If you have code that implements any of those APIs, you will need to update it. Problems will typically manifest as compilation errors.</li>
<li>The following deprecated classes have been removed: <code>grails.web.JsonBuilder</code> and <code>grails.web.OpenRicoBuilder</code>.</li>
</ul><p class="paragraph"/><h3>Upgrading from Grails 1.3.x</h3><p class="paragraph"/><h4>Changes to web.xml template</h4><p class="paragraph"/>If you have customized the web.xml provided by <code>grails install-templates</code> then you will need to update this customized template with the latest version provided by Grails. Failing to do so will lead to a ClassNotFoundException for the <code>org.codehaus.groovy.grails.web.util.Log4jConfigListener</code> class.<p class="paragraph"/><h4>Groovy 1.8 Changes</h4><p class="paragraph"/>Groovy 1.8 is a little stricter in terms of compilation so you may be required to fix compilation errors in your application that didn't occur under Grails 1.3.x.<p class="paragraph"/>Groovy 1.8 also requires that you update many of the libraries that you may be using in your application. Libraries known to require an upgrade include:
<ul class="star">
<li>Spock</li>
<li>Geb</li>
<li>GMock (upgrade unavailable as of this writing)</li>
</ul><p class="paragraph"/><h4>New 'environment' bean</h4><p class="paragraph"/>Spring 3.1 adds a new bean with the name 'environment'. It's of type <code>Environment</code> (in package <code>org.springframework.core.env</code>) and it will automatically be autowired into properties with the same name. This seems to cause particular problems with domain classes that have an <code>environment</code> property. In this case, adding the method:
<div class="code"><pre>void setEnvironment(org.springframework.core.env.Environment env) &#123;&#125;</pre></div>
works around the problem.<p class="paragraph"/><h4>HSQLDB Has Been Replaced With H2</h4><p class="paragraph"/>HSQLDB is still bundled with Grails but is not configured as a default runtime dependency. Upgrade options include replacing HSQLDB references in DataSource.groovy with H2 references or adding HSQLDB as a runtime dependency for the application.<p class="paragraph"/>If you want to run an application with different versions of Grails, it's simplest to add HSQLDB as a runtime dependency, which you can do in BuildConfig.groovy:<p class="paragraph"/><div class="code"><pre>grails.project.dependency.resolution = &#123;
inherits(<span class="java&#45;quote">"global"</span>) &#123;
&#125;
repositories &#123;
grailsPlugins()
grailsHome()
grailsCentral()
&#125;<p class="paragraph"/> dependencies &#123;
// Add HSQLDB as a runtime dependency
runtime 'hsqldb:hsqldb:1.8.0.10'
&#125;
&#125;</pre></div><p class="paragraph"/>A default DataSource.groovy which is compatible with H2 looks like this:<p class="paragraph"/><div class="code"><pre>dataSource &#123;
driverClassName = <span class="java&#45;quote">"org.h2.Driver"</span>
username = <span class="java&#45;quote">"sa"</span>
password = <span class="java&#45;quote">""</span>
&#125;
// environment specific settings
environments &#123;
development &#123;
dataSource &#123;
dbCreate = <span class="java&#45;quote">"create&#45;drop"</span> // one of 'create', 'create&#45;drop','update'
url = <span class="java&#45;quote">"jdbc:h2:mem:devDb"</span>
&#125;
&#125;
test &#123;
dataSource &#123;
dbCreate = <span class="java&#45;quote">"update"</span>
url = <span class="java&#45;quote">"jdbc:h2:mem:testDb"</span>
&#125;
&#125;
production &#123;
dataSource &#123;
dbCreate = <span class="java&#45;quote">"update"</span>
url = <span class="java&#45;quote">"jdbc:h2:prodDb"</span>
&#125;
&#125;
&#125;</pre></div><p class="paragraph"/>Another significant difference between H2 and HSQLDB is in the handling of <code>byte&#91;]</code> domain class properties. HSQLDB's default BLOB size is large and so you typically don't need to specify a maximum size. But H2 defaults to a maximum size of 255 bytes! If you store images in the database, the saves are likely to fail because of this. The easy fix is to add a <code>maxSize</code> constraint to the <code>byte&#91;]</code> property:<p class="paragraph"/><div class="code"><pre>class MyDomain &#123;
<span class="java&#45;object">byte</span>&#91;&#93; data<p class="paragraph"/> <span class="java&#45;keyword">static</span> constraints = &#123;
data maxSize: 1024 &#42; 1024 &#42; 2 // 2MB
&#125;
&#125;</pre></div><p class="paragraph"/>This constraint influences schema generation, so in the above example H2 will have the <code>data</code> column set to <code>BINARY(2097152)</code> by Hibernate.<p class="paragraph"/><h4>Abstract Inheritance Changes</h4><p class="paragraph"/>In previous versions of Grails abstract classes in <code>grails-app/domain</code> were not treated as persistent. This is no longer the case and has a significant impact on upgrading your application. For example consider the following domain model in a Grails 1.3.x application:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">abstract</span> class Sellable &#123;<p class="paragraph"/>&#125;
class Book <span class="java&#45;keyword">extends</span> Sellable &#123;<p class="paragraph"/>&#125;</pre></div><p class="paragraph"/>In Grails 1.3.x you would get a BOOK table and the properties from the <code>Sellable</code> class would be stored within the <code>BOOK</code> table. However, in Grails 2.x you will get a <code>SELLABLE</code> table and the default table-per-hierarchy inheritance rules apply with all properties of the <code>Book</code> stored in the <code>SELLABLE</code> table.<p class="paragraph"/>You have two options when upgrading in this scenario:
<ol>
<li>Move the abstract <code>Sellable</code> class into the src/groovy package. If the <code>Sellable</code> class is in the <code>src/groovy</code> directory it will no longer be regarded as persistent.</li>
<li>Use the <a href="http://grails.org/plugin/database-migration" target="blank">database migration</a> plugin to apply the appropriate changes to the database (typically renaming the table to the root abstract class of the inheritance tree).</li>
</ol><p class="paragraph"/><h4>Criteria Queries Default to INNER JOIN</h4><p class="paragraph"/>The previous default of LEFT JOIN for criteria queries across associations is now INNER JOIN.<p class="paragraph"/><h4>Invalid Constraints Now Thrown an Exception</h4><p class="paragraph"/>Previously if you defined a constraint on a property that doesn't exist no error would be thrown:<p class="paragraph"/><div class="code"><pre>class Person &#123;
<span class="java&#45;object">String</span> name
<span class="java&#45;keyword">static</span> constraints = &#123;
bad nullable:<span class="java&#45;keyword">false</span> // invalid property, no error thrown
&#125;
&#125;</pre></div><p class="paragraph"/>Now the above code will result in an exception<p class="paragraph"/><h4>Logging By Convention Changes</h4><p class="paragraph"/>The packages that you should use for Grails artifacts have mostly changed. In particular:
<ul class="star">
<li><code>service</code> -&#62; <code>services</code></li>
<li><code>controller</code> -&#62; <code>controllers</code></li>
<li><code>tagLib</code> -&#62; <code>taglib</code> (case change)</li>
<li><code>bootstrap</code> -&#62; <code>conf</code></li>
<li><code>dataSource</code> -&#62; <code>conf</code></li>
</ul><p class="paragraph"/>You can find out more about logging by convention in the <a href="../guide/single.html#logging" class="guide">main part</a> of the user guide, under "Configuring loggers". This change is a side-effect of injecting the <code>log</code> property into artefacts at compile time.<p class="paragraph"/><h4>jQuery Replaces Prototype</h4><p class="paragraph"/>The Protoype Javascript library has been removed from Grails core and now new Grails applications have the jQuery plugin configured by default. This will only impact you if you are using Prototype with the adaptive AJAX tags in your application, e.g. &#60;g:remoteLink/&#62; etc, because those tags will break as soon as you upgrade.<p class="paragraph"/>To resolve this issue, simply install the <a href="http://grails.org/plugin/prototype" target="blank">Prototype plugin</a> in your application. You can also remove the prototype files from your <code>web-app/js/prototype</code> directory if you want.<p class="paragraph"/><h4>The Resources Plugin</h4><p class="paragraph"/>The Resources plugin is a great new feature of Grails that allows you to manage static web resources better than before, but you do need to be aware that it adds an extra URL at <code>/static</code>. If you have access control in your application, this may mean that the static resources require an authenticated user to load them! Make sure your access rules take account of the <code>/static</code> URL.<p class="paragraph"/><h4>Controller Public Methods</h4><p class="paragraph"/>As of Grails 2.0, public methods of controllers are now treated as actions in addition to actions defined as traditional Closures. If you were relying on the use of methods for privacy controls or as helper methods then this could result in unexpected behavior. To resolve this issue you should mark all methods of your application that are not to be exposed as actions as <code>private</code> methods.<p class="paragraph"/><h4>Command Object Constraints</h4><p class="paragraph"/>As of Grails 2.0, constrained properties in command object classes are no longer nullable by default. Nullable command object properties must be explicitly configured as such in the same way that nullable persistent properties in domain classes are configured.<p class="paragraph"/><h4>The redirect Method</h4><p class="paragraph"/>The <a href="../ref/Controllers/redirect.html" class="controllers">redirect</a> method no longer commits the response. The result of this is code that relies of this behavior will break in 2.0. For example:<p class="paragraph"/><div class="code"><pre>redirect action: <span class="java&#45;quote">"next"</span>
<span class="java&#45;keyword">if</span> (response.committed) &#123;
// <span class="java&#45;keyword">do</span> something
&#125;</pre></div><p class="paragraph"/>In this case in Grails 1.3.x and below the <code>response.committed</code> property would return true and the <code>if</code> block will execute. In Grails 2.0 this is no longer the case and you should instead use the new <code>isRedirected()</code> method of the <code>request</code> object:<p class="paragraph"/><div class="code"><pre>redirect action: <span class="java&#45;quote">"next"</span>
<span class="java&#45;keyword">if</span> (request.redirected) &#123;
// <span class="java&#45;keyword">do</span> something
&#125;</pre></div><p class="paragraph"/>Another side-effect of the changes to the redirect method is that it now always uses the <code>grails.serverURL</code> configuration option if it's set. Previous versions of Grails included default values for all the environments, but when upgrading to Grails 2.0 those values more often than not break redirection. So, we recommend you remove the development and test settings for <code>grails.serverURL</code> or replace them with something appropriate for your application.<p class="paragraph"/><h4>Content Negotiation</h4><p class="paragraph"/>As of Grails 2.0 the <a href="../ref/Controllers/withFormat.html" class="controllers">withFormat</a> method of controllers no longer takes into account the request content type (dictated by the <code>CONTENT_TYPE</code> header), but instead deals exclusively with the response content type (dictated by the <code>ACCEPT</code> header or file extension). This means that if your application has code that relies on reading XML from the request using <code>withFormat</code> this will no longer work:<p class="paragraph"/><div class="code"><pre>def processBook() &#123;
withFormat &#123;
xml &#123;
// read request XML
&#125;
html &#123;
// read request parameters
&#125;
&#125;
&#125;</pre></div><p class="paragraph"/>Instead you use the <code>withFormat</code> method provided on the <code>request</code> object:<p class="paragraph"/><div class="code"><pre>def processBook() &#123;
request.withFormat &#123;
xml &#123;
// read request XML
&#125;
html &#123;
// read request parameters
&#125;
&#125;
&#125;</pre></div><p class="paragraph"/><h4>Unit Test Framework</h4><p class="paragraph"/>Grails 2 introduces a new unit testing framework that is simpler and behaves more consistently than the old one. The old framework based on the <code>GrailsUnitTestCase</code> class hierarchy is still available for backwards compatibility, but it does not work with the new annotations.<p class="paragraph"/>Migrating unit tests to the new approach is non-trivial, but recommended. Here are a set of mappings from the old style to the new:
<ol>
<li>Remove <code>extends *UnitTestCase</code> and add a <code>&#64;TestFor</code> annotation to the class if you're testing a core artifact (controller, tag lib, domain class, etc.) or <code>&#64;TestMixin(GrailsUnitTestMixin)</code> for non-core artifacts and non-artifact classes.</li>
<li>Add <code>&#64;Mock</code> annotation for domain classes that must be mocked and use <code>new MyDomain().save()</code> in place of <code>mockDomain()</code>.</li>
<li>Replace references to <code>mockRequest</code>, <code>mockResponse</code> and <code>mockParams</code> with <code>request</code>, <code>response</code> and <code>params</code>.</li>
<li>Remove references to <code>renderArgs</code> and use the <code>view</code> and <code>model</code> properties for view rendering, or <code>response.text</code> for all others.</li>
<li>Replace references to <code>redirectArgs</code> with <code>response.redirectedUrl</code>. The latter takes into account the URL mappings as is a string URL rather than a map of <code>redirect()</code> arguments.</li>
<li>The <code>mockCommandObject()</code> method is no longer needed as Grails automatically detects whether an action requires a command object or not.</li>
</ol><p class="paragraph"/>There are other differences, but these are the main ones. We recommend that you read the <a href="../guide/single.html#testing" class="guide">chapter on testing</a> thoroughly to understand everything that has changed.<p class="paragraph"/>Note that the Grails annotations don't need to be imported in your test cases to run them from the command line, but your IDE may need them. So, here are the relevant classes with packages:
<ul class="star">
<li><code>grails.test.mixin.TestFor</code></li>
<li><code>grails.test.mixin.TestMixin</code></li>
<li><code>grails.test.mixin.Mock</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.webflow/WebFlowUnitTestMixin</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>Command Line Output</h4><p class="paragraph"/>Ant output is now hidden by default to keep the noise in the terminal to a minimum. That means if you use <code>ant.echo</code> in your scripts to communicate messages to the user, we recommend switching to an alternative mechanism.<p class="paragraph"/>For status related messages, you can use the event system:<p class="paragraph"/><div class="code"><pre>event <span class="java&#45;quote">"StatusUpdate"</span>, &#91;<span class="java&#45;quote">"Some message"</span>&#93;
event <span class="java&#45;quote">"StatusFinal"</span>, &#91;<span class="java&#45;quote">"Some message"</span>&#93;
event <span class="java&#45;quote">"StatusError"</span>, &#91;<span class="java&#45;quote">"Some message"</span>&#93;</pre></div><p class="paragraph"/>For more control you can use the <code>grailsConsole</code> script variable, which gives you access to an instance of <a href="../api/grails/build/logging/GrailsConsole.html" class="api">GrailsConsole</a>. In particular, you can log information messages with <code>log()</code> or <code>info()</code>, errors and warnings with <code>error()</code> and <code>warning()</code>, and request user input with <code>userInput()</code>.<p class="paragraph"/><h4>Custom Plugin Repositories</h4><p class="paragraph"/>Many plugins have dependencies, both other plugins and straight JAR libraries. These are often located in Maven Central, the Grails core repository or the Grails Central Plugin Repository in which case applications are largely unaffected if they upgrade to Grails 2. But sometimes such dependencies are located elsewhere and Grails must be told where they can be found.<p class="paragraph"/>Due to changes in the way Grails handles the resolution of dependencies, Grails 2.0 requires you to add any such <a href="../guide/single.html#dependencyRepositories" class="guide">custom repository locations</a> to your project if an affected plugin is to install properly.<p class="paragraph"/><h4>Ivy Cache Location Has Changed</h4><p class="paragraph"/>The default Ivy cache location for Grails has changed. If the thought of yet another cache of JARs on your disk horrifies you, then you can change this in your <code>settings.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.dependency.cache.dir = <span class="java&#45;quote">"$&#123;userHome&#125;/.ivy2/cache"</span></pre></div><p class="paragraph"/>If you do this, be aware that you may run into problems running Grails 2 and earlier versions of Grails side-by-side. These problems can be avoided by excluding "xml-apis" and "commons-digester" from the inherited global dependencies in Grails 1.3 and earlier projects.<p class="paragraph"/><h4>URL Domain Properties</h4><p class="paragraph"/>If your domain model has any properties of type <code>java.net.URL</code>, they may cease to work once you upgrade to Grails 2. It seems that the default mapping of <code>URL</code> to database column has changed with the new version of Hibernate. This is a tricky problem to solve, but in the long run it's best if you migrate your <code>URL</code> properties to strings. One technique is to use the <a href="http://grails.org/plugin/database-migration" target="blank">database migration plugin</a> to add a new text column and then execute some code in <code>BootStrap</code> (using Grails 1.3.x or earlier) to fetch each row of the table as a domain instance, convert the <code>URL</code> properties to string URLs, and then write those values to the new column.<p class="paragraph"/><h4>Updated Underlying APIs</h4><p class="paragraph"/>Grails 2.0 contains updated dependencies including Servlet 3.0, Tomcat 7, Spring 3.1, Hibernate 3.6 and Groovy 1.8. This means that certain plugins and applications that depend on earlier versions of these APIs may no longer work. For example the Servlet 3.0 <code>HttpServletRequest</code> interface includes new methods, so if a plugin implements this interface for Servlet 2.5 but not for Servlet 3.0 then said plugin will break. The same can be said of any Spring interface.<p class="paragraph"/><h4>Removal of release-plugin Command</h4><p class="paragraph"/>The built in <code>release-plugin</code> command for releases plugins to the central Grails plugin repository has been removed. The new <a href="http://grails.org/plugin/release" target="blank">release</a> plugin should be used instead which provides an equivalent <code>publish-plugin</code> command.<p class="paragraph"/><h4>Removal of Deprecated Classes</h4><p class="paragraph"/>The following deprecated classes have been removed: <code>grails.web.JsonBuilder</code>, <code>grails.web.OpenRicoBuilder</code><p class="paragraph"/><h3>Upgrading from Grails 1.2.x</h3><p class="paragraph"/><h4>Plugin Repositories</h4><p class="paragraph"/>As of Grails 1.3, Grails no longer natively supports resolving plugins against secured SVN repositories. The plugin resolution mechanism in Grails 1.2 and below has been replaced by one built on <a href="http://ant.apache.org/ivy/" target="blank">Ivy</a>, the upside of which is that you can now resolve Grails plugins against Maven repositories as well as regular Grails repositories.<p class="paragraph"/>Ivy supports a much richer set of repository resolvers for resolving plugins, including support for Webdav, HTTP, SSH and FTP. See the section on <a href="http://ant.apache.org/ivy/history/trunk/settings/resolvers.html" target="blank">resolvers</a> in the Ivy docs for all the available options and the section of <a href="../guide/single.html#repositories" class="guide">plugin repositories</a> in the user guide which explains how to configure additional resolvers.<p class="paragraph"/>If you still need support for resolving plugins against secured SVN repositories then the <a href="http://code.google.com/p/ivysvn/" target="blank">IvySvn</a> project provides a set of resolvers for SVN repositories.<p class="paragraph"/><h3>Upgrading from Grails 1.1.x</h3><p class="paragraph"/><h4>Plugin paths</h4><p class="paragraph"/>In Grails 1.1.x typically a <code>pluginContextPath</code> variable was used to establish paths to plugin resources. For example:<p class="paragraph"/><div class="code"><pre>&#60;g:resource dir=<span class="java&#45;quote">"$&#123;pluginContextPath&#125;/images"</span> file=<span class="java&#45;quote">"foo.jpg"</span> /&#62;</pre></div><p class="paragraph"/>In Grails 1.2 views have been made plugin aware and this is no longer necessary:<p class="paragraph"/><div class="code"><pre>&#60;g:resource dir=<span class="java&#45;quote">"images"</span> file=<span class="java&#45;quote">"foo.jpg"</span> /&#62;</pre></div><p class="paragraph"/>Additionally the above example will no longer link to an application image from a plugin view. To do so change the above to:<p class="paragraph"/><div class="code"><pre>&#60;g:resource contextPath=<span class="java&#45;quote">""</span> dir=<span class="java&#45;quote">"images"</span> file=<span class="java&#45;quote">"foo.jpg"</span> /&#62;</pre></div><p class="paragraph"/>The same rules apply to the <a href="../ref/Tags/javascript.html" class="tags">javascript</a> and <a href="../ref/Tags/render.html" class="tags">render</a> tags.<p class="paragraph"/><h4>Tag and Body return values</h4><p class="paragraph"/>Tags no longer return <code>java.lang.String</code> instances but instead return a Grails <code>StreamCharBuffer</code> instance. The <code>StreamCharBuffer</code> class implements all the same methods as <code>String</code> but doesn't extend <code>String</code>, so code like this will break:<p class="paragraph"/><div class="code"><pre>def foo = body()
<span class="java&#45;keyword">if</span> (foo <span class="java&#45;keyword">instanceof</span> <span class="java&#45;object">String</span>) &#123;
// <span class="java&#45;keyword">do</span> something
&#125;</pre></div><p class="paragraph"/>In these cases you should check for the <code>java.lang.CharSequence</code> interface, which both <code>String</code> and <code>StreamCharBuffer</code> implement:<p class="paragraph"/><div class="code"><pre>def foo = body()
<span class="java&#45;keyword">if</span> (foo <span class="java&#45;keyword">instanceof</span> CharSequence) &#123;
// <span class="java&#45;keyword">do</span> something
&#125;</pre></div><p class="paragraph"/><h4>New JSONBuilder</h4><p class="paragraph"/>There is a new version of <code>JSONBuilder</code> which is semantically different from the one used in earlier versions of Grails. However, if your application depends on the older semantics you can still use the deprecated implementation by setting the following property to <code>true</code> in Config.groovy:<p class="paragraph"/><div class="code"><pre>grails.json.legacy.builder=<span class="java&#45;keyword">true</span></pre></div><p class="paragraph"/><h4>Validation on Flush</h4><p class="paragraph"/>Grails now executes validation routines when the underlying Hibernate session is flushed to ensure that no invalid objects are persisted. If one of your constraints (such as a custom validator) executes a query then this can cause an additional flush, resulting in a <code>StackOverflowError</code>. For example:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">static</span> constraints = &#123;
author validator: &#123; a &#45;&#62;
assert a != Book.findByTitle(<span class="java&#45;quote">"My Book"</span>).author
&#125;
&#125;</pre></div><p class="paragraph"/>The above code can lead to a <code>StackOverflowError</code> in Grails 1.2. The solution is to run the query in a new Hibernate <code>session</code> (which is recommended in general as doing Hibernate work during flushing can cause other issues):<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">static</span> constraints = &#123;
author validator: &#123; a &#45;&#62;
Book.withNewSession &#123;
assert a != Book.findByTitle(<span class="java&#45;quote">"My Book"</span>).author
&#125;
&#125;
&#125;</pre></div><p class="paragraph"/><h3>Upgrading from Grails 1.0.x</h3><p class="paragraph"/><h4>Groovy 1.6</h4><p class="paragraph"/>Grails 1.1 and above ship with Groovy 1.6 and no longer supports code compiled against Groovy 1.5. If you have a library that was compiled with Groovy 1.5 you must recompile it against Groovy 1.6 or higher before using it with Grails 1.1.<p class="paragraph"/><h4>Java 5.0</h4><p class="paragraph"/>Grails 1.1 now no longer supports JDK 1.4, if you wish to continue using Grails then it is recommended you stick to the Grails 1.0.x stream until you are able to upgrade your JDK.<p class="paragraph"/><h4>Configuration Changes</h4><p class="paragraph"/>1) The setting <code>grails.testing.reports.destDir</code> has been renamed to <code>grails.project.test.reports.dir</code> for consistency.<p class="paragraph"/>2) The following settings have been moved from <code>grails-app/conf/Config.groovy</code> to <code>grails-app/conf/BuildConfig.groovy</code>:
<ul class="star">
<ul class="star">
<li><code>grails.config.base.webXml</code></li>
<li><code>grails.project.war.file</code> (renamed from <code>grails.war.destFile</code>)</li>
<li><code>grails.war.dependencies</code></li>
<li><code>grails.war.copyToWebApp</code></li>
<li><code>grails.war.resources</code></li>
</ul></ul><p class="paragraph"/>3) The <code>grails.war.java5.dependencies</code> option is no longer supported, since Java 5.0 is now the baseline (see above).<p class="paragraph"/>4) The use of jsessionid (now considered harmful) is disabled by default. If your application requires jsessionid you can re-enable its usage by adding the following to <code>grails-app/conf/Config.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.views.enable.jsessionid=<span class="java&#45;keyword">true</span></pre></div><p class="paragraph"/>5) The syntax used to configure Log4j has changed. See the user guide section on <a href="../guide/single.html#logging" class="guide">Logging</a> for more information.<p class="paragraph"/><h4>Plugin Changes</h4><p class="paragraph"/>As of version 1.1, Grails no longer stores plugins inside your <code>PROJECT_HOME/plugins</code> directory by default. This may result in compilation errors in your application unless you either re-install all your plugins or set the following property in <code>grails-app/conf/BuildConfig.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.project.plugins.dir=<span class="java&#45;quote">"./plugins"</span></pre></div><p class="paragraph"/><h4>Script Changes</h4><p class="paragraph"/>1) If you were previously using Grails 1.0.3 or below the following syntax is no longer support for importing scripts from GRAILS_HOME:<p class="paragraph"/><div class="code"><pre>Ant.property(environment:<span class="java&#45;quote">"env"</span>)
grailsHome = Ant.antProject.properties.<span class="java&#45;quote">"env.GRAILS_HOME"</span><p class="paragraph"/>includeTargets &#60;&#60; <span class="java&#45;keyword">new</span> File(<span class="java&#45;quote">"$&#123;grailsHome&#125;/scripts/Bootstrap.groovy"</span>)</pre></div><p class="paragraph"/>Instead you should use the new <code>grailsScript</code> method to import a named script:<p class="paragraph"/><div class="code"><pre>includeTargets &#60;&#60; grailsScript(<span class="java&#45;quote">"_GrailsBootstrap"</span>)</pre></div><p class="paragraph"/>2) Due to an upgrade of Gant all references to the variable <code>Ant</code> should be changed to <code>ant</code>.<p class="paragraph"/>3) The root directory of the project is no longer on the classpath, so loading a resource like this will no longer work:<p class="paragraph"/><div class="code"><pre>def stream = getClass().classLoader.getResourceAsStream(
<span class="java&#45;quote">"grails&#45;app/conf/my&#45;config.xml"</span>)</pre></div><p class="paragraph"/>Instead you should use the Java File APIs with the <code>basedir</code> property:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">new</span> File(<span class="java&#45;quote">"$&#123;basedir&#125;/grails&#45;app/conf/my&#45;config.xml"</span>).withInputStream &#123; stream &#45;&#62;
// read the file
&#125;</pre></div><p class="paragraph"/><h4>Command Line Changes</h4><p class="paragraph"/>The <code>run-app-https</code> and <code>run-war-https</code> commands no longer exist and have been replaced by an argument to <a href="../ref/Command Line/run-app.html" class="commandLine">run-app</a>:<p class="paragraph"/><div class="code"><pre>grails run&#45;app &#45;https</pre></div><p class="paragraph"/><h4>Data Mapping Changes</h4><p class="paragraph"/>1) Enum types are now mapped using their String value rather than the ordinal value. You can revert to the old behavior by changing your mapping as follows:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">static</span> mapping = &#123;
someEnum enumType:<span class="java&#45;quote">"ordinal"</span>
&#125;</pre></div><p class="paragraph"/>2) Bidirectional one-to-one associations are now mapped with a single column on the owning side and a foreign key reference. You shouldn't need to change anything; however you should drop column on the inverse side as it contains duplicate data.<p class="paragraph"/><h4>REST Support</h4><p class="paragraph"/>Incoming XML requests are now no longer automatically parsed. To enable parsing of REST requests you can do so using the <code>parseRequest</code> argument inside a URL mapping:<p class="paragraph"/><div class="code"><pre><span class="java&#45;quote">"/book"</span>(controller:<span class="java&#45;quote">"book"</span>,parseRequest:<span class="java&#45;keyword">true</span>)</pre></div><p class="paragraph"/>Alternatively, you can use the new <code>resource</code> argument, which enables parsing by default:<p class="paragraph"/><div class="code"><pre><span class="java&#45;quote">"/book"</span>(resource:<span class="java&#45;quote">"book"</span>)</pre></div>
<a name="2.3 Creating an Application"><!-- Legacy link --></a>
<h2 id="creatingAnApplication">2.4 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 &#91;command name&#93;</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.4 A Hello World Example"><!-- Legacy link --></a>
<h2 id="aHelloWorldExample">2.5 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&#62; 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 &#60;tab&#62; to get a list of all <code>create&#45;&#42;</code> commands. Type a few more letters of the command name and then &#60;tab&#62; 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&#45;keyword">package</span> helloworld<p class="paragraph"/>class HelloController &#123;<p class="paragraph"/> def index() &#123;
render <span class="java&#45;quote">"Hello World!"</span>
&#125;
&#125;</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&#62; 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: /&#60;appname&#62;/&#60;controller&#62;/&#60;action&#62;. 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.6 Using Interactive Mode</h2>
Grails 2.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.5 Getting Set-up in an IDE"><!-- Legacy link --></a>
<h2 id="ide">2.7 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> and the <a href="http://www.jetbrains.net/confluence/display/GRVY/Groovy+Home" target="blank">JetGroovy</a> plugin offer good support for Groovy and Grails developers. Refer to the section on <a href="http://www.jetbrains.com/idea/features/groovy_grails.html" target="blank">Groovy and Grails</a> support on the JetBrains website for a feature overview.<p class="paragraph"/>To integrate Grails with IntelliJ run the following command to generate appropriate project files:<p class="paragraph"/><div class="code"><pre>grails integrate&#45;with &#45;&#45;intellij</pre></div><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="http://www.springsource.com/products/sts" target="blank">SpringSource Tool Suite</a>, which offers built in support for Grails including automatic classpath management, a GSP editor and quick access to Grails commands. See the <a href="http://www.grails.org/STS+Integration" target="blank">STS Integration</a> page for an overview.<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</h4><p class="paragraph"/>Since Grails' focus is on simplicity it is often possible to utilize more simple editors and <a href="http://macromates.com/" target="blank">TextMate</a> on the Mac has an excellent Groovy/Grails bundle available from the <a href="http://wiki.macromates.com/Main/SubversionCheckout" target="blank">Texmate bundles SVN</a>.<p class="paragraph"/>To integrate Grails with TextMate run the following command to generate appropriate project files:<p class="paragraph"/><div class="code"><pre>grails integrate&#45;with &#45;&#45;textmate</pre></div><p class="paragraph"/>Alternatively TextMate can easily open any project with its command line integration by issuing the following command from the root of your project:<p class="paragraph"/><div class="code"><pre>mate .</pre></div>
<a name="2.6 Convention over Configuration"><!-- Legacy link --></a>
<h2 id="conventionOverConfiguration">2.8 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">Gant scripts</a>.</li>
<li><code>src</code> - Supporting sources</li>
<ul class="star">
<li><code>groovy</code> - Other Groovy sources</li>
<li><code>java</code> - Other Java sources</li>
</ul>
<li><code>test</code> - <a href="../guide/single.html#testing" class="guide">Unit and integration tests</a>.</li>
</ul><p class="paragraph"/>
<a name="2.7 Running an Application"><!-- Legacy link --></a>
<h2 id="runningAnApplication">2.9 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&#45;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 &#45;Dserver.port=8090 run&#45;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&#62; run&#45;app
| Server running. Browse to http://localhost:8080/helloworld
| Application loaded in interactive mode. Type 'exit' to shutdown.
| Downloading: plugins&#45;list.xml
grails&#62; exit
| Stopping Grails server
grails&#62; run&#45;app
| Server running. Browse to http://localhost:8080/helloworld
| Application loaded in interactive mode. Type 'exit' to shutdown.
| Downloading: plugins&#45;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.8 Testing an Application"><!-- Legacy link --></a>
<h2 id="testingAnApplication">2.10 Testing an Application</h2>
The <code>create-*</code> commands in Grails automatically create unit or integration tests for you within the <code>test/unit</code> or <code>test/integration</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&#45;app</pre></div>
<a name="2.9 Deploying an Application"><!-- Legacy link --></a>
<h2 id="deployingAnApplication">2.11 Deploying an Application</h2>
Grails applications are deployed as Web Application Archives (WAR files), 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>target</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"/><blockquote class="warning">
NEVER deploy Grails using the <a href="../ref/Command Line/run-app.html" class="commandLine">run-app</a> command as this command sets Grails up for auto-reloading at runtime which has a severe performance and scalability implications
</blockquote><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>&#45;server &#45;Xmx512M &#45;XX:MaxPermSize=256m</pre></div>
<a name="2.10 Supported Java EE Containers"><!-- Legacy link --></a>
<h2 id="supportedJavaEEContainers">2.12 Supported Java EE Containers</h2>
Grails runs on any container that supports Servlet 2.5 and above and is known to work on the following specific container products:
<ul class="star">
<li>Tomcat 7</li>
<li>Tomcat 6</li>
<li>SpringSource tc Server</li>
<li>Eclipse Virgo</li>
<li>GlassFish 3</li>
<li>GlassFish 2</li>
<li>Resin 4</li>
<li>Resin 3</li>
<li>JBoss 6</li>
<li>JBoss 5</li>
<li>Jetty 7</li>
<li>Jetty 6</li>
<li>IBM Websphere 7.0</li>
<li>IBM Websphere 6.1</li>
<li>Oracle Weblogic 10.3</li>
<li>Oracle Weblogic 10</li>
<li>Oracle Weblogic 9</li>
</ul><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.11 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&#45;all Book</pre></div>
<a name="2.12 Creating Artefacts"><!-- Legacy link --></a>
<h2 id="creatingArtefacts">2.14 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&#45;domain&#45;class book</pre></div><p class="paragraph"/>This will result in the creation of a domain class at <code>grails-app/domain/Book.groovy</code> such as:<p class="paragraph"/><div class="code"><pre>class Book &#123;
&#125;</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 <a href="../ref/Command Line/interactive.html" class="commandLine">interactive</a> mode.
</blockquote>
<a name="3. Configuration"><!-- Legacy link --></a>
<h1 id="conf">3 Configuration</h1>
It may seem odd that in a framework that embraces "convention-over-configuration" that we tackle this topic now, but since what configuration there is typically a one-off, it is best to get it out the way.<p class="paragraph"/>With Grails' default settings you can actually develop an application without doing any configuration whatsoever. Grails ships with an embedded servlet container and in-memory H2 database, so there isn't even a database to set up.<p class="paragraph"/>However, typically you should configure a more robust database at some point and that is described in the following section.
<a name="3.1 Basic Configuration"><!-- Legacy link --></a>
<h2 id="config">3.1 Basic Configuration</h2>
For general configuration Grails provides a file called <code>grails-app/conf/Config.groovy</code>. This file uses Groovy's <a href="http://groovy.codehaus.org/ConfigSlurper" target="blank">ConfigSlurper</a> which is very similar to Java properties files except it is pure Groovy hence you can reuse variables and use proper Java types!<p class="paragraph"/>You can add your own configuration in here, for example:<p class="paragraph"/><div class="code"><pre>foo.bar.hello = <span class="java&#45;quote">"world"</span></pre></div><p class="paragraph"/>Then later in your application you can access these settings in one of two ways. The most common is from the <a href="../api/org/codehaus/groovy/grails/commons/GrailsApplication.html" class="api">GrailsApplication</a> object, which is available as a variable in controllers and tag libraries:<p class="paragraph"/><div class="code"><pre>class MyController &#123;
def hello() &#123;
def recipient = grailsApplication.config.foo.bar.hello<p class="paragraph"/> render <span class="java&#45;quote">"Hello $&#123;recipient&#125;"</span>
&#125;
&#125;</pre></div><p class="paragraph"/>The other way involves getting a reference to the <a href="../api/org/codehaus/groovy/grails/commons/ConfigurationHolder.html" class="api">ConfigurationHolder</a> class that holds a reference to the configuration object:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> org.codehaus.groovy.grails.commons.&#42;
&#8230;
def config = ConfigurationHolder.config
assert <span class="java&#45;quote">"world"</span> == config.foo.bar.hello</pre></div><p class="paragraph"/><blockquote class="warning">
ConfigurationHolder and ApplicationHolder are deprecated and will be removed in a future version of Grails, so it is highly preferable to access the <code>GrailsApplication</code> and config from the <code>grailsApplication</code> variable.
</blockquote><p class="paragraph"/>Within <code>Config.groovy</code> you can access several variables:<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>appName</td><td>The application name as it appears in application.properties.</td></tr><tr class="table-odd"><td>appVersion</td><td>The application version as it appears in application.properties.</td></tr><tr class="table-even"><td>grailsApplication</td><td>The <code>GrailsApplication</code> instance.</td></tr></table><p class="paragraph"/>So if you want to include the application name and version in a mail footer for example, you could do it like this:<p class="paragraph"/><div class="code"><pre>mail.footer = <span class="java&#45;quote">"Sent from &#36;&#123;appName&#125; &#36;&#123;appVersion&#125;"</span></pre></div><p class="paragraph"/>
<a name="3.1.1 Built in options"><!-- Legacy link --></a>
<h2 id="builtInOptions">3.1.1 Built in options</h2>
Grails also provides the following configuration options:
<ul class="star">
<li><code>grails.config.locations</code> - The location of properties files or addition Grails Config files that should be merged with main configuration</li>
<li><code>grails.enable.native2ascii</code> - Set this to false if you do not require native2ascii conversion of Grails i18n properties files</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 is '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></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>.</li>
</ul><p class="paragraph"/><h3>War generation</h3>
<ul class="star">
<li><code>grails.project.war.file</code> - Sets the name and location of the WAR file generated by the <a href="../ref/Command Line/war.html" class="commandLine">war</a> command</li>
<li><code>grails.war.dependencies</code> - A closure containing Ant builder syntax or a list of JAR filenames. Lets you customise what libaries are included in the WAR file.</li>
<li><code>grails.war.copyToWebApp</code> - A closure containing Ant builder syntax that is legal inside an Ant copy, for example "fileset()". Lets you control what gets included in the WAR file from the "web-app" directory.</li>
<li><code>grails.war.resources</code> - A closure containing Ant builder syntax. Allows the application to do any other other work before building the final WAR file</li>
</ul><p class="paragraph"/>For more information on using these options, see the section on <a href="../guide/single.html#deployment" class="guide">deployment</a>
<a name="3.1.2 Logging"><!-- Legacy link --></a>
<h2 id="logging">3.1.2 Logging</h2>
<h3>The Basics</h3><p class="paragraph"/>Grails uses its common configuration mechanism to provide the settings for the underlying <a href="http://logging.apache.org/log4j/1.2/index.html" target="blank">Log4j</a> log system, so all you have to do is add a <code>log4j</code> setting to the file <code>grails-app/conf/Config.groovy</code>.<p class="paragraph"/>So what does this <code>log4j</code> setting look like? Here's a basic example:<p class="paragraph"/><div class="code"><pre>log4j = &#123;
error 'org.codehaus.groovy.grails.web.servlet', // controllers
'org.codehaus.groovy.grails.web.pages' // GSP<p class="paragraph"/> warn 'org.apache.catalina'
&#125;</pre></div><p class="paragraph"/>This says that for loggers whose name starts with 'org.codehaus.groovy.grails.web.servlet' or 'org.codehaus.groovy.grails.web.pages', only messages logged at 'error' level and above will be shown. Loggers with names starting with 'org.apache.catalina' logger only show messages at the 'warn' level and above. What does that mean? First of all, you have to understand how levels work.<p class="paragraph"/><h4>Logging levels</h4><p class="paragraph"/>The are several standard logging levels, which are listed here in order of descending priority:
<ol>
<li>off</li>
<li>fatal</li>
<li>error</li>
<li>warn</li>
<li>info</li>
<li>debug</li>
<li>trace</li>
<li>all</li>
</ol><p class="paragraph"/>When you log a message, you implicitly give that message a level. For example, the method <code>log.error(msg)</code> will log a message at the 'error' level. Likewise, <code>log.debug(msg)</code> will log it at 'debug'. Each of the above levels apart from 'off' and 'all' have a corresponding log method of the same name.<p class="paragraph"/>The logging system uses that <em class="italic">message</em> level combined with the configuration for the logger (see next section) to determine whether the message gets written out. For example, if you have an 'org.example.domain' logger configured like so:<p class="paragraph"/><div class="code"><pre>warn 'org.example.domain'</pre></div><p class="paragraph"/>then messages with a level of 'warn', 'error', or 'fatal' will be written out. Messages at other levels will be ignored.<p class="paragraph"/>Before we go on to loggers, a quick note about those 'off' and 'all' levels. These are special in that they can only be used in the configuration; you can't log messages at these levels. So if you configure a logger with a level of 'off', then no messages will be written out. A level of 'all' means that you will see all messages. Simple.<p class="paragraph"/><h4>Loggers</h4><p class="paragraph"/>Loggers are fundamental to the logging system, but they are a source of some confusion. For a start, what are they? Are they shared? How do you configure them?<p class="paragraph"/>A logger is the object you log messages to, so in the call <code>log.debug(msg)</code>, <code>log</code> is a logger instance (of type <a href="http://commons.apache.org/logging/apidocs/org/apache/commons/logging/Log.html" target="blank">Log</a>). These loggers are cached and uniquely identified by name, so if two separate classes use loggers with the same name, those loggers are actually the same instance.<p class="paragraph"/>There are two main ways to get hold of a logger:
<ol>
<li>use the <code>log</code> instance injected into artifacts such as domain classes, controllers and services;</li>
<li>use the Commons Logging API directly.</li>
</ol><p class="paragraph"/>If you use the dynamic <code>log</code> property, then the name of the logger is 'grails.app.&#60;type&#62;.&#60;className&#62;', where <code>type</code> is the type of the artifact, for example 'controller' or 'service, and <code>className</code> is the fully qualified name of the artifact. For example, if you have this service:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">package</span> org.example<p class="paragraph"/>class MyService &#123;
&#8230;
&#125;</pre></div><p class="paragraph"/>then the name of the logger will be 'grails.app.service.org.example.MyService'.<p class="paragraph"/>For other classes, the typical approach is to store a logger based on the class name in a constant static field:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">package</span> org.other<p class="paragraph"/><span class="java&#45;keyword">import</span> org.apache.commons.logging.LogFactory<p class="paragraph"/>class MyClass &#123;
<span class="java&#45;keyword">private</span> <span class="java&#45;keyword">static</span> <span class="java&#45;keyword">final</span> log = LogFactory.getLog(<span class="java&#45;keyword">this</span>)
&#8230;
&#125;</pre></div><p class="paragraph"/>This will create a logger with the name 'org.other.MyClass' - note the lack of a 'grails.app.' prefix since the class isn't an artifact. You can also pass a name to the <code>getLog()</code> method, such as "myLogger", but this is less common because the logging system treats names with dots ('.') in a special way.<p class="paragraph"/><h4>Configuring loggers</h4><p class="paragraph"/>You have already seen how to configure loggers in Grails:<p class="paragraph"/><div class="code"><pre>log4j = &#123;
error 'org.codehaus.groovy.grails.web.servlet'
&#125;</pre></div><p class="paragraph"/>This example configures loggers with names starting with 'org.codehaus.groovy.grails.web.servlet' to ignore any messages sent to them at a level of 'warn' or lower. But is there a logger with this name in the application? No. So why have a configuration for it? Because the above rule applies to any logger whose name <em class="italic">begins with</em> 'org.codehaus.groovy.grails.servlet.' as well. For example, the rule applies to both the <code>org.codehaus.groovy.grails.web.servlet.GrailsDispatcherServlet</code> class and the <code>org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest</code> one.<p class="paragraph"/>In other words, loggers are hierarchical. This makes configuring them by package much simpler than it would otherwise be.<p class="paragraph"/>The most common things that you will want to capture log output from are your controllers, services, and other artifacts. Use the convention mentioned earlier to do that: <em class="italic">grails.app.&#60;artifactType&#62;.&#60;className&#62;</em> . In particular the class name must be fully qualifed, i.e. with the package if there is one:<p class="paragraph"/><div class="code"><pre>log4j = &#123;
// Set level <span class="java&#45;keyword">for</span> all application artifacts
info <span class="java&#45;quote">"grails.app"</span><p class="paragraph"/> // Set <span class="java&#45;keyword">for</span> a specific controller in the <span class="java&#45;keyword">default</span> <span class="java&#45;keyword">package</span>
debug <span class="java&#45;quote">"grails.app.controllers.YourController"</span><p class="paragraph"/> // Set <span class="java&#45;keyword">for</span> a specific domain class
debug <span class="java&#45;quote">"grails.app.domain.org.example.Book"</span><p class="paragraph"/> // Set <span class="java&#45;keyword">for</span> all taglibs
info <span class="java&#45;quote">"grails.app.taglib"</span>
&#125;</pre></div><p class="paragraph"/>The standard artifact names used in the logging configuration are:
<ul class="star">
<li><code>conf</code> - For anything under <code>grails-app/conf</code> such as <code>BootStrap.groovy</code> (but excluding filters)</li>
<li><code>filters</code> - For filters</li>
<li><code>taglib</code> - For tag libraries</li>
<li><code>services</code> - For service classes</li>
<li><code>controllers</code> - For controllers</li>
<li><code>domain</code> - For domain entities</li>
</ul><p class="paragraph"/>Grails itself generates plenty of logging information and it can sometimes be helpful to see that. Here are some useful loggers from Grails internals that you can use, especially when tracking down problems with your application:
<ul class="star">
<li><code>org.codehaus.groovy.grails.commons</code> - Core artifact information such as class loading etc.</li>
<li><code>org.codehaus.groovy.grails.web</code> - Grails web request processing</li>
<li><code>org.codehaus.groovy.grails.web.mapping</code> - URL mapping debugging</li>
<li><code>org.codehaus.groovy.grails.plugins</code> - Log plugin activity</li>
<li><code>grails.spring</code> - See what Spring beans Grails and plugins are defining</li>
<li><code>org.springframework</code> - See what Spring is doing</li>
<li><code>org.hibernate</code> - See what Hibernate is doing</li>
</ul><p class="paragraph"/>So far, we've only looked at explicit configuration of loggers. But what about all those loggers that <em class="italic">don't</em> have an explicit configuration? Are they simply ignored? The answer lies with the root logger.<p class="paragraph"/><h4>The Root Logger</h4><p class="paragraph"/>All logger objects inherit their configuration from the root logger, so if no explicit configuration is provided for a given logger, then any messages that go to that logger are subject to the rules defined for the root logger. In other words, the root logger provides the default configuration for the logging system.<p class="paragraph"/>Grails automatically configures the root logger to only handle messages at 'error' level and above, and all the messages are directed to the console (stdout for those with a C background). You can customise this behaviour by specifying a 'root' section in your logging configuration like so:<p class="paragraph"/><div class="code"><pre>log4j = &#123;
root &#123;
info()
&#125;
&#8230;
&#125;</pre></div><p class="paragraph"/>The above example configures the root logger to log messages at 'info' level and above to the default console appender. You can also configure the root logger to log to one or more named appenders (which we'll talk more about shortly):<p class="paragraph"/><div class="code"><pre>log4j = &#123;
appenders &#123;
file name:'file', file:'/<span class="java&#45;keyword">var</span>/logs/mylog.log'
&#125;
root &#123;
debug 'stdout', 'file'
&#125;
&#125;</pre></div><p class="paragraph"/>In the above example, the root logger will log to two appenders - the default 'stdout' (console) appender and a custom 'file' appender.<p class="paragraph"/>For power users there is an alternative syntax for configuring the root logger: the root <code>org.apache.log4j.Logger</code> instance is passed as an argument to the log4j closure. This lets you work with the logger directly:<p class="paragraph"/><div class="code"><pre>log4j = &#123; root &#45;&#62;
root.level = org.apache.log4j.Level.DEBUG
&#8230;
&#125;</pre></div><p class="paragraph"/>For more information on what you can do with this <code>Logger</code> instance, refer to the Log4j API documentation.<p class="paragraph"/>Those are the basics of logging pretty well covered and they are sufficient if you're happy to only send log messages to the console. But what if you want to send them to a file? How do you make sure that messages from a particular logger go to a file but not the console? These questions and more will be answered as we look into appenders.<p class="paragraph"/><h3>Appenders</h3><p class="paragraph"/>Loggers are a useful mechanism for filtering messages, but they don't physically write the messages anywhere. That's the job of the appender, of which there are various types. For example, there is the default one that writes messages to the console, another that writes them to a file, and several others. You can even create your own appender implementations&#33;<p class="paragraph"/>This diagram shows how they fit into the logging pipeline:<p class="paragraph"/><img border="0" class="center" src="../img/logging.png"></img><p class="paragraph"/>As you can see, a single logger may have several appenders attached to it. In a standard Grails configuration, the console appender named 'stdout' is attached to all loggers through the default root logger configuration. But that's the only one. Adding more appenders can be done within an 'appenders' block:<p class="paragraph"/><div class="code"><pre>log4j = &#123;
appenders &#123;
rollingFile name: <span class="java&#45;quote">"myAppender"</span>,
maxFileSize: 1024,
file: <span class="java&#45;quote">"/tmp/logs/myApp.log"</span>
&#125;
&#125;</pre></div><p class="paragraph"/>The following appenders are available by default:<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">Class</strong></th><th><strong class="bold">Description</strong></th></tr><tr class="table-odd"><td>jdbc</td><td><a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/jdbc/JDBCAppender.html" target="blank">JDBCAppender</a></td><td>Logs to a JDBC connection.</td></tr><tr class="table-even"><td>console</td><td><a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/ConsoleAppender.html" target="blank">ConsoleAppender</a></td><td>Logs to the console.</td></tr><tr class="table-odd"><td>file</td><td><a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/FileAppender.html" target="blank">FileAppender</a></td><td>Logs to a single file.</td></tr><tr class="table-even"><td>rollingFile</td><td><a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/RollingFileAppender.html" target="blank">RollingFileAppender</a></td><td>Logs to rolling files, for example a new file each day.</td></tr></table><p class="paragraph"/>Each named argument passed to an appender maps to a property of the underlying <a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Appender.html" target="blank">Appender</a> implementation. So the previous example sets the <code>name</code>, <code>maxFileSize</code> and <code>file</code> properties of the <code>RollingFileAppender</code> instance.<p class="paragraph"/>You can have as many appenders as you like - just make sure that they all have unique names. You can even have multiple instances of the same appender type, for example several file appenders that log to different files.<p class="paragraph"/>If you prefer to create the appender programmatically or if you want to use an appender implementation that's not available in the above syntax, simply declare an <code>appender</code> entry with an instance of the appender you want:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> org.apache.log4j.&#42;<p class="paragraph"/>log4j = &#123;
appenders &#123;
appender <span class="java&#45;keyword">new</span> RollingFileAppender(
name: <span class="java&#45;quote">"myAppender"</span>,
maxFileSize: 1024,
file: <span class="java&#45;quote">"/tmp/logs/myApp.log"</span>)
&#125;
&#125;</pre></div><p class="paragraph"/>This approach can be used to configure <code>JMSAppender</code>, <code>SocketAppender</code>, <code>SMTPAppender</code>, and more.<p class="paragraph"/>Once you have declared your extra appenders, you can attach them to specific loggers by passing the name as a key to one of the log level methods from the previous section:<p class="paragraph"/><div class="code"><pre>error myAppender: <span class="java&#45;quote">"grails.app.controllers.BookController"</span></pre></div><p class="paragraph"/>This will ensure that the 'grails.app.controller.BookController' logger sends log messages to 'myAppender' as well as any appenders configured for the root logger. To add more than one appender to the logger, then add them to the same level declaration:<p class="paragraph"/><div class="code"><pre>error myAppender: <span class="java&#45;quote">"grails.app.controllers.BookController"</span>,
myFileAppender: &#91;<span class="java&#45;quote">"grails.app.controllers.BookController"</span>,
<span class="java&#45;quote">"grails.app.services.BookService"</span>&#93;,
rollingFile: <span class="java&#45;quote">"grails.app.controllers.BookController"</span></pre></div><p class="paragraph"/>The above example also shows how you can configure more than one logger at a time for a given appender (<code>myFileAppender</code>) by using a list.<p class="paragraph"/>Be aware that you can only configure a single level for a logger, so if you tried this code:<p class="paragraph"/><div class="code"><pre>error myAppender: <span class="java&#45;quote">"grails.app.controllers.BookController"</span>
debug myFileAppender: <span class="java&#45;quote">"grails.app.controllers.BookController"</span>
fatal rollingFile: <span class="java&#45;quote">"grails.app.controllers.BookController"</span></pre></div><p class="paragraph"/>you'd find that only 'fatal' level messages get logged for 'grails.app.controller.BookController'. That's because the last level declared for a given logger wins. What you probably want to do is limit what level of messages an appender writes.<p class="paragraph"/>An appender that is attached to a logger configured with the 'all' level will generate a lot of logging information. That may be fine in a file, but it makes working at the console difficult. So we configure the console appender to only write out messages at 'info' level or above:<p class="paragraph"/><div class="code"><pre>log4j = &#123;
appenders &#123;
console name: <span class="java&#45;quote">"stdout"</span>, threshold: org.apache.log4j.Level.INFO
&#125;
&#125;</pre></div><p class="paragraph"/>The key here is the <code>threshold</code> argument which determines the cut-off for log messages. This argument is available for all appenders, but do note that you currently have to specify a <code>Level</code> instance - a string such as "info" will not work.<p class="paragraph"/><h3>Custom Layouts</h3><p class="paragraph"/>By default the Log4j DSL assumes that you want to use a <a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html" target="blank">PatternLayout</a>. However, there are other layouts available including:
<ul class="star">
<li><code>xml</code> - Create an XML log file</li>
<li><code>html</code> - Creates an HTML log file</li>
<li><code>simple</code> - A simple textual log</li>
<li><code>pattern</code> - A Pattern layout</li>
</ul><p class="paragraph"/>You can specify custom patterns to an appender using the <code>layout</code> setting:<p class="paragraph"/><div class="code"><pre>log4j = &#123;
appenders &#123;
console name: <span class="java&#45;quote">"customAppender"</span>,
layout: pattern(conversionPattern: <span class="java&#45;quote">"%c&#123;2&#125; %m%n"</span>)
&#125;
&#125;</pre></div><p class="paragraph"/>This also works for the built-in appender "stdout", which logs to the console:
<div class="code"><pre>log4j = &#123;
appenders &#123;
console name: <span class="java&#45;quote">"stdout"</span>,
layout: pattern(conversionPattern: <span class="java&#45;quote">"%c&#123;2&#125; %m%n"</span>)
&#125;
&#125;</pre></div><p class="paragraph"/><h3>Environment-specific configuration</h3><p class="paragraph"/>Since the logging configuration is inside <code>Config.groovy</code>, you can put it inside an environment-specific block. However, there is a problem with this approach: you have to provide the full logging configuration each time you define the <code>log4j</code> setting. In other words, you cannot selectively override parts of the configuration - it's all or nothing.<p class="paragraph"/>To get around this, the logging DSL provides its own environment blocks that you can put anywhere in the configuration:<p class="paragraph"/><div class="code"><pre>log4j = &#123;
appenders &#123;
console name: <span class="java&#45;quote">"stdout"</span>,
layout: pattern(conversionPattern: <span class="java&#45;quote">"%c&#123;2&#125; %m%n"</span>)<p class="paragraph"/> environments &#123;
production &#123;
rollingFile name: <span class="java&#45;quote">"myAppender"</span>, maxFileSize: 1024,
file: <span class="java&#45;quote">"/tmp/logs/myApp.log"</span>
&#125;
&#125;
&#125;<p class="paragraph"/> root &#123;
//&#8230;
&#125;<p class="paragraph"/> // other shared config
info <span class="java&#45;quote">"grails.app.controller"</span><p class="paragraph"/> environments &#123;
production &#123;
// Override previous setting <span class="java&#45;keyword">for</span> 'grails.app.controller'
error <span class="java&#45;quote">"grails.app.controllers"</span>
&#125;
&#125;
&#125;</pre></div><p class="paragraph"/>The one place you can't put an environment block is <em class="italic">inside</em> the <code>root</code> definition, but you can put the <code>root</code> definition inside an environment block.<p class="paragraph"/><h3>Full stacktraces</h3><p class="paragraph"/>When exceptions occur, there can be an awful lot of noise in the stacktrace from Java and Groovy internals. Grails filters these typically irrelevant details and restricts traces to non-core Grails/Groovy class packages.<p class="paragraph"/>When this happens, the full trace is always logged to the <code>StackTrace</code> logger, which by default writes its output to a file called <code>stacktrace.log</code>. As with other loggers though, you can change its behaviour in the configuration. For example if you prefer full stack traces to go to the console, add this entry:<p class="paragraph"/><div class="code"><pre>error stdout: <span class="java&#45;quote">"StackTrace"</span></pre></div><p class="paragraph"/>This won't stop Grails from attempting to create the stacktrace.log file - it just redirects where stack traces are written to. An alternative approach is to change the location of the 'stacktrace' appender's file:<p class="paragraph"/><div class="code"><pre>log4j = &#123;
appenders &#123;
rollingFile name: <span class="java&#45;quote">"stacktrace"</span>, maxFileSize: 1024,
file: <span class="java&#45;quote">"/<span class="java&#45;keyword">var</span>/tmp/logs/myApp&#45;stacktrace.log"</span>
&#125;
&#125;</pre></div><p class="paragraph"/>or, if you don't want to the 'stacktrace' appender at all, configure it as a 'null' appender:<p class="paragraph"/><div class="code"><pre>log4j = &#123;
appenders &#123;
'<span class="java&#45;keyword">null</span>' name: <span class="java&#45;quote">"stacktrace"</span>
&#125;
&#125;</pre></div><p class="paragraph"/>You can of course combine this with attaching the 'stdout' appender to the 'StackTrace' logger if you want all the output in the console.<p class="paragraph"/>Finally, you can completely disable stacktrace filtering by setting the <code>grails.full.stacktrace</code> VM property to <code>true</code>:<p class="paragraph"/><div class="code"><pre>grails &#45;Dgrails.full.stacktrace=<span class="java&#45;keyword">true</span> run&#45;app</pre></div><p class="paragraph"/><h3>Masking Request Parameters From Stacktrace Logs</h3><p class="paragraph"/>When Grails logs a stacktrace, the log message may include the names and values of all of the request parameters for the current request. To mask out the values of secure request parameters, specify the parameter names in the <code>grails.exceptionresolver.params.exclude</code> config property:<p class="paragraph"/><div class="code"><pre>grails.exceptionresolver.params.exclude = &#91;'password', 'creditCard'&#93;</pre></div><p class="paragraph"/>Request parameter logging may be turned off altogether by setting the <code>grails.exceptionresolver.logRequestParameters</code> config property to <code>false</code>. The default value is <code>true</code> when the application is running in DEVELOPMENT mode and <code>false</code> for all other modes.<p class="paragraph"/><div class="code"><pre>grails.exceptionresolver.logRequestParameters=<span class="java&#45;keyword">false</span></pre></div><p class="paragraph"/><h3>Logger inheritance</h3><p class="paragraph"/>Earlier, we mentioned that all loggers inherit from the root logger and that loggers are hierarchical based on '.'-separated terms. What this means is that unless you override a parent setting, a logger retains the level and the appenders configured for that parent. So with this configuration:<p class="paragraph"/><div class="code"><pre>log4j = &#123;
appenders &#123;
file name:'file', file:'/<span class="java&#45;keyword">var</span>/logs/mylog.log'
&#125;
root &#123;
debug 'stdout', 'file'
&#125;
&#125;</pre></div><p class="paragraph"/>all loggers in the application will have a level of 'debug' and will log to both the 'stdout' and 'file' appenders. What if you only want to log to 'stdout' for a particular logger? Change the 'additivity' for a logger in that case.<p class="paragraph"/>Additivity simply determines whether a logger inherits the configuration from its parent. If additivity is false, then its not inherited. The default for all loggers is true, i.e. they inherit the configuration. So how do you change this setting? Here's an example:<p class="paragraph"/><div class="code"><pre>log4j = &#123;
appenders &#123;
&#8230;
&#125;
root &#123;
&#8230;
&#125;<p class="paragraph"/> info additivity: <span class="java&#45;keyword">false</span>
stdout: &#91;<span class="java&#45;quote">"grails.app.controllers.BookController"</span>,
<span class="java&#45;quote">"grails.app.services.BookService"</span>&#93;
&#125;</pre></div><p class="paragraph"/>So when you specify a log level, add an 'additivity' named argument. Note that you when you specify the additivity, you must configure the loggers for a named appender. The following syntax will <em class="italic">not</em> work:<p class="paragraph"/><div class="code"><pre>info additivity: <span class="java&#45;keyword">false</span>, &#91;<span class="java&#45;quote">"grails.app.controllers.BookController"</span>,
<span class="java&#45;quote">"grails.app.services.BookService"</span>&#93;</pre></div><p class="paragraph"/><h3>Customizing stack trace printing and filtering</h3><p class="paragraph"/>Stacktraces in general and those generated when using Groovy in particular are quite verbose and contain many stack frames that aren't interesting when diagnosing problems. So Grails uses a implementation of the <code>org.codehaus.groovy.grails.exceptions.StackTraceFilterer</code> interface to filter out irrelevant stack frames. To customize the approach used for filtering, implement that interface in a class in src/groovy or src/java and register it in <code>Config.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.logging.stackTraceFiltererClass =
'com.yourcompany.yourapp.MyStackTraceFilterer'</pre></div><p class="paragraph"/>In addition, Grails customizes the display of the filtered stacktrace to make the information more readable. To customize this, implement the <code>org.codehaus.groovy.grails.exceptions.StackTracePrinter</code> interface in a class in src/groovy or src/java and register it in <code>Config.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.logging.stackTracePrinterClass =
'com.yourcompany.yourapp.MyStackTracePrinter'</pre></div><p class="paragraph"/>Finally, to render error information in the error GSP, an HTML-generating printer implementation is needed. The default implementation is <code>org.codehaus.groovy.grails.web.errors.ErrorsViewStackTracePrinter</code> and it's registered as a Spring bean. To use your own implementation, either implement the <code>org.codehaus.groovy.grails.exceptions.StackTraceFilterer</code> directly or subclass <code>ErrorsViewStackTracePrinter</code> and register it in <code>grails-app/conf/spring/resources.groovy</code> as:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> com.yourcompany.yourapp.MyErrorsViewStackTracePrinter<p class="paragraph"/>beans = &#123;<p class="paragraph"/> errorsViewStackTracePrinter(MyErrorsViewStackTracePrinter,
ref('grailsResourceLocator'))
&#125;</pre></div><p class="paragraph"/><h3>Alternative logging libraries</h3><p class="paragraph"/>By default, Grails uses Log4J to do its logging. For most people this is absolutely fine, and many users don't even care what logging library is used. But if you're not one of those and want to use an alternative, such as the <a href="http://download.oracle.com/javase/6/docs/api/index.html?java/util/logging/package-summary.html" target="blank">JDK logging package</a> or <a href="http://logback.qos.ch/" target="blank">logback</a>, you can do so by simply excluding a couple of dependencies from the global set and adding your own:<p class="paragraph"/><div class="code"><pre>grails.project.dependency.resolution = &#123;
inherits(<span class="java&#45;quote">"global"</span>) &#123;
excludes <span class="java&#45;quote">"grails&#45;plugin&#45;logging"</span>, <span class="java&#45;quote">"log4j"</span>
&#125;
&#8230;
dependencies &#123;
runtime <span class="java&#45;quote">"ch.qos.logback:logback&#45;core:0.9.29"</span>
&#8230;
&#125;
&#8230;
&#125;</pre></div><p class="paragraph"/>If you do this, you will get unfiltered, standard Java stacktraces in your log files and you won't be able to use the logging configuration DSL that's just been described. Instead, you will have to use the standard configuration mechanism for the library you choose.
<a name="3.1.3 GORM"><!-- Legacy link --></a>
<h2 id="configGORM">3.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&#45;keyword">true</span></pre></div><p class="paragraph"/>and to enable failOnError for domain classes by package:
<div class="code"><pre>grails.gorm.failOnError = &#91;'com.companyname.somepackage',
'com.companyname.someotherpackage'&#93;</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"/>
<a name="3.2 Environments"><!-- Legacy link --></a>
<h2 id="environments">3.2 Environments</h2>
<h4>Per Environment Configuration</h4><p class="paragraph"/>Grails supports the concept of per environment configuration. The <code>Config.groovy</code>, <code>DataSource.groovy</code>, and <code>BootStrap.groovy</code> files in the <code>grails-app/conf</code> directory can use per-environment configuration using the syntax provided by <a href="http://groovy.codehaus.org/ConfigSlurper." target="blank">ConfigSlurper</a> As an example consider the following default <code>DataSource</code> definition provided by Grails:<p class="paragraph"/><div class="code"><pre>dataSource &#123;
pooled = <span class="java&#45;keyword">false</span>
driverClassName = <span class="java&#45;quote">"org.h2.Driver"</span>
username = <span class="java&#45;quote">"sa"</span>
password = <span class="java&#45;quote">""</span>
&#125;
environments &#123;
development &#123;
dataSource &#123;
dbCreate = <span class="java&#45;quote">"create&#45;drop"</span>
url = <span class="java&#45;quote">"jdbc:h2:mem:devDb"</span>
&#125;
&#125;
test &#123;
dataSource &#123;
dbCreate = <span class="java&#45;quote">"update"</span>
url = <span class="java&#45;quote">"jdbc:h2:mem:testDb"</span>
&#125;
&#125;
production &#123;
dataSource &#123;
dbCreate = <span class="java&#45;quote">"update"</span>
url = <span class="java&#45;quote">"jdbc:h2:prodDb"</span>
&#125;
&#125;
&#125;</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 &#91;environment&#93; &#91;command name&#93;</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 &#45;Dgrails.env=UAT run&#45;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="../api/grails/util/Environment.html" class="api">Environment</a> class:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> grails.util.Environment<p class="paragraph"/>...<p class="paragraph"/><span class="java&#45;keyword">switch</span> (Environment.current) &#123;
<span class="java&#45;keyword">case</span> Environment.DEVELOPMENT:
configureForDevelopment()
<span class="java&#45;keyword">break</span>
<span class="java&#45;keyword">case</span> Environment.PRODUCTION:
configureForProduction()
<span class="java&#45;keyword">break</span>
&#125;</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 = &#123; ServletContext ctx &#45;&#62;
environments &#123;
production &#123;
ctx.setAttribute(<span class="java&#45;quote">"env"</span>, <span class="java&#45;quote">"prod"</span>)
&#125;
development &#123;
ctx.setAttribute(<span class="java&#45;quote">"env"</span>, <span class="java&#45;quote">"dev"</span>)
&#125;
&#125;
ctx.setAttribute(<span class="java&#45;quote">"foo"</span>, <span class="java&#45;quote">"bar"</span>)
&#125;</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 &#123;
production &#123;
// <span class="java&#45;keyword">do</span> something in production
&#125;
development &#123;
// <span class="java&#45;keyword">do</span> something only in development
&#125;
&#125;</pre></div>
<a name="3.3 The DataSource"><!-- Legacy link --></a>
<h2 id="dataSource">3.3 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 Ivy 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>grails.project.dependency.resolution = &#123;
inherits(<span class="java&#45;quote">"global"</span>)
log <span class="java&#45;quote">"warn"</span>
repositories &#123;
grailsPlugins()
grailsHome()
grailsCentral()
mavenCentral()
&#125;
dependencies &#123;
runtime 'mysql:mysql&#45;connector&#45;java:5.1.16'
&#125;
&#125;</pre></div><p class="paragraph"/>Note that the built-in <code>mavenCentral()</code> repository is included here since that's a reliable location for this library.<p class="paragraph"/>If you can't use Ivy 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>properties</code> - Extra properties to set on the DataSource bean. See the <a href="http://commons.apache.org/dbcp/api-1.2.2/org/apache/commons/dbcp/BasicDataSource.html" target="blank">Commons DBCP BasicDataSource</a> documentation.</li>
</ul><p class="paragraph"/>A typical configuration for MySQL may be something like:<p class="paragraph"/><div class="code"><pre>dataSource &#123;
pooled = <span class="java&#45;keyword">true</span>
dbCreate = <span class="java&#45;quote">"update"</span>
url = <span class="java&#45;quote">"jdbc:mysql://localhost/yourDB"</span>
driverClassName = <span class="java&#45;quote">"com.mysql.jdbc.Driver"</span>
dialect = org.hibernate.dialect.MySQL5InnoDBDialect
username = <span class="java&#45;quote">"yourUser"</span>
password = <span class="java&#45;quote">"yourPassword"</span>
&#125;</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 &#123;
<span class="java&#45;object">boolean</span> pooled = <span class="java&#45;keyword">true</span> // type declaration results in ignored local variable
&#8230;
&#125;</pre></div><p class="paragraph"/>Example of advanced configuration using extra properties:
<div class="code"><pre>dataSource &#123;
pooled = <span class="java&#45;keyword">true</span>
dbCreate = <span class="java&#45;quote">"update"</span>
url = <span class="java&#45;quote">"jdbc:mysql://localhost/yourDB"</span>
driverClassName = <span class="java&#45;quote">"com.mysql.jdbc.Driver"</span>
dialect = org.hibernate.dialect.MySQL5InnoDBDialect
username = <span class="java&#45;quote">"yourUser"</span>
password = <span class="java&#45;quote">"yourPassword"</span>
properties &#123;
maxActive = 50
maxIdle = 25
minIdle = 5
initialSize = 5
minEvictableIdleTimeMillis = 60000
timeBetweenEvictionRunsMillis = 60000
maxWait = 10000
validationQuery = <span class="java&#45;quote">"/&#42; ping &#42;/"</span>
&#125;
&#125;</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 schemaCreates 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">3.3.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 &#123;
pooled = <span class="java&#45;keyword">true</span>
driverClassName = <span class="java&#45;quote">"com.mysql.jdbc.Driver"</span>
dialect = org.hibernate.dialect.MySQL5InnoDBDialect
// other common settings here
&#125;<p class="paragraph"/>environments &#123;
production &#123;
dataSource &#123;
url = <span class="java&#45;quote">"jdbc:mysql://liveip.com/liveDb"</span>
// other environment&#45;specific settings here
&#125;
&#125;
&#125;</pre></div>
<a name="3.3.2 JNDI DataSources"><!-- Legacy link --></a>
<h2 id="JNDIDataSources">3.3.2 JNDI DataSources</h2>
<h4>Referring to a JNDI DataSource</h4><p class="paragraph"/>Most Java EE containers supply <code>DataSource</code> instances via <a href="http://www.oracle.com/technetwork/java/jndi/index.html" target="blank">Java Naming and Directory Interface</a> (JNDI). Grails supports the definition of JNDI data sources as follows:<p class="paragraph"/><div class="code"><pre>dataSource &#123;
jndiName = <span class="java&#45;quote">"java:comp/env/myDataSource"</span>
&#125;</pre></div><p class="paragraph"/>The format on the JNDI name may vary from container to container, but the way you define the <code>DataSource</code> in Grails remains the same.<p class="paragraph"/><h4>Configuring a Development time JNDI resource</h4><p class="paragraph"/>The way in which you configure JNDI data sources at development time is plugin dependent. Using the <a href="http://grails.org/plugin/tomcat" target="blank">Tomcat</a> plugin you can define JNDI resources using the <code>grails.naming.entries</code> setting in <code>grails-app/conf/Config.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.naming.entries = &#91;
<span class="java&#45;quote">"bean/MyBeanFactory"</span>: &#91;
auth: <span class="java&#45;quote">"Container"</span>,
type: <span class="java&#45;quote">"com.mycompany.MyBean"</span>,
factory: <span class="java&#45;quote">"org.apache.naming.factory.BeanFactory"</span>,
bar: <span class="java&#45;quote">"23"</span>
&#93;,
<span class="java&#45;quote">"jdbc/EmployeeDB"</span>: &#91;
type: <span class="java&#45;quote">"javax.sql.DataSource"</span>, //required
auth: <span class="java&#45;quote">"Container"</span>, // optional
description: <span class="java&#45;quote">"Data source <span class="java&#45;keyword">for</span> Foo"</span>, //optional
driverClassName: <span class="java&#45;quote">"org.h2.Driver"</span>,
url: <span class="java&#45;quote">"jdbc:h2:mem:database"</span>,
username: <span class="java&#45;quote">"dbusername"</span>,
password: <span class="java&#45;quote">"dbpassword"</span>,
maxActive: <span class="java&#45;quote">"8"</span>,
maxIdle: <span class="java&#45;quote">"4"</span>
&#93;,
<span class="java&#45;quote">"mail/session"</span>: &#91;
type: <span class="java&#45;quote">"javax.mail.Session,
auth: "</span>Container<span class="java&#45;quote">",
"</span>mail.smtp.host<span class="java&#45;quote">": "</span>localhost"
&#93;
&#93;</pre></div>
<a name="3.3.3 Automatic Database Migration"><!-- Legacy link --></a>
<h2 id="automaticDatabaseMigration">3.3.3 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 Rails-style migrations via the <a href="http://grails.org/plugin/database-migration" target="blank">Database Migration</a> plugin which can be installed by running<p class="paragraph"/><pre class="bq"><code>
grails install-plugin database-migration</code></pre><p class="paragraph"/>The plugin uses <a href="http://www.liquibase.org/" target="blank">Liquibase</a> and and provides access to all of its functionality, and also has support for GORM (for example generating a change set by comparing your domain classes to a database).
<a name="3.3.4 Transaction-aware DataSource Proxy"><!-- Legacy link --></a>
<h2 id="transactionAwareDataSourceProxy">3.3.4 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 &#123;<p class="paragraph"/> def dataSourceUnproxied
&#8230;
&#125;</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">3.3.5 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 &#123;
production &#123;
grails.serverURL = <span class="java&#45;quote">"http://www.changeme.com"</span>
grails.dbconsole.enabled = <span class="java&#45;keyword">true</span>
grails.dbconsole.urlRoot = '/admin/dbconsole'
&#125;
development &#123;
grails.serverURL = <span class="java&#45;quote">"http://localhost:8080/&#36;&#123;appName&#125;"</span>
&#125;
test &#123;
grails.serverURL = <span class="java&#45;quote">"http://localhost:8080/&#36;&#123;appName&#125;"</span>
&#125;
&#125;</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">3.3.6 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 &#123;
pooled = <span class="java&#45;keyword">true</span>
driverClassName = <span class="java&#45;quote">"org.h2.Driver"</span>
username = <span class="java&#45;quote">"sa"</span>
password = <span class="java&#45;quote">""</span>
&#125;
hibernate &#123;
cache.use_second_level_cache = <span class="java&#45;keyword">true</span>
cache.use_query_cache = <span class="java&#45;keyword">true</span>
cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider'
&#125;<p class="paragraph"/>environments &#123;
development &#123;
dataSource &#123;
dbCreate = <span class="java&#45;quote">"create&#45;drop"</span>
url = <span class="java&#45;quote">"jdbc:h2:mem:devDb"</span>
&#125;
&#125;
test &#123;
dataSource &#123;
dbCreate = <span class="java&#45;quote">"update"</span>
url = <span class="java&#45;quote">"jdbc:h2:mem:testDb"</span>
&#125;
&#125;
production &#123;
dataSource &#123;
dbCreate = <span class="java&#45;quote">"update"</span>
url = <span class="java&#45;quote">"jdbc:h2:prodDb"</span>
&#125;
&#125;
&#125;</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 another <code>dataSource</code> block (at the top level, in an environment block, or both, just like the standard <code>DataSource</code> definition) with a custom name, separated by an underscore. 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>environments &#123;
development &#123;
dataSource &#123;
dbCreate = <span class="java&#45;quote">"create&#45;drop"</span>
url = <span class="java&#45;quote">"jdbc:h2:mem:devDb"</span>
&#125;
dataSource_lookup &#123;
dialect = org.hibernate.dialect.MySQLInnoDBDialect
driverClassName = 'com.mysql.jdbc.Driver'
username = 'lookup'
password = 'secret'
url = 'jdbc:mysql://localhost/lookup'
dbCreate = 'update'
&#125;
&#125;
test &#123;
dataSource &#123;
dbCreate = <span class="java&#45;quote">"update"</span>
url = <span class="java&#45;quote">"jdbc:h2:mem:testDb"</span>
&#125;
&#125;
production &#123;
dataSource &#123;
dbCreate = <span class="java&#45;quote">"update"</span>
url = <span class="java&#45;quote">"jdbc:h2:prodDb"</span>
&#125;
dataSource_lookup &#123;
dialect = org.hibernate.dialect.Oracle10gDialect
driverClassName = 'oracle.jdbc.driver.OracleDriver'
username = 'lookup'
password = 'secret'
url = 'jdbc:oracle:thin:@localhost:1521:lookup'
dbCreate = 'update'
&#125;
&#125;
&#125;</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 &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> code<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
datasource 'lookup'
&#125;
&#125;</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 &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> code<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
datasources(&#91;'lookup', 'auditing'&#93;)
&#125;
&#125;</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 &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> code<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
datasources(&#91;'lookup', 'DEFAULT'&#93;)
&#125;
&#125;</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 &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> code<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
datasource 'ALL'
&#125;
&#125;</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 &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> code<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
datasources(&#91;'lookup', 'auditing'&#93;)
&#125;
&#125;</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)
&#8230;
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>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 &#123;<p class="paragraph"/> <span class="java&#45;keyword">static</span> datasource = 'lookup'<p class="paragraph"/> void someMethod(...) &#123;
&#8230;
&#125;
&#125;</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>XA and Two-phase Commit</h4><p class="paragraph"/>Grails has no native support for <a href="../ref/Httpssecurewikimediaorgwikipediaenwiki XO pen XA/XA.html" class="https://secure.wikimedia.org/wikipedia/en/wiki/X/Open_XA">XA</a> <code>DataSource</code>s or <a href="../ref/Httpssecurewikimediaorgwikipediaenwiki Twophasecommit/two-phase commit.html" class="https://secure.wikimedia.org/wikipedia/en/wiki/Two-phase_commit">two-phase commit</a>, but the <a href="http://grails.org/plugin/atomikos" target="blank">Atomikos plugin</a> makes it easy. See the plugin documentation for the simple changes needed in your <code>DataSource</code> definitions to reconfigure them as XA <code>DataSource</code>s.<p class="paragraph"/>
<a name="3.4 Externalized Configuration"><!-- Legacy link --></a>
<h2 id="configExternalized">3.4 Externalized Configuration</h2>
Some deployments require that configuration be sourced from more than one place and be changeable without requiring a rebuild of the application. In order to support deployment scenarios such as these the configuration can be externalized. To do so, point Grails at the locations of the configuration files that should be used by adding a <code>grails.config.locations</code> setting in <code>Config.groovy</code>, for example:<p class="paragraph"/><div class="code"><pre>grails.config.locations = &#91;
<span class="java&#45;quote">"classpath:$&#123;appName&#125;&#45;config.properties"</span>,
<span class="java&#45;quote">"classpath:$&#123;appName&#125;&#45;config.groovy"</span>,
<span class="java&#45;quote">"file:$&#123;userHome&#125;/.grails/$&#123;appName&#125;&#45;config.properties"</span>,
<span class="java&#45;quote">"file:$&#123;userHome&#125;/.grails/$&#123;appName&#125;&#45;config.groovy"</span> &#93;</pre></div><p class="paragraph"/>In the above example we're loading configuration files (both Java Properties files and <a href="http://groovy.codehaus.org/ConfigSlurper" target="blank">ConfigSlurper</a> configurations) from different places on the classpath and files located in <code>USER_HOME</code>.<p class="paragraph"/>It is also possible to load config by specifying a class that is a config script.<p class="paragraph"/><div class="code"><pre>grails.config.locations = &#91;com.my.app.MyConfig&#93;</pre></div><p class="paragraph"/>This can be useful in situations where the config is either coming from a plugin or some other part of your application. A typical use for this is re-using configuration provided by plugins across multiple applications.<p class="paragraph"/>Ultimately all configuration files get merged into the <code>config</code> property of the <a href="../api/org/codehaus/groovy/grails/commons/GrailsApplication.html" class="api">GrailsApplication</a> object and are hence obtainable from there.<p class="paragraph"/>Values that have the same name as previously defined values will overwrite the existing values, and the pointed to configuration sources are loaded in the order in which they are defined.<p class="paragraph"/><h4>Config Defaults</h4><p class="paragraph"/>The configuration values contained in the locations described by the <code>grails.config.locations</code> property will <strong class="bold">override</strong> any values defined in your application <code>Config.groovy</code> file which may not be what you want. You may want to have a set of <em class="italic">default</em> values be be loaded that can be overridden in either your application's <code>Config.groovy</code> file or in a named config location. For this you can use the <code>grails.config.defaults.locations</code> property.<p class="paragraph"/>This property supports the same values as the <code>grails.config.locations</code> property (i.e. paths to config scripts, property files or classes), but the config described by <code>grails.config.defaults.locations</code> will be loaded <em class="italic">before</em> all other values and can therefore be overridden. Some plugins use this mechanism to supply one or more sets of default configuration that you can choose to include in your application config.<p class="paragraph"/><blockquote class="note">
Grails also supports the concept of property place holders and property override configurers as defined in <a href="http://www.springframework.org." target="blank">Spring</a> For more information on these see the section on <a href="../guide/single.html#spring" class="guide">Grails and Spring</a>
</blockquote>
<a name="3.5 Versioning"><!-- Legacy link --></a>
<h2 id="versioning">3.5 Versioning</h2>
<h4>Versioning Basics</h4><p class="paragraph"/>Grails has built in support for application versioning. The version of the application is set to <code>0.1</code> when you first create an application with the <a href="../ref/Command Line/create-app.html" class="commandLine">create-app</a> command. The version is stored in the application meta data file <code>application.properties</code> in the root of the project.<p class="paragraph"/>To change the version of your application you can edit the file manually, or run the <a href="../ref/Command Line/set-version.html" class="commandLine">set-version</a> command:<p class="paragraph"/><div class="code"><pre>grails set&#45;version 0.2</pre></div><p class="paragraph"/>The version is used in various commands including the <a href="../ref/Command Line/war.html" class="commandLine">war</a> command which will append the application version to the end of the created WAR file.<p class="paragraph"/><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="../api/org/codehaus/groovy/grails/commons/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&#91;'app.version'&#93;</pre></div><p class="paragraph"/>You can retrieve the the version of Grails that is running with:<p class="paragraph"/><div class="code"><pre>def grailsVersion = grailsApplication.metadata&#91;'app.grails.version'&#93;</pre></div><p class="paragraph"/>or the <code>GrailsUtil</code> class:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> grails.util.GrailsUtil
&#8230;
def grailsVersion = GrailsUtil.grailsVersion</pre></div>
<a name="3.6 Project Documentation"><!-- Legacy link --></a>
<h2 id="docengine">3.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"/><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>&#64;monospace&#64;</pre></div><p class="paragraph"/>Italic: <em class="italic">italic</em>
<div class="code"><pre>&#95;italic&#95;</pre></div><p class="paragraph"/>Bold: <strong class="bold">bold</strong>
<div class="code"><pre>&#42;bold&#42;</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>&#33;http://grails.org/images/new/grailslogo_topNav.png&#33;</pre></div><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>&#91;SpringSource|http://www.springsource.com/&#93;</pre></div><p class="paragraph"/>or<p class="paragraph"/><div class="code"><pre><span class="java&#45;quote">"SpringSource"</span>:http://www.springsource.com/</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>&#91;Intro|guide:introduction&#93;</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>&#91;controllers|renderPDF&#93;</pre></div><p class="paragraph"/>In this case the category of the reference item is on the left hand side of the | and the name of the reference item on the right.<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>&#91;<span class="java&#45;object">String</span>|api:java.lang.<span class="java&#45;object">String</span>&#93;</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&#45;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.&#60;space&#62;Heading3
h4.&#60;space&#62;Heading4</pre></div><p class="paragraph"/>Unordered lists are defined with the use of the * character:<p class="paragraph"/><div class="code"><pre>&#42; item 1
&#42;&#42; subitem 1
&#42;&#42; subitem 2
&#42; item 2</pre></div><p class="paragraph"/>Numbered lists can be defined with the # character:<p class="paragraph"/><div class="code"><pre>&#35; 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>&#123;table&#125;
&#42;Name&#42; | &#42;<span class="java&#45;object">Number</span>&#42;
Albert | 46
Wilma | 1348
James | 12
&#123;table&#125;</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 &#123;
<span class="java&#45;object">String</span> title
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>&#123;code&#125;
class Book &#123;
<span class="java&#45;object">String</span> title
&#125;
&#123;code&#125;</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&#45;tag">&#60;hello&#62;</span>world<span class="xml&#45;tag">&#60;/hello&#62;</span></pre></div><p class="paragraph"/><div class="code"><pre>&#123;code:xml&#125;
&#60;hello&#62;world&#60;/hello&#62;
&#123;code&#125;</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>&#123;note&#125;
This is a note!
&#123;note&#125;</pre></div><p class="paragraph"/>Warning:<p class="paragraph"/><blockquote class="warning">
This is a warning!
</blockquote><p class="paragraph"/><div class="code"><pre>&#123;warning&#125;
This is a warning!
&#123;warning&#125;</pre></div>
<a name="3.7 Dependency Resolution"><!-- Legacy link --></a>
<h2 id="ivy">3.7 Dependency Resolution</h2>
Grails features a dependency resolution DSL that lets you control how plugins and JAR dependencies are resolved.<p class="paragraph"/>You specify a <code>grails.project.dependency.resolution</code> property inside the <code>grails-app/conf/BuildConfig.groovy</code> file that configures how dependencies are resolved:<p class="paragraph"/><div class="code"><pre>grails.project.dependency.resolution = &#123;
// config here
&#125;</pre></div><p class="paragraph"/>The default configuration looks like the following:<p class="paragraph"/><div class="code"><pre>grails.project.class.dir = <span class="java&#45;quote">"target/classes"</span>
grails.project.test.class.dir = <span class="java&#45;quote">"target/test&#45;classes"</span>
grails.project.test.reports.dir = <span class="java&#45;quote">"target/test&#45;reports"</span>
//grails.project.war.file = <span class="java&#45;quote">"target/&#36;&#123;appName&#125;&#45;&#36;&#123;appVersion&#125;.war"</span><p class="paragraph"/>grails.project.dependency.resolution = &#123;
// inherit Grails' <span class="java&#45;keyword">default</span> dependencies
inherits(<span class="java&#45;quote">"global"</span>) &#123;
// uncomment to disable ehcache
// excludes 'ehcache'
&#125;
log <span class="java&#45;quote">"warn"</span>
repositories &#123;
grailsPlugins()
grailsHome()
grailsCentral()<p class="paragraph"/> // uncomment these to enable remote dependency resolution
// from <span class="java&#45;keyword">public</span> Maven repositories
//mavenCentral()
//mavenLocal()
//mavenRepo <span class="java&#45;quote">"http://snapshots.repository.codehaus.org"</span>
//mavenRepo <span class="java&#45;quote">"http://repository.codehaus.org"</span>
//mavenRepo <span class="java&#45;quote">"http://download.java.net/maven/2/"</span>
//mavenRepo <span class="java&#45;quote">"http://repository.jboss.com/maven2/"</span>
&#125;
dependencies &#123;
// specify dependencies here under either 'build', 'compile',
// 'runtime', 'test' or 'provided' scopes eg.<p class="paragraph"/> // runtime 'mysql:mysql&#45;connector&#45;java:5.1.16'
&#125;<p class="paragraph"/> plugins &#123;
compile <span class="java&#45;quote">"&#58;hibernate:&#36;grailsVersion"</span>
compile <span class="java&#45;quote">"&#58;jquery:1.6.1.1"</span>
compile <span class="java&#45;quote">"&#58;resources:1.0"</span><p class="paragraph"/> build <span class="java&#45;quote">"&#58;tomcat:&#36;grailsVersion"</span>
&#125;
&#125;</pre></div><p class="paragraph"/>The details of the above will be explained in the next few sections.<p class="paragraph"/>
<a name="3.7.1 Configurations and Dependencies"><!-- Legacy link --></a>
<h2 id="configurationsAndDependencies">3.7.1 Configurations and Dependencies</h2>
Grails features five dependency resolution configurations (or 'scopes'):
<ul class="star">
<li> <code>build</code>: Dependencies for the build system only</li>
<li> <code>compile</code>: Dependencies for the compile step</li>
<li> <code>runtime</code>: Dependencies needed at runtime but not for compilation (see above)</li>
<li> <code>test</code>: Dependencies needed for testing but not at runtime (see above)</li>
<li> <code>provided</code>: Dependencies needed at development time, but not during WAR deployment</li>
</ul><p class="paragraph"/>Within the <code>dependencies</code> block you can specify a dependency that falls into one of these configurations by calling the equivalent method. For example if your application requires the MySQL driver to function at <code>runtime</code> you can specify that like this:<p class="paragraph"/><div class="code"><pre>runtime 'com.mysql:mysql&#45;connector&#45;java:5.1.16'</pre></div><p class="paragraph"/>This uses the string syntax: <code>group:name:version</code>. You can also use a Map-based syntax:<p class="paragraph"/><div class="code"><pre>runtime group: 'com.mysql',
name: 'mysql&#45;connector&#45;java',
version: '5.1.16'</pre></div><p class="paragraph"/>In Maven terminology, <code>group</code> corresponds to an artifact's <code>groupId</code> and <code>name</code> corresponds to its <code>artifactId</code>.<p class="paragraph"/>Multiple dependencies can be specified by passing multiple arguments:<p class="paragraph"/><div class="code"><pre>runtime 'com.mysql:mysql&#45;connector&#45;java:5.1.16',
'net.sf.ehcache:ehcache:1.6.1'<p class="paragraph"/>// Or<p class="paragraph"/>runtime(
&#91;group:'com.mysql', name:'mysql&#45;connector&#45;java', version:'5.1.16'&#93;,
&#91;group:'net.sf.ehcache', name:'ehcache', version:'1.6.1'&#93;
)</pre></div><p class="paragraph"/><h3>Disabling transitive dependency resolution</h3><p class="paragraph"/>By default, Grails will not only get the JARs and plugins that you declare, but it will also get their transitive dependencies. This is usually what you want, but there are occasions where you want a dependency without all its baggage. In such cases, you can disable transitive dependency resolution on a case-by-case basis:<p class="paragraph"/><div class="code"><pre>runtime('com.mysql:mysql&#45;connector&#45;java:5.1.16',
'net.sf.ehcache:ehcache:1.6.1') &#123;
transitive = <span class="java&#45;keyword">false</span>
&#125;<p class="paragraph"/>// Or
runtime group:'com.mysql',
name:'mysql&#45;connector&#45;java',
version:'5.1.16',
transitive:<span class="java&#45;keyword">false</span></pre></div><p class="paragraph"/><h3>Excluding specific transitive dependencies</h3><p class="paragraph"/>A far more common scenario is where you want the transitive dependencies, but some of them cause issues with your own dependencies or are unnecessary. For example, many Apache projects have 'commons-logging' as a transitive dependency, but it shouldn't be included in a Grails project (we use SLF4J). That's where the <code>excludes</code> option comes in:<p class="paragraph"/><div class="code"><pre>runtime('com.mysql:mysql&#45;connector&#45;java:5.1.16',
'net.sf.ehcache:ehcache:1.6.1') &#123;
excludes <span class="java&#45;quote">"xml&#45;apis"</span>, <span class="java&#45;quote">"commons&#45;logging"</span>
&#125;<p class="paragraph"/>// Or
runtime(group:'com.mysql', name:'mysql&#45;connector&#45;java', version:'5.1.16') &#123;
excludes(&#91; group: 'xml&#45;apis', name: 'xml&#45;apis'&#93;,
&#91; group: 'org.apache.httpcomponents' &#93;,
&#91; name: 'commons&#45;logging' &#93;)</pre></div><p class="paragraph"/>As you can see, you can either exclude dependencies by their artifact ID (also known as a module name) or any combination of group and artifact IDs (if you use the Map notation). You may also come across <code>exclude</code> as well, but that can only accept a single string or Map:<p class="paragraph"/><div class="code"><pre>runtime('com.mysql:mysql&#45;connector&#45;java:5.1.16',
'net.sf.ehcache:ehcache:1.6.1') &#123;
exclude <span class="java&#45;quote">"xml&#45;apis"</span>
&#125;</pre></div><p class="paragraph"/><h3>Using Ivy module configurations</h3><p class="paragraph"/>If you use Ivy module configurations and wish to depend on a specific configuration of a module, you can use the <code>dependencyConfiguration</code> method to specify the configuration to use.<p class="paragraph"/><div class="code"><pre>provided(<span class="java&#45;quote">"my.org:web&#45;service:1.0"</span>) &#123;
dependencyConfiguration <span class="java&#45;quote">"api"</span>
&#125;</pre></div><p class="paragraph"/>If the dependency configuration is not explicitly set, the configuration named <code>"default"</code> will be used (which is also the correct value for dependencies coming from Maven style repositories).<p class="paragraph"/><h3>Where are the JARs?</h3><p class="paragraph"/>With all these declarative dependencies, you may wonder where all the JARs end up. They have to go somewhere after all. By default Grails puts them into a directory, called the dependency cache, that resides on your local file system at <code>user.home</code>/.grails/ivy-cache. You can change this either via the <code>settings.groovy</code> file:<p class="paragraph"/><div class="code"><pre>grails.dependency.cache.dir = <span class="java&#45;quote">"$&#123;userHome&#125;/.my&#45;dependency&#45;cache"</span></pre></div><p class="paragraph"/>or in the dependency DSL:<p class="paragraph"/><div class="code"><pre>grails.project.dependency.resolution = &#123;
&#8230;
cacheDir <span class="java&#45;quote">"target/ivy&#45;cache"</span>
&#8230;
&#125;</pre></div><p class="paragraph"/>The <code>settings.groovy</code> option applies to all projects, so it's the preferred approach.
<a name="3.7.2 Dependency Repositories"><!-- Legacy link --></a>
<h2 id="dependencyRepositories">3.7.2 Dependency Repositories</h2>
<h4>Remote Repositories</h4><p class="paragraph"/>Initially your BuildConfig.groovy does not use any remote public Maven repositories. There is a default <code>grailsHome()</code> repository that will locate the JAR files Grails needs from your Grails installation. To use a public repository, specify it in the <code>repositories</code> block:<p class="paragraph"/><div class="code"><pre>repositories &#123;
mavenCentral()
&#125;</pre></div><p class="paragraph"/>In this case the default public Maven repository is specified. To use the SpringSource Enterprise Bundle Repository you can use the <code>ebr()</code> method:<p class="paragraph"/><div class="code"><pre>repositories &#123;
ebr()
&#125;</pre></div><p class="paragraph"/>You can also specify a specific Maven repository to use by URL:<p class="paragraph"/><div class="code"><pre>repositories &#123;
mavenRepo <span class="java&#45;quote">"http://repository.codehaus.org"</span>
&#125;</pre></div><p class="paragraph"/>and even give it a name:<p class="paragraph"/><div class="code"><pre>repositories &#123;
mavenRepo name: <span class="java&#45;quote">"Codehaus"</span>, root: <span class="java&#45;quote">"http://repository.codehaus.org"</span>
&#125;</pre></div><p class="paragraph"/>so that you can easily identify it in logs.<p class="paragraph"/><h4>Controlling Repositories Inherited from Plugins</h4><p class="paragraph"/>A plugin you have installed may define a reference to a remote repository just as an application can. By default your application will inherit this repository definition when you install the plugin.<p class="paragraph"/>If you do not wish to inherit repository definitions from plugins then you can disable repository inheritance:<p class="paragraph"/><div class="code"><pre>repositories &#123;
inherit <span class="java&#45;keyword">false</span>
&#125;</pre></div><p class="paragraph"/>In this case your application will not inherit any repository definitions from plugins and it is down to you to provide appropriate (possibly internal) repository definitions.<p class="paragraph"/><h4>Offline Mode</h4><p class="paragraph"/>There are times when it is not desirable to connect to any remote repositories (whilst working on the train for example!). In this case you can use the <code>offline</code> flag to execute Grails commands and Grails will not connect to any remote repositories:<p class="paragraph"/><div class="code"><pre>grails &#45;&#45;offline run&#45;app</pre></div><p class="paragraph"/><blockquote class="note">
Note that this command will fail if you do not have the necessary dependencies in your local Ivy cache
</blockquote><p class="paragraph"/>You can also globally configure offline mode by setting <code>grails.offline.mode</code> to <code>true</code> in <code>~/.grails/settings.groovy</code> or in your project's <code>BuildConfig.groovy</code> file:<p class="paragraph"/><div class="code"><pre>grails.offline.mode=<span class="java&#45;keyword">true</span></pre></div><p class="paragraph"/><h4>Local Resolvers</h4><p class="paragraph"/>If you do not wish to use a public Maven repository you can specify a flat file repository:<p class="paragraph"/><div class="code"><pre>repositories &#123;
flatDir name:'myRepo', dirs:'/path/to/repo'
&#125;</pre></div><p class="paragraph"/>To specify your local Maven cache (<code>~/.m2/repository</code>) as a repository:<p class="paragraph"/><div class="code"><pre>repositories &#123;
mavenLocal()
&#125;</pre></div>
<h4>Custom Resolvers</h4><p class="paragraph"/>If all else fails since Grails builds on Apache Ivy you can specify an Ivy resolver:<p class="paragraph"/><div class="code"><pre>/&#42;
&#42; Configure our resolver.
&#42;/
def libResolver = <span class="java&#45;keyword">new</span> org.apache.ivy.plugins.resolver.URLResolver()
&#91;'libraries', 'builds'&#93;.each &#123;<p class="paragraph"/> libResolver.addArtifactPattern(
<span class="java&#45;quote">"http://my.repository/&#36;&#123;it&#125;/"</span> +
<span class="java&#45;quote">"&#91;organisation&#93;/&#91;module&#93;/&#91;revision&#93;/&#91;type&#93;s/&#91;artifact&#93;.&#91;ext&#93;"</span>)<p class="paragraph"/> libResolver.addIvyPattern(
<span class="java&#45;quote">"http://my.repository/&#36;&#123;it&#125;/"</span> +
<span class="java&#45;quote">"&#91;organisation&#93;/&#91;module&#93;/&#91;revision&#93;/&#91;type&#93;s/&#91;artifact&#93;.&#91;ext&#93;"</span>)
&#125;<p class="paragraph"/>libResolver.name = <span class="java&#45;quote">"my&#45;repository"</span>
libResolver.settings = ivySettings<p class="paragraph"/>resolver libResolver</pre></div><p class="paragraph"/>It's also possible to pull dependencies from a repository using SSH. Ivy comes with a dedicated resolver that you can configure and include in your project like so:
<div class="code"><pre><span class="java&#45;keyword">import</span> org.apache.ivy.plugins.resolver.SshResolver
&#8230;
repositories &#123;
...<p class="paragraph"/> def sshResolver = <span class="java&#45;keyword">new</span> SshResolver(
name: <span class="java&#45;quote">"myRepo"</span>,
user: <span class="java&#45;quote">"username"</span>,
host: <span class="java&#45;quote">"dev.x.com"</span>,
keyFile: <span class="java&#45;keyword">new</span> File(<span class="java&#45;quote">"/home/username/.ssh/id_rsa"</span>),
m2compatible: <span class="java&#45;keyword">true</span>)<p class="paragraph"/> sshResolver.addArtifactPattern(
<span class="java&#45;quote">"/home/grails/repo/&#91;organisation&#93;/&#91;artifact&#93;/"</span> +
<span class="java&#45;quote">"&#91;revision&#93;/&#91;artifact&#93;&#45;&#91;revision&#93;.&#91;ext&#93;"</span>)<p class="paragraph"/> sshResolver.latestStrategy =
<span class="java&#45;keyword">new</span> org.apache.ivy.plugins.latest.LatestTimeStrategy()<p class="paragraph"/> sshResolver.changingPattern = <span class="java&#45;quote">".&#42;SNAPSHOT"</span><p class="paragraph"/> sshResolver.setCheckmodified(<span class="java&#45;keyword">true</span>)<p class="paragraph"/> resolver sshResolver
&#125;</pre></div><p class="paragraph"/>Download the <a href="http://www.jcraft.com/jsch/" target="blank">JSch</a> JAR and add it to Grails' classpath to use the SSH resolver. You can do this by passing the path in the Grails command line:
<div class="code"><pre>grails &#45;classpath /path/to/jsch compile|run&#45;app|etc.</pre></div><p class="paragraph"/>You can also add its path to the <code>CLASSPATH</code> environment variable but be aware this it affects many Java applications. An alternative on Unix is to create an alias for <code>grails -classpath ...</code> so that you don't have to type the extra arguments each time.<p class="paragraph"/><h4>Authentication</h4><p class="paragraph"/>If your repository requires authentication you can configure this using a <code>credentials</code> block:<p class="paragraph"/><div class="code"><pre>credentials &#123;
realm = <span class="java&#45;quote">".."</span>
host = <span class="java&#45;quote">"localhost"</span>
username = <span class="java&#45;quote">"myuser"</span>
password = <span class="java&#45;quote">"mypass"</span>
&#125;</pre></div><p class="paragraph"/>This can be placed in your <code>USER_HOME/.grails/settings.groovy</code> file using the <code>grails.project.ivy.authentication</code> setting:<p class="paragraph"/><div class="code"><pre>grails.project.ivy.authentication = &#123;
credentials &#123;
realm = <span class="java&#45;quote">".."</span>
host = <span class="java&#45;quote">"localhost"</span>
username = <span class="java&#45;quote">"myuser"</span>
password = <span class="java&#45;quote">"mypass"</span>
&#125;
&#125;</pre></div>
<a name="3.7.3 Debugging Resolution"><!-- Legacy link --></a>
<h2 id="debuggingResolution">3.7.3 Debugging Resolution</h2>
If you are having trouble getting a dependency to resolve you can enable more verbose debugging from the underlying engine using the <code>log</code> method:<p class="paragraph"/><div class="code"><pre>// log level of Ivy resolver, either 'error', 'warn',
// 'info', 'debug' or 'verbose'
log <span class="java&#45;quote">"warn"</span></pre></div><p class="paragraph"/>A common issue is that the checksums for a dependency don't match the associated JAR file, and so Ivy rejects the dependency. This helps ensure that the dependencies are valid. But for a variety of reasons some dependencies simply don't have valid checksums in the repositories, even if they are valid JARs. To get round this, you can disable Ivy's dependency checks like so:<p class="paragraph"/><div class="code"><pre>grails.project.dependency.resolution = &#123;
&#8230;
log <span class="java&#45;quote">"warn"</span>
checksums <span class="java&#45;keyword">false</span>
&#8230;
&#125;</pre></div><p class="paragraph"/>This is a global setting, so only use it if you have to.
<a name="3.7.4 Inherited Dependencies"><!-- Legacy link --></a>
<h2 id="inheritedDependencies">3.7.4 Inherited Dependencies</h2>
By default every Grails application inherits several framework dependencies. This is done through the line:<p class="paragraph"/><div class="code"><pre>inherits <span class="java&#45;quote">"global"</span></pre></div><p class="paragraph"/>Inside the <code>BuildConfig.groovy</code> file. To exclude specific inherited dependencies you use the <code>excludes</code> method:<p class="paragraph"/><div class="code"><pre>inherits(<span class="java&#45;quote">"global"</span>) &#123;
excludes <span class="java&#45;quote">"oscache"</span>, <span class="java&#45;quote">"ehcache"</span>
&#125;</pre></div>
<a name="3.7.5 Providing Default Dependencies"><!-- Legacy link --></a>
<h2 id="providingDefaultDependencies">3.7.5 Providing Default Dependencies</h2>
Most Grails applications have runtime dependencies on several jar files that are provided by the Grails framework. These include libraries like Spring, Sitemesh, Hibernate etc. When a war file is created, all of these dependencies will be included in it. But, an application may choose to exclude these jar files from the war. This is useful when the jar files will be provided by the container, as would normally be the case if multiple Grails applications are deployed to the same container.<p class="paragraph"/>The dependency resolution DSL provides a mechanism to express that all of the default dependencies will be provided by the container. This is done by invoking the <code>defaultDependenciesProvided</code> method and passing <code>true</code> as an argument:<p class="paragraph"/><div class="code"><pre>grails.project.dependency.resolution = &#123;<p class="paragraph"/> defaultDependenciesProvided <span class="java&#45;keyword">true</span> // all of the <span class="java&#45;keyword">default</span> dependencies will
// be <span class="java&#45;quote">"provided"</span> by the container<p class="paragraph"/> inherits <span class="java&#45;quote">"global"</span> // inherit Grails' <span class="java&#45;keyword">default</span> dependencies<p class="paragraph"/> repositories &#123;
grailsHome()
&#8230;
&#125;
dependencies &#123;
&#8230;
&#125;
&#125;</pre></div><p class="paragraph"/><blockquote class="note">
<code>defaultDependenciesProvided</code> must come before <code>inherits</code>, otherwise the Grails dependencies will be included in the war.
</blockquote>
<a name="3.7.11 Changing/Snapshot Dependencies"><!-- Legacy link --></a>
<h2 id="changingDependencies">3.7.6 Snapshots and Other Changing Dependencies</h2>
Typically, dependencies are constant. That is, for a given combination of <code>group</code>, <code>name</code> and <code>version</code> the jar (or plugin) that it refers to will never change. The Grails dependency management system uses this fact to cache dependencies in order to avoid having to download them from the source repository each time. Sometimes this is not desirable. For example, many developers use the convention of a <em class="italic">snapshot</em> (i.e. a dependency with a version number ending in “-SNAPSHOT”) that can change from time to time while still retaining the same version number. We call this a "changing dependency".<p class="paragraph"/>Whenever you have a changing dependency, Grails will always check the remote repository for a new version. More specifically, when a changing dependency is encountered during dependency resolution its last modified timestamp in the local cache is compared against the last modified timestamp in the dependency repositories. If the version on the remote server is deemed to be newer than the version in the local cache, the new version will be downloaded and used.<p class="paragraph"/>{info}
Be sure to read the next section on “Dependency Resolution Caching” in addition to this one as it affects changing dependencies.
{info}<p class="paragraph"/>All dependencies (jars and plugins) with a version number ending in <code>-SNAPSHOT</code> are <strong class="bold">implicitly</strong> considered to be changing by Grails. You can also explicitly specify that a dependency is changing by setting the changing flag in the dependency DSL:<p class="paragraph"/><div class="code"><pre>runtime ('org.my:lib:1.2.3') &#123;
changing = <span class="java&#45;keyword">true</span>
&#125;</pre></div><p class="paragraph"/>There is a caveat to the support for changing dependencies that you should be aware of. Grails will stop looking for newer versions of a dependency once it finds a remote repository that has the dependency.<p class="paragraph"/>Consider the following setup:<p class="paragraph"/><div class="code"><pre>grails.project.dependency.resolution = &#123;
repositories &#123;
mavenLocal()
mavenRepo <span class="java&#45;quote">"http://my.org/repo"</span>
&#125;
dependencies &#123;
compile <span class="java&#45;quote">"myorg:mylib:1.0&#45;SNAPSHOT"</span>
&#125;</pre></div><p class="paragraph"/>In this example we are using the local maven repository and a remote network maven repository. Assuming that the local Grails dependency and the local Maven cache do not contain the dependency but the remote repository does, when we perform dependency resolution the following actions will occur:
<ul class="star">
<li>maven local repository is searched, dependency not found</li>
<li>maven network repository is searched, dependency is downloaded to the cache and used</li>
</ul><p class="paragraph"/>Note that the repositories are checked in the order they are defined in the <code>BuildConfig.groovy</code> file.<p class="paragraph"/>If we perform dependency resolution again without the dependency changing on the remote server, the following will happen:
<ul class="star">
<li>maven local repository is searched, dependency not found</li>
<li>maven network repository is searched, dependency is found to be the same “age” as the version in the cache so will not be updated (i.e. downloaded)</li>
</ul><p class="paragraph"/>Later on, a new version of <code>mylib 1.0-SNAPSHOT</code> is published changing the version on the server. The next time we perform dependency resolution, the following will happen:
<ul class="star">
<li>maven local repository is searched, dependency not found</li>
<li>maven network repository is searched, dependency is found to newer than version in the cache so will be updated (i.e. downloaded to the cache)</li>
</ul><p class="paragraph"/>So far everything is working well.<p class="paragraph"/>Now we want to test some local changes to the <code>mylib</code> library. To do this we build it locally and install it to the local Maven cache (how doesn't particularly matter). The next time we perform a dependency resolution, the following will occur:
<ul class="star">
<li>maven local repository is searched, dependency is found to newer than version in the cache so will be updated (i.e. downloaded to the cache)</li>
<li>maven network repository is NOT searched as we've already found the dependency</li>
</ul><p class="paragraph"/>This is what we wanted to occur.<p class="paragraph"/>Later on, a new version of <code>mylib 1.0-SNAPSHOT</code> is published changing the version on the server. The next time we perform dependency resolution, the following will happen:
<ul class="star">
<li>maven local repository is searched, dependency is found to be the same “age” as the version in the cache so will not be updated (i.e. downloaded)</li>
<li>maven network repository is NOT searched as we've already found the dependency</li>
</ul><p class="paragraph"/>This is likely to not be the desired outcome. We are now out of sync with the latest published snapshot and will continue to keep using the version from the local maven repository.<p class="paragraph"/>The rule to remember is this: when resolving a dependency, Grails will stop searching as soon as it finds a repository that has the dependency at the specified version number. It will <strong class="bold">not</strong> continue searching all repositories trying to find a more recently modified instance.<p class="paragraph"/>To remedy this situation (i.e. build against the <em class="italic">newer</em> version of <code>mylib 1.0-SNAPSHOT</code> in the remote repository), you can either:
<ul class="star">
<li>Delete the version from the local maven repository, or</li>
<li>Reorder the repositories in the <code>BuildConfig.groovy</code> file</li>
</ul><p class="paragraph"/>Where possible, prefer deleting the version from the local maven repository. In general, when you have finished building against a locally built SNAPSHOT always try to clear it from the local maven repository.<p class="paragraph"/><blockquote class="note">
This changing dependency behaviour is an unmodifiable characteristic of the underlying dependency management system that Grails uses, Apache Ivy. It is currently not possible to have Ivy search all repositories to look for newer versions (in terms of modification date) of the same dependency (i.e. the same combination of <code>group</code>, <code>name</code> and <code>version</code>).
</blockquote>
<a name="3.7.6 Dependency Reports"><!-- Legacy link --></a>
<h2 id="dependencyReports">3.7.7 Dependency Reports</h2>
As mentioned in the previous section a Grails application consists of dependencies inherited from the framework, the plugins installed and the application dependencies itself.<p class="paragraph"/>To obtain a report of an application's dependencies you can run the <a href="../ref/Command Line/dependency-report.html" class="commandLine">dependency-report</a> command:<p class="paragraph"/><div class="code"><pre>grails dependency&#45;report</pre></div><p class="paragraph"/>By default this will generate reports in the <code>target/dependency-report</code> directory. You can specify which configuration (scope) you want a report for by passing an argument containing the configuration name:<p class="paragraph"/><div class="code"><pre>grails dependency&#45;report runtime</pre></div>
<a name="3.7.7 Plugin JAR Dependencies"><!-- Legacy link --></a>
<h2 id="pluginJARDependencies">3.7.8 Plugin JAR Dependencies</h2>
<h4>Specifying Plugin JAR dependencies</h4><p class="paragraph"/>The way in which you specify dependencies for a <a href="../guide/single.html#plugins" class="guide">plugin</a> is identical to how you specify dependencies in an application. When a plugin is installed into an application the application automatically inherits the dependencies of the plugin.<p class="paragraph"/>To define a dependency that is resolved for use with the plugin but not <em class="italic">exported</em> to the application then you can set the <code>export</code> property of the dependency:<p class="paragraph"/><div class="code"><pre>test('org.spockframework:spock&#45;core:0.5&#45;groovy&#45;1.8') &#123;
export = <span class="java&#45;keyword">false</span>
&#125;</pre></div><p class="paragraph"/>In this case the Spock dependency will be available only to the plugin and not resolved as an application dependency. Alternatively, if you're using the Map syntax:<p class="paragraph"/><div class="code"><pre>test group: 'org.spockframework', name: 'spock&#45;core',
version: '0.5&#45;groovy&#45;1.8', export: <span class="java&#45;keyword">false</span></pre></div><p class="paragraph"/><blockquote class="note">
You can use <code>exported = false</code> instead of <code>export = false</code>, but we recommend the latter because it's consistent with the Map argument.
</blockquote><p class="paragraph"/><h4>Overriding Plugin JAR Dependencies in Your Application</h4><p class="paragraph"/>If a plugin is using a JAR which conflicts with another plugin, or an application dependency then you can override how a plugin resolves its dependencies inside an application using exclusions. For example:<p class="paragraph"/><div class="code"><pre>plugins &#123;
compile(<span class="java&#45;quote">"&#58;hibernate&#58;&#36;grailsVersion"</span>) &#123;
excludes <span class="java&#45;quote">"javassist"</span>
&#125;
&#125;<p class="paragraph"/>dependencies &#123;
runtime <span class="java&#45;quote">"javassist:javassist:3.4.GA"</span>
&#125;</pre></div><p class="paragraph"/>In this case the application explicitly declares a dependency on the "hibernate" plugin and specifies an exclusion using the <code>excludes</code> method, effectively excluding the javassist library as a dependency.
<a name="3.7.8 Maven Integration"><!-- Legacy link --></a>
<h2 id="mavenIntegration">3.7.9 Maven Integration</h2>
When using the Grails Maven plugin, Grails' dependency resolution mechanics are disabled as it is assumed that you will manage dependencies with Maven's <code>pom.xml</code> file.<p class="paragraph"/>However, if you would like to continue using Grails regular commands like <a href="../ref/Command Line/run-app.html" class="commandLine">run-app</a>, <a href="../ref/Command Line/test-app.html" class="commandLine">test-app</a> and so on then you can tell Grails' command line to load dependencies from the Maven <code>pom.xml</code> file instead.<p class="paragraph"/>To do so simply add the following line to your <code>BuildConfig.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.project.dependency.resolution = &#123;
pom <span class="java&#45;keyword">true</span>
..
&#125;</pre></div><p class="paragraph"/>The line <code>pom true</code> tells Grails to parse Maven's <code>pom.xml</code> and load dependencies from there.
<a name="3.7.9 Deploying to a Maven Repository"><!-- Legacy link --></a>
<h2 id="mavendeploy">3.7.10 Deploying to a Maven Repository</h2>
If you use Maven to build your Grails project, you can use the standard Maven targets <code>mvn install</code> and <code>mvn deploy</code>.
If not, you can deploy a Grails project or plugin to a Maven repository using the <a href="http://grails.org/plugin/maven-publisher" target="blank">maven-publisher</a> plugin.<p class="paragraph"/>The plugin provides the ability to publish Grails projects and plugins to local and remote Maven repositories. There are two key additional targets added by the plugin:
<ul class="star">
<li><strong class="bold">maven-install</strong> - Installs a Grails project or plugin into your local Maven cache</li>
<li><strong class="bold">maven-deploy</strong> - Deploys a Grails project or plugin to a remote Maven repository</li>
</ul><p class="paragraph"/>By default this plugin will automatically generate a valid <code>pom.xml</code> for you unless a <code>pom.xml</code> is already present in the root of the project, in which case this <code>pom.xml</code> file will be used.<p class="paragraph"/><h4>maven-install</h4><p class="paragraph"/>The <code>maven-install</code> command will install the Grails project or plugin artifact into your local Maven cache:<p class="paragraph"/><div class="code"><pre>grails maven&#45;install</pre></div><p class="paragraph"/>In the case of plugins, the plugin zip file will be installed, whilst for application the application WAR file will be installed.<p class="paragraph"/><h4>maven-deploy</h4><p class="paragraph"/>The <code>maven-deploy</code> command will deploy a Grails project or plugin into a remote Maven repository:<p class="paragraph"/><div class="code"><pre>grails maven&#45;deploy</pre></div><p class="paragraph"/>It is assumed that you have specified the necessary <code>&#60;distributionManagement&#62;</code> configuration within a <code>pom.xml</code> or that you specify the <code>id</code> of the remote repository to deploy to:<p class="paragraph"/><div class="code"><pre>grails maven&#45;deploy &#45;&#45;repository=myRepo</pre></div><p class="paragraph"/>The <code>repository</code> argument specifies the 'id' for the repository. Configure the details of the repository specified by this 'id' within your <code>grails-app/conf/BuildConfig.groovy</code> file or in your <code>$USER_HOME/.grails/settings.groovy</code> file:<p class="paragraph"/><div class="code"><pre>grails.project.dependency.distribution = &#123;
localRepository = <span class="java&#45;quote">"/path/to/my/local"</span>
remoteRepository(id: <span class="java&#45;quote">"myRepo"</span>, url: <span class="java&#45;quote">"http://myserver/path/to/repo"</span>)
&#125;</pre></div><p class="paragraph"/>The syntax for configuring remote repositories matches the syntax from the <a href="http://maven.apache.org/ant-tasks/reference.html#remoteRepository" target="blank">remoteRepository</a> element in the Ant Maven tasks. For example the following XML:<p class="paragraph"/><div class="code"><pre>&#60;remoteRepository id=<span class="java&#45;quote">"myRepo"</span> url=<span class="java&#45;quote">"scp://localhost/www/repository"</span>&#62;
&#60;authentication username=<span class="java&#45;quote">"..."</span> privateKey=<span class="java&#45;quote">"&#36;&#123;user.home&#125;/.ssh/id_dsa"</span>/&#62;
&#60;/remoteRepository&#62;</pre></div><p class="paragraph"/>Can be expressed as:<p class="paragraph"/><div class="code"><pre>remoteRepository(id: <span class="java&#45;quote">"myRepo"</span>, url: <span class="java&#45;quote">"scp://localhost/www/repository"</span>) &#123;
authentication username: <span class="java&#45;quote">"..."</span>, privateKey: <span class="java&#45;quote">"&#36;&#123;userHome&#125;/.ssh/id_dsa"</span>
&#125;</pre></div><p class="paragraph"/>By default the plugin will try to detect the protocol to use from the URL of the repository (ie "http" from "http://.." etc.), however to specify a different protocol you can do:<p class="paragraph"/><div class="code"><pre>grails maven&#45;deploy &#45;&#45;repository=myRepo &#45;&#45;protocol=webdav</pre></div><p class="paragraph"/>The available protocols are:
<ul class="star">
<li>http</li>
<li>scp</li>
<li>scpexe</li>
<li>ftp</li>
<li>webdav</li>
</ul><p class="paragraph"/><h4>Groups, Artifacts and Versions</h4><p class="paragraph"/>Maven defines the notion of a 'groupId', 'artifactId' and a 'version'. This plugin pulls this information from the Grails project conventions or plugin descriptor.<p class="paragraph"/><h5>Projects</h5><p class="paragraph"/>For applications this plugin will use the Grails application name and version provided by Grails when generating the <code>pom.xml</code> file. To change the version you can run the <code>set-version</code> command:<p class="paragraph"/><div class="code"><pre>grails set&#45;version 0.2</pre></div><p class="paragraph"/>The Maven <code>groupId</code> will be the same as the project name, unless you specify a different one in Config.groovy:<p class="paragraph"/><div class="code"><pre>grails.project.groupId=<span class="java&#45;quote">"com.mycompany"</span></pre></div><p class="paragraph"/><h5>Plugins</h5><p class="paragraph"/>With a Grails plugin the <code>groupId</code> and <code>version</code> are taken from the following properties in the <code>GrailsPlugin.groovy</code> descriptor:<p class="paragraph"/><div class="code"><pre><span class="java&#45;object">String</span> groupId = 'myOrg'
<span class="java&#45;object">String</span> version = '0.1'</pre></div><p class="paragraph"/>The 'artifactId' is taken from the plugin name. For example if you have a plugin called <code>FeedsGrailsPlugin</code> the <code>artifactId</code> will be "feeds". If your plugin does not specify a <code>groupId</code> then this defaults to "org.grails.plugins".
<a name="3.7.10 Plugin Dependencies"><!-- Legacy link --></a>
<h2 id="pluginDependencies">3.7.11 Plugin Dependencies</h2>
As of Grails 1.3 you can declaratively specify plugins as dependencies via the dependency DSL instead of using the <a href="../ref/Command Line/install-plugin.html" class="commandLine">install-plugin</a> command:<p class="paragraph"/><div class="code"><pre>grails.project.dependency.resolution = &#123;
&#8230;
repositories &#123;
&#8230;
&#125;<p class="paragraph"/> plugins &#123;
runtime ':hibernate:1.2.1'
&#125;<p class="paragraph"/> dependencies &#123;
&#8230;
&#125;
&#8230;
&#125;</pre></div><p class="paragraph"/>If you don't specify a group id the default plugin group id of <code>org.grails.plugins</code> is used. You can specify to use the latest version of a particular plugin by using "latest.integration" as the version number:<p class="paragraph"/><div class="code"><pre>plugins &#123;
runtime ':hibernate:latest.integration'
&#125;</pre></div><p class="paragraph"/><h4>Integration vs. Release</h4><p class="paragraph"/>The "latest.integration" version label will also include resolving snapshot versions. To not include snapshot versions then use the "latest.release" label:<p class="paragraph"/><div class="code"><pre>plugins &#123;
runtime ':hibernate:latest.release'
&#125;</pre></div><p class="paragraph"/><blockquote class="note">
The "latest.release" label only works with Maven compatible repositories. If you have a regular SVN-based Grails repository then you should use "latest.integration".
</blockquote><p class="paragraph"/>And of course if you use a Maven repository with an alternative group id you can specify a group id:<p class="paragraph"/><div class="code"><pre>plugins &#123;
runtime 'mycompany:hibernate:latest.integration'
&#125;</pre></div><p class="paragraph"/><h4>Plugin Exclusions</h4><p class="paragraph"/>You can control how plugins transitively resolves both plugin and JAR dependencies using exclusions. For example:<p class="paragraph"/><div class="code"><pre>plugins &#123;
runtime(':weceem:0.8') &#123;
excludes <span class="java&#45;quote">"searchable"</span>
&#125;
&#125;</pre></div><p class="paragraph"/>Here we have defined a dependency on the "weceem" plugin which transitively depends on the "searchable" plugin. By using the <code>excludes</code> method you can tell Grails <em class="italic">not</em> to transitively install the searchable plugin. You can combine this technique to specify an alternative version of a plugin:<p class="paragraph"/><div class="code"><pre>plugins &#123;
runtime(':weceem:0.8') &#123;
excludes <span class="java&#45;quote">"searchable"</span> // excludes most recent version
&#125;
runtime ':searchable:0.5.4' // specifies a fixed searchable version
&#125;</pre></div><p class="paragraph"/>You can also completely disable transitive plugin installs, in which case no transitive dependencies will be resolved:<p class="paragraph"/><div class="code"><pre>plugins &#123;
runtime(':weceem:0.8') &#123;
transitive = <span class="java&#45;keyword">false</span>
&#125;
runtime ':searchable:0.5.4' // specifies a fixed searchable version
&#125;</pre></div>
<a name="4. The Command Line"><!-- Legacy link --></a>
<h1 id="commandLine">4 The Command Line</h1>
Grails' command line system is built on <a href="http://gant.codehaus.org/" target="blank">Gant</a> - a simple Groovy wrapper around <a href="http://ant.apache.org" target="blank">Apache Ant</a>.<p class="paragraph"/>However, Grails takes it further through the use of convention and the <code>grails</code> command. When you type:<p class="paragraph"/><div class="code"><pre>grails &#91;command name&#93;</pre></div><p class="paragraph"/>Grails searches in the following directories for Gant scripts to execute:
<ul class="star">
<li><code>USER_HOME/.grails/scripts</code></li>
<li><code>PROJECT_HOME/scripts</code></li>
<li><code>PROJECT_HOME/plugins/*/scripts</code></li>
<li><code>GRAILS_HOME/scripts</code></li>
</ul><p class="paragraph"/>Grails will also convert command names that are in lower case form such as run-app into camel case. So typing<p class="paragraph"/><div class="code"><pre>grails run&#45;app</pre></div><p class="paragraph"/>Results in a search for the following files:
<ul class="star">
<li><code>USER_HOME/.grails/scripts/RunApp.groovy</code></li>
<li><code>PROJECT_HOME/scripts/RunApp.groovy</code></li>
<li><code>PLUGINS_HOME/*/scripts/RunApp.groovy</code></li>
<li><code>GLOBAL_PLUGINS_HOME/*/scripts/RunApp.groovy</code></li>
<li><code>GRAILS_HOME/scripts/RunApp.groovy</code></li>
</ul><p class="paragraph"/>If multiple matches are found Grails will give you a choice of which one to execute.<p class="paragraph"/>When Grails executes a Gant script, it invokes the "default" target defined in that script. If there is no default, Grails will quit with an error.<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>Usage (optionals marked with &#42;):
grails &#91;environment&#93;&#42; &#91;target&#93; &#91;arguments&#93;&#42;<p class="paragraph"/>Examples:
grails dev run&#45;app
grails create&#45;app books<p class="paragraph"/>Available Targets (type grails help 'target&#45;name' <span class="java&#45;keyword">for</span> more info):
grails bootstrap
grails bug&#45;report
grails clean
grails compile
...</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"/>It's often useful to provide custom arguments to the JVM when running Grails commands, in particular with <code>run-app</code> where you may for example want to set a higher maximum heap size. The Grails command will use any JVM options provided in the general <code>JAVA_OPTS</code> environment variable, but you can also specify a Grails-specific environment variable too:<p class="paragraph"/><div class="code"><pre>export GRAILS_OPTS=<span class="java&#45;quote">"&#45;Xmx1G &#45;Xms256m &#45;XX:MaxPermSize=256m"</span>
grails run&#45;app</pre></div><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>&#45;&#45;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 &#45;&#45;non&#45;interactive</pre></div>
<h2 id="interactiveMode">4.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 &#33; (bang) commands, you get file path auto completion - ideal for external commands that operate on the file system such as 'ls', 'cat', 'git', etc.
<a name="4.1 Creating Gant Scripts"><!-- Legacy link --></a>
<h2 id="creatingGantScripts">4.2 Creating Gant Scripts</h2>
You can create your own Gant 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&#45;script compile&#45;sources</pre></div><p class="paragraph"/>Will create a script called <code>scripts/CompileSources.groovy</code>. A Gant script itself is similar to a regular Groovy script except that it supports the concept of "targets" and dependencies between them:<p class="paragraph"/><div class="code"><pre>target(<span class="java&#45;keyword">default</span>:<span class="java&#45;quote">"The <span class="java&#45;keyword">default</span> target is the one that gets executed by Grails"</span>) &#123;
depends(clean, compile)
&#125;<p class="paragraph"/>target(clean:<span class="java&#45;quote">"Clean out things"</span>) &#123;
ant.delete(dir:<span class="java&#45;quote">"output"</span>)
&#125;<p class="paragraph"/>target(compile:<span class="java&#45;quote">"Compile some sources"</span>) &#123;
ant.mkdir(dir:<span class="java&#45;quote">"mkdir"</span>)
ant.javac(srcdir:<span class="java&#45;quote">"src/java"</span>, destdir:<span class="java&#45;quote">"output"</span>)
&#125;</pre></div><p class="paragraph"/>As demonstrated in the script above, there is an implicit <code>ant</code> variable (an instance of <code>groovy.util.AntBuilder</code>) that allows access to the <a href="http://ant.apache.org/manual/index.html" target="blank">Apache Ant API</a>.
<blockquote class="note">
In previous versions of Grails (1.0.3 and below), the variable was <code>Ant</code>, i.e. with a capital first letter.
</blockquote><p class="paragraph"/>You can also "depend" on other targets using the <code>depends</code> method demonstrated in the <code>default</code> target above.<p class="paragraph"/><h3>The default target</h3><p class="paragraph"/>In the example above, we specified a target with the explicit name "default". This is one way of defining the default target for a script. An alternative approach is to use the <code>setDefaultTarget()</code> method:<p class="paragraph"/><div class="code"><pre>target(<span class="java&#45;quote">"clean&#45;compile"</span>: <span class="java&#45;quote">"Performs a clean compilation on the app source"</span>) &#123;
depends(clean, compile)
&#125;<p class="paragraph"/>target(clean:<span class="java&#45;quote">"Clean out things"</span>) &#123;
ant.delete(dir:<span class="java&#45;quote">"output"</span>)
&#125;<p class="paragraph"/>target(compile:<span class="java&#45;quote">"Compile some sources"</span>) &#123;
ant.mkdir(dir:<span class="java&#45;quote">"mkdir"</span>)
ant.javac(srcdir:<span class="java&#45;quote">"src/java"</span>, destdir:<span class="java&#45;quote">"output"</span>)
&#125;<p class="paragraph"/>setDefaultTarget(<span class="java&#45;quote">"clean&#45;compile"</span>)</pre></div><p class="paragraph"/>This lets you call the default target directly from other scripts if you wish. Also, although we have put the call to <code>setDefaultTarget()</code> at the end of the script in this example, it can go anywhere as long as it comes <em class="italic">after</em> the target it refers to ("clean-compile" in this case).<p class="paragraph"/>Which approach is better? To be honest, you can use whichever you prefer - there don't seem to be any major advantages in either case. One thing we would say is that if you want to allow other scripts to call your "default" target, you should move it into a shared script that doesn't have a default target at all. We'll talk some more about this in the next section.
<a name="4.2 Re-using Grails scripts"><!-- Legacy link --></a>
<h2 id="reusingGrailsScripts">4.3 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). Of particular use are the <a href="../ref/Command Line/compile.html" class="commandLine">compile</a>, <a href="../ref/Command Line/package.html" class="commandLine">package</a> and <a href="../ref/Command Line/bootstrap.html" class="commandLine">bootstrap</a> scripts.<p class="paragraph"/>The <a href="../ref/Command Line/bootstrap.html" class="commandLine">bootstrap</a> script for example lets you bootstrap a Spring <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/ApplicationContext.html" class="api">ApplicationContext</a> instance to get access to the data source and so on (the integration tests use this):<p class="paragraph"/><div class="code"><pre>includeTargets &#60;&#60; grailsScript(<span class="java&#45;quote">"_GrailsBootstrap"</span>)<p class="paragraph"/>target ('<span class="java&#45;keyword">default</span>': <span class="java&#45;quote">"Database stuff"</span>) &#123;
depends(configureProxy, packageApp, classpath, loadApp, configureApp)<p class="paragraph"/> Connection c
<span class="java&#45;keyword">try</span> &#123;
c = appCtx.getBean('dataSource').getConnection()
// <span class="java&#45;keyword">do</span> something with connection
&#125;
<span class="java&#45;keyword">finally</span> &#123;
c?.close()
&#125;
&#125;</pre></div><p class="paragraph"/><h3>Pulling in targets from other scripts</h3><p class="paragraph"/>Gant lets you pull in all targets (except "default") from another Gant script. You can then depend upon or invoke those targets as if they had been defined in the current script. The mechanism for doing this is the <code>includeTargets</code> property. Simply "append" a file or class to it using the left-shift operator:
<div class="code"><pre>includeTargets &#60;&#60; <span class="java&#45;keyword">new</span> File(<span class="java&#45;quote">"/path/to/my/script.groovy"</span>)
includeTargets &#60;&#60; gant.tools.Ivy</pre></div>
Don't worry too much about the syntax using a class, it's quite specialised. If you're interested, look into the Gant documentation.<p class="paragraph"/><h3>Core Grails targets</h3><p class="paragraph"/>As you saw in the example at the beginning of this section, you use neither the File- nor the class-based syntax for <code>includeTargets</code> when including core Grails targets. Instead, you should use the special <code>grailsScript()</code> method that is provided by the Grails command launcher (note that this is not available in normal Gant scripts, just Grails ones).<p class="paragraph"/>The syntax for the <code>grailsScript()</code> method is pretty straightforward: simply pass it the name of the Grails script to include, without any path information. Here is a list of Grails scripts that you could reuse:
<table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th><strong class="bold">Script</strong></th><th><strong class="bold">Description</strong></th></tr><tr class="table-odd"><td>&#95;GrailsSettings</td><td>You really should include this! Fortunately, it is included automatically by all other Grails scripts except &#95;GrailsProxy, so you usually don't have to include it explicitly.</td></tr><tr class="table-even"><td>&#95;GrailsEvents</td><td>Include this to fire events. Adds an <code>event(String eventName, List args)</code> method. Again, included by almost all other Grails scripts.</td></tr><tr class="table-odd"><td>&#95;GrailsClasspath</td><td>Configures compilation, test, and runtime classpaths. If you want to use or play with them, include this script. Again, included by almost all other Grails scripts.</td></tr><tr class="table-even"><td>&#95;GrailsProxy</td><td>If you don't have direct access to the internet and use a proxy, include this script to configure access through your proxy.</td></tr><tr class="table-odd"><td>&#95;GrailsArgParsing</td><td>Provides a <code>parseArguments</code> target that does what it says on the tin: parses the arguments provided by the user when they run your script. Adds them to the <code>argsMap</code> property.</td></tr><tr class="table-even"><td>&#95;GrailsTest</td><td>Contains all the shared test code. Useful if you want to add any extra tests.</td></tr><tr class="table-odd"><td>&#95;GrailsRun</td><td>Provides all you need to run the application in the configured servlet container, either normally (<code>runApp</code>/<code>runAppHttps</code>) or from a WAR file (<code>runWar</code>/<code>runWarHttps</code>).</td></tr></table><p class="paragraph"/>There are many more scripts provided by Grails, so it is worth digging into the scripts themselves to find out what kind of targets are available. Anything that starts with an "&#95;" is designed for reuse.<p class="paragraph"/><h3>Script architecture</h3><p class="paragraph"/>You maybe wondering what those underscores are doing in the names of the Grails scripts. That is Grails' way of determining that a script is <em class="italic">internal</em> , or in other words that it has not corresponding "command". So you can't run "grails &#95;grails-settings" for example. That is also why they don't have a default target.<p class="paragraph"/>Internal scripts are all about code sharing and reuse. In fact, we recommend you take a similar approach in your own scripts: put all your targets into an internal script that can be easily shared, and provide simple command scripts that parse any command line arguments and delegate to the targets in the internal script. For example if you have a script that runs some functional tests, you can split it like this:
<div class="code"><pre>./scripts/FunctionalTests.groovy:<p class="paragraph"/>includeTargets &#60;&#60; <span class="java&#45;keyword">new</span> File(<span class="java&#45;quote">"$&#123;basedir&#125;/scripts/_FunctionalTests.groovy"</span>)<p class="paragraph"/>target(<span class="java&#45;keyword">default</span>: <span class="java&#45;quote">"Runs the functional tests <span class="java&#45;keyword">for</span> <span class="java&#45;keyword">this</span> project."</span>) &#123;
depends(runFunctionalTests)
&#125;<p class="paragraph"/>./scripts/_FunctionalTests.groovy:<p class="paragraph"/>includeTargets &#60;&#60; grailsScript(<span class="java&#45;quote">"_GrailsTest"</span>)<p class="paragraph"/>target(runFunctionalTests: <span class="java&#45;quote">"Run functional tests."</span>) &#123;
depends(...)
&#8230;
&#125;</pre></div><p class="paragraph"/>Here are a few general guidelines on writing scripts:
<ul class="star">
<li>Split scripts into a "command" script and an internal one.</li>
<li>Put the bulk of the implementation in the internal script.</li>
<li>Put argument parsing into the "command" script.</li>
<li>To pass arguments to a target, create some script variables and initialise them before calling the target.</li>
<li>Avoid name clashes by using closures assigned to script variables instead of targets. You can then pass arguments direct to the closures.</li>
</ul><p class="paragraph"/>
<a name="4.3 Hooking into Events"><!-- Legacy link --></a>
<h2 id="events">4.4 Hooking into Events</h2>
Grails provides the ability to hook into scripting events. These are events triggered during execution of Grails target and plugin scripts.<p class="paragraph"/>The mechanism is deliberately simple and loosely specified. The list of possible events is not fixed in any way, so it is possible to hook into events triggered by plugin scripts, for which there is no equivalent event in the core target scripts.<p class="paragraph"/><h4>Defining event handlers</h4><p class="paragraph"/>Event handlers are defined in scripts called <code>_Events.groovy</code>. Grails searches for these scripts in the following locations:
<ul class="star">
<li><code>USER_HOME/.grails/scripts</code> - user-specific event handlers</li>
<li><code>PROJECT_HOME/scripts</code> - applicaton-specific event handlers</li>
<li><code>PLUGINS_HOME/*/scripts</code> - plugin-specific event handlers</li>
<li><code>GLOBAL_PLUGINS_HOME/*/scripts</code> - event handlers provided by global plugins</li>
</ul><p class="paragraph"/>Whenever an event is fired, <em class="italic">all</em> the registered handlers for that event are executed. Note that the registration of handlers is performed automatically by Grails, so you just need to declare them in the relevant <code>_Events.groovy</code> file.<p class="paragraph"/>Event handlers are blocks defined in <code>_Events.groovy</code>, with a name beginning with "event". The following example can be put in your /scripts directory to demonstrate the feature:<p class="paragraph"/><div class="code"><pre>eventCreatedArtefact = &#123; type, name &#45;&#62;
println <span class="java&#45;quote">"Created $type $name"</span>
&#125;<p class="paragraph"/>eventStatusUpdate = &#123; msg &#45;&#62;
println msg
&#125;<p class="paragraph"/>eventStatusFinal = &#123; msg &#45;&#62;
println msg
&#125;</pre></div><p class="paragraph"/>You can see here the three handlers <code>eventCreatedArtefact</code>, <code>eventStatusUpdate</code>, <code>eventStatusFinal</code>. Grails provides some standard events, which are documented in the command line reference guide. For example the <a href="../ref/Command Line/compile.html" class="commandLine">compile</a> command fires the following events:
<ul class="star">
<li><code>CompileStart</code> - Called when compilation starts, passing the kind of compile - source or tests</li>
<li><code>CompileEnd</code> - Called when compilation is finished, passing the kind of compile - source or tests</li>
</ul><p class="paragraph"/><h4>Triggering events</h4><p class="paragraph"/>To trigger an event simply include the Init.groovy script and call the event() closure:<p class="paragraph"/><div class="code"><pre>includeTargets &#60;&#60; grailsScript(<span class="java&#45;quote">"_GrailsEvents"</span>)<p class="paragraph"/>event(<span class="java&#45;quote">"StatusFinal"</span>, &#91;<span class="java&#45;quote">"Super duper plugin action complete!"</span>&#93;)</pre></div><p class="paragraph"/><h4>Common Events</h4><p class="paragraph"/>Below is a table of some of the common events that can be leveraged:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Event</th><th>Parameters</th><th>Description</th></tr><tr class="table-odd"><td>StatusUpdate</td><td>message</td><td>Passed a string indicating current script status/progress</td></tr><tr class="table-even"><td>StatusError</td><td>message</td><td>Passed a string indicating an error message from the current script</td></tr><tr class="table-odd"><td>StatusFinal</td><td>message</td><td>Passed a string indicating the final script status message, i.e. when completing a target, even if the target does not exit the scripting environment</td></tr><tr class="table-even"><td>CreatedArtefact</td><td>artefactType,artefactName</td><td>Called when a create-xxxx script has completed and created an artefact</td></tr><tr class="table-odd"><td>CreatedFile</td><td>fileName</td><td>Called whenever a project source filed is created, not including files constantly managed by Grails</td></tr><tr class="table-even"><td>Exiting</td><td>returnCode</td><td>Called when the scripting environment is about to exit cleanly</td></tr><tr class="table-odd"><td>PluginInstalled</td><td>pluginName</td><td>Called after a plugin has been installed</td></tr><tr class="table-even"><td>CompileStart</td><td>kind</td><td>Called when compilation starts, passing the kind of compile - source or tests</td></tr><tr class="table-odd"><td>CompileEnd</td><td>kind</td><td>Called when compilation is finished, passing the kind of compile - source or tests</td></tr><tr class="table-even"><td>DocStart</td><td>kind</td><td>Called when documentation generation is about to start - javadoc or groovydoc</td></tr><tr class="table-odd"><td>DocEnd</td><td>kind</td><td>Called when documentation generation has ended - javadoc or groovydoc</td></tr><tr class="table-even"><td>SetClasspath</td><td>rootLoader</td><td>Called during classpath initialization so plugins can augment the classpath with rootLoader.addURL(...). Note that this augments the classpath <strong class="bold">after</strong> event scripts are loaded so you cannot use this to load a class that your event script needs to import, although you can do this if you load the class by name.</td></tr><tr class="table-odd"><td>PackagingEnd</td><td>none</td><td>Called at the end of packaging (which is called prior to the Tomcat server being started and after web.xml is generated)</td></tr></table>
<a name="4.4 Customising the build"><!-- Legacy link --></a>
<h2 id="buildCustomising">4.5 Customising the build</h2>
Grails is most definitely an opinionated framework and it prefers convention to configuration, but this doesn't mean you <em class="italic">can't</em> configure it. In this section, we look at how you can influence and modify the standard Grails build.<p class="paragraph"/><h3>The defaults</h3><p class="paragraph"/>The core of the Grails build configuration is the <code>grails.util.BuildSettings</code> class, which contains quite a bit of useful information. It controls where classes are compiled to, what dependencies the application has, and other such settings.<p class="paragraph"/>Here is a selection of the configuration options and their default values:
<table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th><strong class="bold">Property</strong></th><th><strong class="bold">Config option</strong></th><th><strong class="bold">Default value</strong></th></tr><tr class="table-odd"><td>grailsWorkDir</td><td>grails.work.dir</td><td>$USER_HOME/.grails/&#60;grailsVersion&#62;</td></tr><tr class="table-even"><td>projectWorkDir</td><td>grails.project.work.dir</td><td>&#60;grailsWorkDir&#62;/projects/&#60;baseDirName&#62;</td></tr><tr class="table-odd"><td>classesDir</td><td>grails.project.class.dir</td><td>&#60;projectWorkDir&#62;/classes</td></tr><tr class="table-even"><td>testClassesDir</td><td>grails.project.test.class.dir</td><td>&#60;projectWorkDir&#62;/test-classes</td></tr><tr class="table-odd"><td>testReportsDir</td><td>grails.project.test.reports.dir</td><td>&#60;projectWorkDir&#62;/test/reports</td></tr><tr class="table-even"><td>resourcesDir</td><td>grails.project.resource.dir</td><td>&#60;projectWorkDir&#62;/resources</td></tr><tr class="table-odd"><td>projectPluginsDir</td><td>grails.project.plugins.dir</td><td>&#60;projectWorkDir&#62;/plugins</td></tr><tr class="table-even"><td>globalPluginsDir</td><td>grails.global.plugins.dir</td><td>&#60;grailsWorkDir&#62;/global-plugins</td></tr><tr class="table-odd"><td>verboseCompile</td><td>grails.project.compile.verbose</td><td><code>false</code></td></tr></table><p class="paragraph"/>The <code>BuildSettings</code> class has some other properties too, but they should be treated as read-only:
<table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th><strong class="bold">Property</strong></th><th><strong class="bold">Description</strong></th></tr><tr class="table-odd"><td>baseDir</td><td>The location of the project.</td></tr><tr class="table-even"><td>userHome</td><td>The user's home directory.</td></tr><tr class="table-odd"><td>grailsHome</td><td>The location of the Grails installation in use (may be <code>null</code>).</td></tr><tr class="table-even"><td>grailsVersion</td><td>The version of Grails being used by the project.</td></tr><tr class="table-odd"><td>grailsEnv</td><td>The current Grails environment.</td></tr><tr class="table-even"><td>compileDependencies</td><td>A list of compile-time project dependencies as <code>File</code> instances.</td></tr><tr class="table-odd"><td>testDependencies</td><td>A list of test-time project dependencies as <code>File</code> instances.</td></tr><tr class="table-even"><td>runtimeDependencies</td><td>A list of runtime-time project dependencies as <code>File</code> instances.</td></tr></table><p class="paragraph"/>Of course, these properties aren't much good if you can't get hold of them. Fortunately that's easy to do: an instance of <code>BuildSettings</code> is available to your scripts as the <code>grailsSettings</code> script variable. You can also access it from your code by using the <code>grails.util.BuildSettingsHolder</code> class, but this isn't recommended.<p class="paragraph"/><h3>Overriding the defaults</h3><p class="paragraph"/>All of the properties in the first table can be overridden by a system property or a configuration option - simply use the "config option" name. For example, to change the project working directory, you could either run this command:
<div class="code"><pre>grails &#45;Dgrails.project.work.dir=work compile</pre></div>
or add this option to your <code>grails-app/conf/BuildConfig.groovy</code> file:
<div class="code"><pre>grails.project.work.dir = <span class="java&#45;quote">"work"</span></pre></div>
Note that the default values take account of the property values they depend on, so setting the project working directory like this would also relocate the compiled classes, test classes, resources, and plugins.<p class="paragraph"/>What happens if you use both a system property and a configuration option? Then the system property wins because it takes precedence over the <code>BuildConfig.groovy</code> file, which in turn takes precedence over the default values.<p class="paragraph"/>The <code>BuildConfig.groovy</code> file is a sibling of <code>grails-app/conf/Config.groovy</code> - the former contains options that only affect the build, whereas the latter contains those that affect the application at runtime. It's not limited to the options in the first table either: you will find build configuration options dotted around the documentation, such as ones for specifying the port that the embedded servlet container runs on or for determining what files get packaged in the WAR file.<p class="paragraph"/><h3>Available build settings</h3><p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Name</th><th>Description</th></tr><tr class="table-odd"><td>grails.server.port.http</td><td>Port to run the embedded servlet container on ("run-app" and "run-war"). Integer.</td></tr><tr class="table-even"><td>grails.server.port.https</td><td>Port to run the embedded servlet container on for HTTPS ("run-app &#45;&#45;https" and "run-war &#45;&#45;https"). Integer.</td></tr><tr class="table-odd"><td>grails.config.base.webXml</td><td>Path to a custom web.xml file to use for the application (alternative to using the web.xml template).</td></tr><tr class="table-even"><td>grails.compiler.dependencies</td><td>Legacy approach to adding extra dependencies to the compiler classpath. Set it to a closure containing "fileset()" entries. These entries will be processed by an <code>AntBuilder</code> so the syntax is the Groovy form of the corresponding XML elements in an Ant build file, e.g. <code>fileset(dir: "$basedir/lib", include: "&#42;&#42;/&#42;.class)</code>.</td></tr><tr class="table-odd"><td>grails.testing.patterns</td><td>A list of Ant path patterns that let you control which files are included in the tests. The patterns should not include the test case suffix, which is set by the next property.</td></tr><tr class="table-even"><td>grails.testing.nameSuffix</td><td>By default, tests are assumed to have a suffix of "Tests". You can change it to anything you like but setting this option. For example, another common suffix is "Test".</td></tr><tr class="table-odd"><td>grails.project.war.file</td><td>A string containing the file path of the generated WAR file, along with its full name (include extension). For example, "target/my-app.war".</td></tr><tr class="table-even"><td>grails.war.dependencies</td><td>A closure containing "fileset()" entries that allows you complete control over what goes in the WAR's "WEB-INF/lib" directory.</td></tr><tr class="table-odd"><td>grails.war.copyToWebApp</td><td>A closure containing "fileset()" entries that allows you complete control over what goes in the root of the WAR. It overrides the default behaviour of including everything under "web-app".</td></tr><tr class="table-even"><td>grails.war.resources</td><td>A closure that takes the location of the staging directory as its first argument. You can use any Ant tasks to do anything you like. It is typically used to remove files from the staging directory before that directory is jar'd up into a WAR.</td></tr><tr class="table-odd"><td>grails.project.web.xml</td><td>The location to generate Grails' web.xml to</td></tr></table>
<a name="4.5 Ant and Maven"><!-- Legacy link --></a>
<h2 id="antAndMaven">4.6 Ant and Maven</h2>
If all the other projects in your team or company are built using a standard build tool such as Ant or Maven, you become the black sheep of the family when you use the Grails command line to build your application. Fortunately, you can easily integrate the Grails build system into the main build tools in use today (well, the ones in use in Java projects at least).<p class="paragraph"/><h3>Ant Integration</h3><p class="paragraph"/>When you create a Grails application with the <a href="../ref/Command Line/create-app.html" class="commandLine">create-app</a> command, Grails doesn't automatically create an Ant <code>build.xml</code> file but you can generate one with the <a href="../ref/Command Line/integrate-with.html" class="commandLine">integrate-with</a> command:<p class="paragraph"/><pre class="bq"><code>
grails integrate-with --ant</code></pre><p class="paragraph"/>This creates a <code>build.xml</code> file containing the following targets:
<ul class="star">
<li><code>clean</code> - Cleans the Grails application</li>
<li><code>compile</code> - Compiles your application's source code</li>
<li><code>test</code> - Runs the unit tests</li>
<li><code>run</code> - Equivalent to "grails run-app"</li>
<li><code>war</code> - Creates a WAR file</li>
<li><code>deploy</code> - Empty by default, but can be used to implement automatic deployment</li>
</ul><p class="paragraph"/>Each of these can be run by Ant, for example:<p class="paragraph"/><div class="code"><pre>ant war</pre></div><p class="paragraph"/>The build file is configured to use <a href="http://ant.apache.org/ivy/" target="blank">Apache Ivy</a> for dependency management, which means that it will automatically download all the requisite Grails JAR files and other dependencies on demand. You don't even have to install Grails locally to use it! That makes it particularly useful for continuous integration systems such as <a href="http://cruisecontrol.sourceforge.net/" target="blank">CruiseControl</a> or <a href="http://jenkins-ci.org/" target="blank">Jenkins</a>.<p class="paragraph"/>It uses the Grails <a href="../api/grails/ant/GrailsTask.html" class="api">Ant task</a> to hook into the existing Grails build system. The task lets you run any Grails script that's available, not just the ones used by the generated build file. To use the task, you must first declare it:
<div class="code"><pre>&#60;taskdef name=<span class="java&#45;quote">"grailsTask"</span>
classname=<span class="java&#45;quote">"grails.ant.GrailsTask"</span>
classpathref=<span class="java&#45;quote">"grails.classpath"</span>/&#62;</pre></div><p class="paragraph"/>This raises the question: what should be in "grails.classpath"? The task itself is in the "grails-bootstrap" JAR artifact, so that needs to be on the classpath at least. You should also include the "groovy-all" JAR. With the task defined, you just need to use it! The following table shows you what attributes are available:
<table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Attribute</th><th>Description</th><th>Required</th></tr><tr class="table-odd"><td>home</td><td>The location of the Grails installation directory to use for the build.</td><td>Yes, unless classpath is specified.</td></tr><tr class="table-even"><td>classpathref</td><td>Classpath to load Grails from. Must include the "grails-bootstrap" artifact and should include "grails-scripts".</td><td>Yes, unless <code>home</code> is set or you use a <code>classpath</code> element.</td></tr><tr class="table-odd"><td>script</td><td>The name of the Grails script to run, e.g. "TestApp".</td><td>Yes.</td></tr><tr class="table-even"><td>args</td><td>The arguments to pass to the script, e.g. "-unit -xml".</td><td>No. Defaults to "".</td></tr><tr class="table-odd"><td>environment</td><td>The Grails environment to run the script in.</td><td>No. Defaults to the script default.</td></tr><tr class="table-even"><td>includeRuntimeClasspath</td><td>Advanced setting: adds the application's runtime classpath to the build classpath if true.</td><td>No. Defaults to <code>true</code>.</td></tr></table><p class="paragraph"/>The task also supports the following nested elements, all of which are standard Ant path structures:
<ul class="star">
<li><code>classpath</code> - The build classpath (used to load Gant and the Grails scripts).</li>
<li><code>compileClasspath</code> - Classpath used to compile the application's classes.</li>
<li><code>runtimeClasspath</code> - Classpath used to run the application and package the WAR. Typically includes everything in @compileClasspath.</li>
<li><code>testClasspath</code> - Classpath used to compile and run the tests. Typically includes everything in <code>runtimeClasspath</code>.</li>
</ul><p class="paragraph"/>How you populate these paths is up to you. If you use the <code>home</code> attribute and put your own dependencies in the <code>lib</code> directory, then you don't even need to use any of them. For an example of their use, take a look at the generated Ant build file for new apps.<p class="paragraph"/><h3>Maven Integration</h3><p class="paragraph"/>Grails provides integration with <a href="http://maven.apache.org" target="blank">Maven 2</a> with a Maven plugin. The current Maven plugin is based on but supersedes the version created by <a href="http://forge.octo.com/" target="blank">Octo</a>, who did a great job with the original.<p class="paragraph"/><h4>Preparation</h4><p class="paragraph"/>In order to use the new plugin, all you need is Maven 2 installed and set up. This is because <strong class="bold">you no longer need to install Grails separately to use it with Maven!</strong><p class="paragraph"/><blockquote class="note">
The Maven 2 integration for Grails has been designed and tested for Maven 2.0.9 and above. It will not work with earlier versions.
</blockquote><p class="paragraph"/><blockquote class="note">
The default mvn setup DOES NOT supply sufficient memory to run the Grails environment. We recommend that you add the following environment variable setting to prevent poor performance:<p class="paragraph"/><code>export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=256"</code>
</blockquote><p class="paragraph"/><h4>Creating a Grails Maven Project</h4><p class="paragraph"/>To create a Mavenized Grails project simply run the following command:<p class="paragraph"/><div class="code"><pre>mvn archetype:generate &#45;DarchetypeGroupId=org.grails &#92;
&#45;DarchetypeArtifactId=grails&#45;maven&#45;archetype &#92;
&#45;DarchetypeVersion=1.3.2 &#92;
&#45;DgroupId=example &#45;DartifactId=my&#45;app</pre></div><p class="paragraph"/>Choose whichever grails version, group ID and artifact ID you want for your application, but everything else must be as written. This will create a new Maven project with a POM and a couple of other files. What you won't see is anything that looks like a Grails application. So, the next step is to create the project structure that you're used to.
But first, to set target JDK to Java 6, do that now. Open my-app/pom.xml and change
<div class="code"><pre>&#60;plugin&#62;
&#60;artifactId&#62;maven&#45;compiler&#45;plugin&#60;/artifactId&#62;
&#60;configuration&#62;
&#60;source&#62;1.5&#60;/source&#62;
&#60;target&#62;1.5&#60;/target&#62;
&#60;/configuration&#62;
&#60;/plugin&#62;</pre></div>
to
<div class="code"><pre>&#60;plugin&#62;
&#60;artifactId&#62;maven&#45;compiler&#45;plugin&#60;/artifactId&#62;
&#60;configuration&#62;
&#60;source&#62;1.6&#60;/source&#62;
&#60;target&#62;1.6&#60;/target&#62;
&#60;/configuration&#62;
&#60;/plugin&#62;</pre></div><p class="paragraph"/>Then you're ready to create the project structure:<p class="paragraph"/><div class="code"><pre>cd my&#45;app
mvn initialize</pre></div><p class="paragraph"/><blockquote class="note">
if you see a message similar to this:<p class="paragraph"/><div class="code"><pre>Resolving plugin JAR dependencies &#8230;
:: problems summary ::
:::: WARNINGS
module not found: org.hibernate&#35;hibernate&#45;core;3.3.1.GA</pre></div><p class="paragraph"/>you need to add the plugins manually to application.properties:<p class="paragraph"/><div class="code"><pre>plugins.hibernate=2.0.0
plugins.tomcat=2.0.0</pre></div><p class="paragraph"/>then run<p class="paragraph"/><div class="code"><pre>mvn compile</pre></div><p class="paragraph"/>and the hibernate and tomcat plugins will be installed.
</blockquote><p class="paragraph"/>Now you have a Grails application all ready to go. The plugin integrates into the standard build cycle, so you can use the standard Maven phases to build and package your app: <code>mvn clean</code> , <code>mvn compile</code> , <code>mvn test</code> , <code>mvn package</code> , <code>mvn install</code> .<p class="paragraph"/>You can also use some of the Grails commands that have been wrapped as Maven goals:
<ul class="star">
<li><code>grails:create-controller</code> - Calls the <a href="../ref/Command Line/create-controller.html" class="commandLine">create-controller</a> command</li>
<li><code>grails:create-domain-class</code> - Calls the <a href="../ref/Command Line/create-domain-class.html" class="commandLine">create-domain-class</a> command</li>
<li><code>grails:create-integration-test</code> - Calls the <a href="../ref/Command Line/create-integration-test.html" class="commandLine">create-integration-test</a> command</li>
<li><code>grails:create-pom</code> - Creates a new Maven POM for an existing Grails project</li>
<li><code>grails:create-script</code> - Calls the <a href="../ref/Command Line/create-script.html" class="commandLine">create-script</a> command</li>
<li><code>grails:create-service</code> - Calls the <a href="../ref/Command Line/create-service.html" class="commandLine">create-service</a> command</li>
<li><code>grails:create-taglib</code> - Calls the <a href="../ref/Command Line/create-tag-lib.html" class="commandLine">create-tag-lib</a> command</li>
<li><code>grails:create-unit-test</code> - Calls the <a href="../ref/Command Line/create-unit-test.html" class="commandLine">create-unit-test</a> command</li>
<li><code>grails:exec</code> - Executes an arbitrary Grails command line script</li>
<li><code>grails:generate-all</code> - Calls the <a href="../ref/Command Line/generate-all.html" class="commandLine">generate-all</a> command</li>
<li><code>grails:generate-controller</code> - Calls the <a href="../ref/Command Line/generate-controller.html" class="commandLine">generate-controller</a> command</li>
<li><code>grails:generate-views</code> - Calls the <a href="../ref/Command Line/generate-views.html" class="commandLine">generate-views</a> command</li>
<li><code>grails:install-plugin</code> - Calls the <a href="../ref/Command Line/install-plugin.html" class="commandLine">install-plugin</a> command</li>
<li><code>grails:install-templates</code> - Calls the <a href="../ref/Command Line/install-templates.html" class="commandLine">install-templates</a> command</li>
<li><code>grails:list-plugins</code> - Calls the <a href="../ref/Command Line/list-plugins.html" class="commandLine">list-plugins</a> command</li>
<li><code>grails:package</code> - Calls the <a href="../ref/Command Line/package.html" class="commandLine">package</a> command</li>
<li><code>grails:run-app</code> - Calls the <a href="../ref/Command Line/run-app.html" class="commandLine">run-app</a> command</li>
<li><code>grails:uninstall-plugin</code> - Calls the <a href="../ref/Command Line/uninstall-plugin.html" class="commandLine">uninstall-plugin</a> command</li>
</ul><p class="paragraph"/>For a complete, up to date list, run <code>mvn grails:help</code><p class="paragraph"/><h4>Mavenizing an existing project</h4><p class="paragraph"/>Creating a new project is great way to start, but what if you already have one? You don't want to create a new project and then copy the contents of the old one over. The solution is to create a POM for the existing project using this Maven command (substitute the version number with the grails version of your existing project):
<div class="code"><pre>mvn org.grails:grails&#45;maven&#45;plugin:1.3.2:create&#45;pom &#45;DgroupId=com.mycompany</pre></div>
When this command has finished, you can immediately start using the standard phases, such as <code>mvn package</code>. Note that you have to specify a group ID when creating the POM.<p class="paragraph"/>You may also want to set target JDK to Java 6; see above.<p class="paragraph"/><h4>Adding Grails commands to phases</h4><p class="paragraph"/>The standard POM created for you by Grails already attaches the appropriate core Grails commands to their corresponding build phases, so "compile" goes in the "compile" phase and "war" goes in the "package" phase. That doesn't help though when you want to attach a plugin's command to a particular phase. The classic example is functional tests. How do you make sure that your functional tests (using which ever plugin you have decided on) are run during the "integration-test" phase?<p class="paragraph"/>Fear not: all things are possible. In this case, you can associate the command to a phase using an extra "execution" block:
<div class="code"><pre><span class="xml&#45;tag">&#60;plugin&#62;</span>
<span class="xml&#45;tag">&#60;groupId&#62;</span>org.grails<span class="xml&#45;tag">&#60;/groupId&#62;</span>
<span class="xml&#45;tag">&#60;artifactId&#62;</span>grails&#45;maven&#45;plugin<span class="xml&#45;tag">&#60;/artifactId&#62;</span>
<span class="xml&#45;tag">&#60;version&#62;</span>1.3.2<span class="xml&#45;tag">&#60;/version&#62;</span>
<span class="xml&#45;tag">&#60;extensions&#62;</span>true<span class="xml&#45;tag">&#60;/extensions&#62;</span>
<span class="xml&#45;tag">&#60;executions&#62;</span>
<span class="xml&#45;tag">&#60;execution&#62;</span>
<span class="xml&#45;tag">&#60;goals&#62;</span>
&#8230;
<span class="xml&#45;tag">&#60;/goals&#62;</span>
<span class="xml&#45;tag">&#60;/execution&#62;</span>
<span class="xml&#45;comment">&#60;!&#45;&#45; Add the <span class="xml&#45;quote">"functional&#45;tests"</span> command to the <span class="xml&#45;quote">"integration&#45;test"</span> phase &#45;&#45;&#62;</span>
<span class="xml&#45;tag">&#60;execution&#62;</span>
<span class="xml&#45;tag">&#60;id&#62;</span>functional&#45;tests<span class="xml&#45;tag">&#60;/id&#62;</span>
<span class="xml&#45;tag">&#60;phase&#62;</span>integration&#45;test<span class="xml&#45;tag">&#60;/phase&#62;</span>
<span class="xml&#45;tag">&#60;goals&#62;</span>
<span class="xml&#45;tag">&#60;goal&#62;</span>exec<span class="xml&#45;tag">&#60;/goal&#62;</span>
<span class="xml&#45;tag">&#60;/goals&#62;</span>
<span class="xml&#45;tag">&#60;configuration&#62;</span>
<span class="xml&#45;tag">&#60;command&#62;</span>functional&#45;tests<span class="xml&#45;tag">&#60;/command&#62;</span>
<span class="xml&#45;tag">&#60;/configuration&#62;</span>
<span class="xml&#45;tag">&#60;/execution&#62;</span>
<span class="xml&#45;tag">&#60;/executions&#62;</span>
<span class="xml&#45;tag">&#60;/plugin&#62;</span></pre></div><p class="paragraph"/>This also demonstrates the <code>grails:exec</code> goal, which can be used to run any Grails command. Simply pass the name of the command as the <code>command</code> system property, and optionally specify the arguments with the <code>args</code> property:
<div class="code"><pre>mvn grails:exec &#45;Dcommand=create&#45;webtest &#45;Dargs=Book</pre></div><p class="paragraph"/><h4>Debugging a Grails Maven Project</h4><p class="paragraph"/>Maven can be launched in debug mode using the "mvnDebug" command. To launch your Grails application in debug, simply run:<p class="paragraph"/><div class="code"><pre>mvnDebug grails:run&#45;app</pre></div><p class="paragraph"/>The process will be suspended on startup and listening for a debugger on port 8000.<p class="paragraph"/>If you need more control of the debugger, this can be specified using the MAVEN_OPTS environment variable, and launch Maven with the default "mvn" command:<p class="paragraph"/><div class="code"><pre>MAVEN_OPTS=<span class="java&#45;quote">"&#45;Xdebug &#45;Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"</span>
mvn grails:run&#45;app</pre></div><p class="paragraph"/><h4>Raising issues</h4><p class="paragraph"/>If you come across any problems with the Maven integration, please raise a JIRA issue as a sub-task of <a href="http://jira.codehaus.org/browse/GRAILS-3547" target="blank">GRAILS-3547</a>.
<a name="5. Object Relational Mapping (GORM)"><!-- Legacy link --></a>
<h1 id="GORM">5 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&#45;quote">"Groovy in Action"</span>)<p class="paragraph"/>book
.addToAuthors(name:<span class="java&#45;quote">"Dierk Koenig"</span>)
.addToAuthors(name:<span class="java&#45;quote">"Guillaume LaForge"</span>)
.save()</pre></div>
<a name="5.1 Quick Start Guide"><!-- Legacy link --></a>
<h2 id="quickStartGuide">5.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&#45;domain&#45;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&#45;keyword">package</span> helloworld<p class="paragraph"/>class Person &#123;
&#125;</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 &#123;
<span class="java&#45;object">String</span> name
<span class="java&#45;object">Integer</span> age
Date lastVisit
&#125;</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">5.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&#45;keyword">new</span> Person(name: <span class="java&#45;quote">"Fred"</span>, age: 40, lastVisit: <span class="java&#45;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&#45;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">5.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&#45;domain&#45;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&#45;keyword">package</span> org.bookstore<p class="paragraph"/>class Book &#123;
&#125;</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&#45;keyword">package</span> org.bookstore<p class="paragraph"/>class Book &#123;
<span class="java&#45;object">String</span> title
Date releaseDate
<span class="java&#45;object">String</span> ISBN
&#125;</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">5.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">5.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 &#123;
Nose nose
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Nose &#123;
&#125;</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:<p class="paragraph"/><h5>Example B</h5><p class="paragraph"/><div class="code"><pre>class Face &#123;
Nose nose
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Nose &#123;
<span class="java&#45;keyword">static</span> belongsTo = &#91;face:Face&#93;
&#125;</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&#45;keyword">new</span> Face(nose:<span class="java&#45;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&#45;keyword">new</span> Nose(face:<span class="java&#45;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 &#123;
<span class="java&#45;keyword">static</span> hasOne = &#91;nose:Nose&#93;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Nose &#123;
Face face
&#125;</pre></div><p class="paragraph"/>Note that using this property puts the foreign key on the inverse table to the previous example, 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 &#123;
<span class="java&#45;keyword">static</span> hasOne = &#91;nose:Nose&#93;<p class="paragraph"/> <span class="java&#45;keyword">static</span> constraints = &#123;
nose unique: <span class="java&#45;keyword">true</span>
&#125;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Nose &#123;
Face face
&#125;</pre></div>
<a name="5.2.1.2 One-to-many"><!-- Legacy link --></a>
<h2 id="oneToMany">5.2.1.2 One-to-many</h2>
A one-to-many relationship is when one class, example <code>Author</code>, has many instances of a 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 &#123;
<span class="java&#45;keyword">static</span> hasMany = &#91;books: Book&#93;<p class="paragraph"/> <span class="java&#45;object">String</span> name
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Book &#123;
<span class="java&#45;object">String</span> title
&#125;</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&#45;keyword">for</span> (book in a.books) &#123;
println book.title
&#125;</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 &#123;
<span class="java&#45;keyword">static</span> hasMany = &#91;books: Book&#93;<p class="paragraph"/> <span class="java&#45;object">String</span> name
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Book &#123;
<span class="java&#45;keyword">static</span> belongsTo = &#91;author: Author&#93;
<span class="java&#45;object">String</span> title
&#125;</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 &#123;
<span class="java&#45;keyword">static</span> hasMany = &#91;flights: Flight&#93;
<span class="java&#45;keyword">static</span> mappedBy = &#91;flights: <span class="java&#45;quote">"departureAirport"</span>&#93;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Flight &#123;
Airport departureAirport
Airport destinationAirport
&#125;</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 &#123;
<span class="java&#45;keyword">static</span> hasMany = &#91;outboundFlights: Flight, inboundFlights: Flight&#93;
<span class="java&#45;keyword">static</span> mappedBy = &#91;outboundFlights: <span class="java&#45;quote">"departureAirport"</span>,
inboundFlights: <span class="java&#45;quote">"destinationAirport"</span>&#93;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Flight &#123;
Airport departureAirport
Airport destinationAirport
&#125;</pre></div><p class="paragraph"/>
<a name="5.2.1.3 Many-to-many"><!-- Legacy link --></a>
<h2 id="manyToMany">5.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 &#123;
<span class="java&#45;keyword">static</span> belongsTo = Author
<span class="java&#45;keyword">static</span> hasMany = &#91;authors:Author&#93;
<span class="java&#45;object">String</span> title
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Author &#123;
<span class="java&#45;keyword">static</span> hasMany = &#91;books:Book&#93;
<span class="java&#45;object">String</span> name
&#125;</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&#45;keyword">new</span> Author(name:<span class="java&#45;quote">"Stephen King"</span>)
.addToBooks(<span class="java&#45;keyword">new</span> Book(title:<span class="java&#45;quote">"The Stand"</span>))
.addToBooks(<span class="java&#45;keyword">new</span> Book(title:<span class="java&#45;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&#45;keyword">new</span> Book(name:<span class="java&#45;quote">"Groovy in Action"</span>)
.addToAuthors(<span class="java&#45;keyword">new</span> Author(name:<span class="java&#45;quote">"Dierk Koenig"</span>))
.addToAuthors(<span class="java&#45;keyword">new</span> Author(name:<span class="java&#45;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">5.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 &#123;
<span class="java&#45;keyword">static</span> hasMany = &#91;nicknames: <span class="java&#45;object">String</span>&#93;
&#125;</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 &#123;<p class="paragraph"/> <span class="java&#45;keyword">static</span> hasMany = &#91;nicknames: <span class="java&#45;object">String</span>&#93;<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
hasMany joinTable: &#91;name: 'bunch_o_nicknames',
key: 'person_id',
column: 'nickname',
type: <span class="java&#45;quote">"text"</span>&#93;
&#125;
&#125;</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>&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;
| person_id | nickname |
&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;
| 1 | Fred |
&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;</pre></div>
<a name="5.2.2 Composition in GORM"><!-- Legacy link --></a>
<h2 id="gormComposition">5.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 &#123;
Address homeAddress
Address workAddress
<span class="java&#45;keyword">static</span> embedded = &#91;'homeAddress', 'workAddress'&#93;
&#125;<p class="paragraph"/>class Address &#123;
<span class="java&#45;object">String</span> number
<span class="java&#45;object">String</span> code
&#125;</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">5.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 &#123;
<span class="java&#45;object">String</span> author
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class BlogEntry <span class="java&#45;keyword">extends</span> Content &#123;
URL url
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Book <span class="java&#45;keyword">extends</span> Content &#123;
<span class="java&#45;object">String</span> ISBN
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class PodCast <span class="java&#45;keyword">extends</span> Content &#123;
<span class="java&#45;object">byte</span>&#91;&#93; audioStream
&#125;</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">5.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 &#123;
<span class="java&#45;keyword">static</span> hasMany = &#91;books: Book&#93;
&#125;</pre></div><p class="paragraph"/>The books property that GORM injects is a <code>java.util.Set</code>. Sets guarantee uniquenes 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 &#123;<p class="paragraph"/> SortedSet books<p class="paragraph"/> <span class="java&#45;keyword">static</span> hasMany = &#91;books: Book&#93;
&#125;</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&#45;keyword">implements</span> Comparable &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> title
Date releaseDate = <span class="java&#45;keyword">new</span> Date()<p class="paragraph"/> <span class="java&#45;object">int</span> compareTo(obj) &#123;
releaseDate.compareTo(obj.releaseDate)
&#125;
&#125;</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 &#123;<p class="paragraph"/> List books<p class="paragraph"/> <span class="java&#45;keyword">static</span> hasMany = &#91;books: Book&#93;
&#125;</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&#91;0&#93; // 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&#45;keyword">new</span> Book(title: 'The Shining')
book.save()
author.addToBooks(book)<p class="paragraph"/>// Do it <span class="java&#45;keyword">this</span> way instead.
def book = <span class="java&#45;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 &#123;<p class="paragraph"/> Collection books<p class="paragraph"/> <span class="java&#45;keyword">static</span> hasMany = &#91;books: Book&#93;
&#125;</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 &#123;
Map books // map of ISBN:book names
&#125;<p class="paragraph"/>def a = <span class="java&#45;keyword">new</span> Author()
a.books = &#91;<span class="java&#45;quote">"1590597583"</span>:<span class="java&#45;quote">"Grails Book"</span>&#93;
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 &#123;<p class="paragraph"/> Map authors<p class="paragraph"/> <span class="java&#45;keyword">static</span> hasMany = &#91;authors: Author&#93;
&#125;<p class="paragraph"/>def a = <span class="java&#45;keyword">new</span> Author(name:<span class="java&#45;quote">"Stephen King"</span>)<p class="paragraph"/>def book = <span class="java&#45;keyword">new</span> Book()
book.authors = &#91;stephen:a&#93;
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&#45;keyword">new</span> Book(title:<span class="java&#45;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&#45;keyword">new</span> Book(title:<span class="java&#45;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">5.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://ibatis.apache.org/," target="blank">iBatis</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">5.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&#45;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&#45;keyword">try</span> &#123;
p.save(flush: <span class="java&#45;keyword">true</span>)
&#125;
<span class="java&#45;keyword">catch</span> (org.springframework.dao.DataIntegrityViolationException e) &#123;
// deal with exception
&#125;</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&#45;keyword">try</span> &#123;
p.save(failOnError: <span class="java&#45;keyword">true</span>)
&#125;
<span class="java&#45;keyword">catch</span> (ValidationException e) &#123;
// deal with exception
&#125;</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">5.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&#45;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&#45;keyword">try</span> &#123;
p.delete(flush: <span class="java&#45;keyword">true</span>)
&#125;
<span class="java&#45;keyword">catch</span> (org.springframework.dao.DataIntegrityViolationException e) &#123;
flash.message = <span class="java&#45;quote">"Could not delete person $&#123;p.name&#125;"</span>
redirect(action: <span class="java&#45;quote">"show"</span>, id: p.id)
&#125;</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&#45;quote">"delete Customer c where c.name = :oldName"</span>,
&#91;oldName: <span class="java&#45;quote">"Fred"</span>&#93;)</pre></div><p class="paragraph"/>
<a name="5.3.3 Understanding Cascading Updates and Deletes"><!-- Legacy link --></a>
<h2 id="cascades">5.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 &#123;
<span class="java&#45;object">String</span> name
<span class="java&#45;keyword">static</span> hasMany = &#91;flights: Flight&#93;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Flight &#123;
<span class="java&#45;object">String</span> number
<span class="java&#45;keyword">static</span> belongsTo = &#91;airport: Airport&#93;
&#125;</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&#45;keyword">new</span> Airport(name: <span class="java&#45;quote">"Gatwick"</span>)
.addToFlights(<span class="java&#45;keyword">new</span> Flight(number: <span class="java&#45;quote">"BA3430"</span>))
.addToFlights(<span class="java&#45;keyword">new</span> Flight(number: <span class="java&#45;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&#45;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 &#123; <span class="java&#45;keyword">static</span> hasMany = &#91;bees: B&#93; &#125;</pre></div><p class="paragraph"/><div class="code"><pre>class B &#123; <span class="java&#45;keyword">static</span> belongsTo = &#91;a: A&#93; &#125;</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 &#123; <span class="java&#45;keyword">static</span> hasMany = &#91;bees: B&#93; &#125;</pre></div><p class="paragraph"/><div class="code"><pre>class B &#123; &#125;</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 &#123; <span class="java&#45;keyword">static</span> hasMany = &#91;bees: B&#93; &#125;</pre></div><p class="paragraph"/><div class="code"><pre>class B &#123; A a &#125;</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 &#123; &#125;</pre></div><p class="paragraph"/><div class="code"><pre>class B &#123; <span class="java&#45;keyword">static</span> belongsTo = &#91;a: A&#93; &#125;</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-&#62;B) and "NONE" from the side that defines the <code>belongsTo</code> (B-&#62;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">5.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 &#123;
<span class="java&#45;object">String</span> name
<span class="java&#45;keyword">static</span> hasMany = &#91;flights: Flight&#93;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Flight &#123;
<span class="java&#45;object">String</span> number
Location destination
<span class="java&#45;keyword">static</span> belongsTo = &#91;airport: Airport&#93;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Location &#123;
<span class="java&#45;object">String</span> city
<span class="java&#45;object">String</span> country
&#125;</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&#45;quote">"Gatwick"</span>)
<span class="java&#45;keyword">for</span> (flight in airport.flights) &#123;
println flight.destination.city
&#125;</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 &#123;
<span class="java&#45;object">String</span> name
<span class="java&#45;keyword">static</span> hasMany = &#91;flights: Flight&#93;
<span class="java&#45;keyword">static</span> mapping = &#123;
flights lazy: <span class="java&#45;keyword">false</span>
&#125;
&#125;</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 &#123;
<span class="java&#45;object">String</span> name
<span class="java&#45;keyword">static</span> hasMany = &#91;flights: Flight&#93;
<span class="java&#45;keyword">static</span> mapping = &#123;
flights batchSize: 10
&#125;
&#125;</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 &#123;
&#8230;
<span class="java&#45;keyword">static</span> mapping = &#123;
batchSize 10
&#125;
&#125;</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">5.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&#45;keyword">try</span> &#123;
airport.name = <span class="java&#45;quote">"Heathrow"</span>
airport.save(flush: <span class="java&#45;keyword">true</span>)
&#125;
<span class="java&#45;keyword">catch</span> (org.springframework.dao.OptimisticLockingFailureException e) &#123;
// deal with exception
&#125;</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&#45;keyword">for</span> update
airport.name = <span class="java&#45;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&#45;keyword">for</span> update
airport.name = <span class="java&#45;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&#45;quote">"Heathrow"</span>, &#91;lock: <span class="java&#45;keyword">true</span>&#93;)</pre></div><p class="paragraph"/>Or using criteria:<p class="paragraph"/><div class="code"><pre>def airport = Airport.createCriteria().get &#123;
eq('name', 'Heathrow')
lock <span class="java&#45;keyword">true</span>
&#125;</pre></div><p class="paragraph"/>
<a name="5.3.6 Modification Checking"><!-- Legacy link --></a>
<h2 id="modificationChecking">5.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&#45;keyword">if</span> (airport.isDirty()) &#123;
// <span class="java&#45;keyword">do</span> something based on changed state
&#125;</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&#45;keyword">if</span> (airport.isDirty('name')) &#123;
// <span class="java&#45;keyword">do</span> something based on changed name
&#125;</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&#45;keyword">for</span> (fieldName in modifiedFieldNames) &#123;
// <span class="java&#45;keyword">do</span> something based on changed value
&#125;</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&#45;keyword">for</span> (fieldName in modifiedFieldNames) &#123;
def currentValue = airport.<span class="java&#45;quote">"$fieldName"</span>
def originalValue = airport.getPersistentValue(fieldName)
<span class="java&#45;keyword">if</span> (currentValue != originalValue) &#123;
// <span class="java&#45;keyword">do</span> something based on changed value
&#125;
&#125;</pre></div><p class="paragraph"/>
<a name="5.4 Querying with GORM"><!-- Legacy link --></a>
<h2 id="querying">5.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&#45;quote">"title"</span>, order:<span class="java&#45;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">5.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 &#123;
<span class="java&#45;object">String</span> title
Date releaseDate
Author author
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Author &#123;
<span class="java&#45;object">String</span> name
&#125;</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&#45;quote">"The Stand"</span>)<p class="paragraph"/>book = Book.findByTitleLike(<span class="java&#45;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&#45;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(&#91;Property&#93;&#91;Comparator&#93;&#91;<span class="java&#45;object">Boolean</span> Operator&#93;)?&#91;Property&#93;&#91;Comparator&#93;</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&#45;quote">"The Stand"</span>)<p class="paragraph"/>book = Book.findByTitleLike(<span class="java&#45;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>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&#45;keyword">new</span> Date()
def lastWeek = now &#45; 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&#45;quote">"%Java%"</span>, <span class="java&#45;keyword">new</span> Date() &#45; 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&#45;quote">"%Java%"</span>, <span class="java&#45;keyword">new</span> Date() &#45; 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&#45;quote">"Stephen King"</span>)<p class="paragraph"/>def books = author ? Book.findAllByAuthor(author) : &#91;&#93;</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&#45;quote">"Harry Pot%"</span>,
&#91;max: 3, offset: 2, sort: <span class="java&#45;quote">"title"</span>, order: <span class="java&#45;quote">"desc"</span>&#93;)</pre></div>
<h2 id="whereQueries">5.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 &#123;
firstName == <span class="java&#45;quote">"Bart"</span>
&#125;
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 &#123;
<span class="java&#45;keyword">static</span> simpsons = where &#123;
lastName == <span class="java&#45;quote">"Simpson"</span>
&#125;
&#8230;
&#125;
&#8230;
Person.simpsons.each &#123;
println it.firstname
&#125;</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 &#123;
lastName == <span class="java&#45;quote">"Simpson"</span>
&#125;
def results = Person.findAll(sort:<span class="java&#45;quote">"firstName"</span>) &#123;
lastName == <span class="java&#45;quote">"Simpson"</span>
&#125;
Person p = Person.find &#123; firstName == <span class="java&#45;quote">"Bart"</span> &#125;</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">&#62;</strong></td><td>gt</td><td>Greater than</td></tr><tr class="table-even"><td><strong class="bold">&#60;</strong></td><td>lt</td><td>Less than</td></tr><tr class="table-odd"><td><strong class="bold">&#62;=</strong></td><td>ge</td><td>Greater than or equal to</td></tr><tr class="table-even"><td><strong class="bold">&#60;=</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 &#123;
(lastName != <span class="java&#45;quote">"Simpson"</span> &#38;&#38; firstName != <span class="java&#45;quote">"Fred"</span>) || (firstName == <span class="java&#45;quote">"Bart"</span> &#38;&#38; age &#62; 9)
&#125;
def results = query.list(sort:<span class="java&#45;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 &#123;
firstName ==~ ~/B.+/
&#125;</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 &#123;
age in 18..65
&#125;</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 &#123;
middleName == <span class="java&#45;keyword">null</span>
&#125;</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 &#123;
lastName == <span class="java&#45;quote">"Simpson"</span>
&#125;
def bartQuery = query.where &#123;
firstName == <span class="java&#45;quote">"Bart"</span>
&#125;
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 = &#123;
lastName == <span class="java&#45;quote">"Simpson"</span>
&#125;
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&#45;keyword">import</span> grails.gorm.DetachedCriteria<p class="paragraph"/>def callable = &#123;
lastName == <span class="java&#45;quote">"Simpson"</span>
&#125; as DetachedCriteria&#60;Person&#62;
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>&#38;&#38;</code>) to form conjunctions and disjunctions:<p class="paragraph"/><div class="code"><pre>def query = Person.where &#123;
(lastName != <span class="java&#45;quote">"Simpson"</span> &#38;&#38; firstName != <span class="java&#45;quote">"Fred"</span>) || (firstName == <span class="java&#45;quote">"Bart"</span> &#38;&#38; age &#62; 9)
&#125;</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 &#123;
firstName == <span class="java&#45;quote">"Fred"</span> &#38;&#38; !(lastName == 'Simpson')
&#125;</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 &#123;
firstName == lastName
&#125;</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">&#62;</strong></td><td>gtProperty</td><td>Greater than</td></tr><tr class="table-even"><td><strong class="bold">&#60;</strong></td><td>ltProperty</td><td>Less than</td></tr><tr class="table-odd"><td><strong class="bold">&#62;=</strong></td><td>geProperty</td><td>Greater than or equal to</td></tr><tr class="table-even"><td><strong class="bold">&#60;=</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 &#123;
owner.firstName == <span class="java&#45;quote">"Joe"</span> || owner.firstName == <span class="java&#45;quote">"Fred"</span>
&#125;</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 &#123;
pets &#123; name == <span class="java&#45;quote">"Jack"</span> || name == <span class="java&#45;quote">"Joe"</span> &#125;
&#125;</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 &#123;
pets &#123; name == <span class="java&#45;quote">"Jack"</span> &#125; || firstName == <span class="java&#45;quote">"Ed"</span>
&#125;</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 &#123;
pets.size() == 2
&#125;</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">&#62;</strong></td><td>sizeGt</td><td>The collection size is greater than</td></tr><tr class="table-even"><td><strong class="bold">&#60;</strong></td><td>sizeLt</td><td>The collection size is less than</td></tr><tr class="table-odd"><td><strong class="bold">&#62;=</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">&#60;=</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&#45;keyword">final</span> query = Person.where &#123;
age &#62; avg(age)
&#125;</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 &#123;
age &#62; avg(age).of &#123; lastName == <span class="java&#45;quote">"Simpson"</span> &#125; &#38;&#38; firstName == <span class="java&#45;quote">"Homer"</span>
&#125;</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 &#123;
age &#60; property(age).of &#123; lastName == <span class="java&#45;quote">"Simpson"</span> &#125;
&#125;</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 &#123;
year(birthDate) == 2011
&#125;</pre></div><p class="paragraph"/>You can also apply functions to associations:<p class="paragraph"/><div class="code"><pre>def query = Person.where &#123;
year(pets.birthDate) == 2009
&#125;</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 &#123;
lastName == 'Simpson'
&#125;
<span class="java&#45;object">int</span> total = query.updateAll(lastName:<span class="java&#45;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 &#123;
lastName == 'Simpson'
&#125;
<span class="java&#45;object">int</span> total = query.deleteAll()</pre></div>
<a name="5.4.2 Criteria"><!-- Legacy link --></a>
<h2 id="criteria">5.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 &#123;
between(<span class="java&#45;quote">"balance"</span>, 500, 1000)
eq(<span class="java&#45;quote">"branch"</span>, <span class="java&#45;quote">"London"</span>)
or &#123;
like(<span class="java&#45;quote">"holderFirstName"</span>, <span class="java&#45;quote">"Fred%"</span>)
like(<span class="java&#45;quote">"holderFirstName"</span>, <span class="java&#45;quote">"Barney%"</span>)
&#125;
maxResults(10)
order(<span class="java&#45;quote">"holderLastName"</span>, <span class="java&#45;quote">"desc"</span>)
&#125;</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 &#123;
between(<span class="java&#45;quote">"balance"</span>, 500, 1000)
eq(<span class="java&#45;quote">"branch"</span>, <span class="java&#45;quote">"London"</span>)
&#125;</pre></div><p class="paragraph"/>This also works with logical AND:<p class="paragraph"/><div class="code"><pre>and &#123;
between(<span class="java&#45;quote">"balance"</span>, 500, 1000)
eq(<span class="java&#45;quote">"branch"</span>, <span class="java&#45;quote">"London"</span>)
&#125;</pre></div><p class="paragraph"/>And you can also negate using logical NOT:<p class="paragraph"/><div class="code"><pre>not &#123;
between(<span class="java&#45;quote">"balance"</span>, 500, 1000)
eq(<span class="java&#45;quote">"branch"</span>, <span class="java&#45;quote">"London"</span>)
&#125;</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 &#123;
&#8230;
<span class="java&#45;keyword">static</span> hasMany = &#91;transactions: Transaction&#93;
&#8230;
&#125;</pre></div><p class="paragraph"/>We can query this association by using the property name <code>transaction</code> as a builder node:<p class="paragraph"/><div class="code"><pre>def c = Account.createCriteria()
def now = <span class="java&#45;keyword">new</span> Date()
def results = c.list &#123;
transactions &#123;
between('date', now &#45; 10, now)
&#125;
&#125;</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&#45;keyword">new</span> Date()
def results = c.list &#123;
or &#123;
between('created', now &#45; 10, now)
transactions &#123;
between('date', now &#45; 10, now)
&#125;
&#125;
&#125;</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 &#123;
projections &#123;
countDistinct('branch')
&#125;
&#125;</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>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 &#123;
sqlRestriction <span class="java&#45;quote">"char_length(first_name) &#60;= 4"</span>
&#125;</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 &#123;
maxResults(10)
&#125;
def f = results.first()
def l = results.last()
def n = results.next()
def p = results.previous()<p class="paragraph"/>def <span class="java&#45;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&#45;keyword">import</span> org.hibernate.FetchMode as FM
&#8230;
def results = c.list &#123;
maxResults(10)
firstResult(50)
fetchMode(<span class="java&#45;quote">"aRelationship"</span>, FM.JOIN)
&#125;</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&#123;
eq <span class="java&#45;quote">"assignee.id"</span>, task.assignee.id
join 'assignee'
join 'project'
order 'priority', 'asc'
&#125;</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&#45;keyword">import</span> org.hibernate.FetchMode as FM
&#8230;
def results = Airport.withCriteria &#123;
eq <span class="java&#45;quote">"region"</span>, <span class="java&#45;quote">"EMEA"</span>
fetchMode <span class="java&#45;quote">"flights"</span>, FM.SELECT
&#125;</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 &#123;
eq <span class="java&#45;quote">"region"</span>, <span class="java&#45;quote">"EMEA"</span>
flights &#123;
like <span class="java&#45;quote">"number"</span>, <span class="java&#45;quote">"BA%"</span>
&#125;
&#125;</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 &#123; &#8230; &#125;</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 &#123; &#8230; &#125;</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>
<h2 id="detachedCriteria">5.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&#45;keyword">import</span> grails.gorm.&#42;
&#8230;
def criteria = <span class="java&#45;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&#45;keyword">new</span> DetachedCriteria(Person).build &#123;
eq 'lastName', 'Simpson'
&#125;</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&#45;keyword">new</span> DetachedCriteria(Person).build &#123;
eq 'lastName', 'Simpson'
&#125;
def bartQuery = criteria.build &#123;
eq 'firstName', 'Bart'
&#125;</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&#45;keyword">new</span> DetachedCriteria(Person).build &#123;
eq 'lastName', 'Simpson'
&#125;
def results = criteria.list(max:4, sort:<span class="java&#45;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&#45;quote">"firstName"</span>) &#123;
gt 'age', 30
&#125;</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&#45;keyword">new</span> DetachedCriteria(Person).build &#123;
eq 'lastName', 'Simpson'
&#125;
criteria.each &#123;
println it.firstName
&#125;</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&#45;keyword">new</span> DetachedCriteria(Person).build &#123;
eq 'lastName', 'Simpson'
&#125;
def bart = criteria.findByFirstName(<span class="java&#45;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 &#123;
gt <span class="java&#45;quote">"age"</span>, <span class="java&#45;keyword">new</span> DetachedCriteria(Person).build &#123;
projections &#123;
avg <span class="java&#45;quote">"age"</span>
&#125;
&#125;
order <span class="java&#45;quote">"firstName"</span>
&#125;</pre></div><p class="paragraph"/>Notice that in this case the subquery class is the same as the original criteria query class (ie. <code>Person</code>) and hence the query can be shortened to:<p class="paragraph"/><div class="code"><pre>def results = Person.withCriteria &#123;
gt <span class="java&#45;quote">"age"</span>, &#123;
projections &#123;
avg <span class="java&#45;quote">"age"</span>
&#125;
&#125;
order <span class="java&#45;quote">"firstName"</span>
&#125;</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 &#123;
gtAll <span class="java&#45;quote">"age"</span>, &#123;
projections &#123;
property <span class="java&#45;quote">"age"</span>
&#125;
between 'age', 18, 65
&#125;<p class="paragraph"/> order <span class="java&#45;quote">"firstName"</span>
&#125;</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&#45;keyword">new</span> DetachedCriteria(Person).build &#123;
eq 'lastName', 'Simpson'
&#125;
<span class="java&#45;object">int</span> total = criteria.updateAll(lastName:<span class="java&#45;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&#45;keyword">new</span> DetachedCriteria(Person).build &#123;
eq 'lastName', 'Simpson'
&#125;
<span class="java&#45;object">int</span> total = criteria.deleteAll()</pre></div>
<a name="5.4.3 Hibernate Query Language (HQL)"><!-- Legacy link --></a>
<h2 id="hql">5.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&#45;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&#45;quote">"from Book as b where b.title like ?"</span>, &#91;<span class="java&#45;quote">"The Shi%"</span>&#93;)</pre></div><p class="paragraph"/><div class="code"><pre>def author = Author.findByName(<span class="java&#45;quote">"Stephen King"</span>)
def books = Book.findAll(<span class="java&#45;quote">"from Book as book where book.author = ?"</span>,
&#91;author&#93;)</pre></div><p class="paragraph"/>Or even named parameters:<p class="paragraph"/><div class="code"><pre>def results =
Book.findAll(<span class="java&#45;quote">"from Book as b "</span> +
<span class="java&#45;quote">"where b.title like :search or b.author like :search"</span>,
&#91;search: <span class="java&#45;quote">"The Shi%"</span>&#93;)</pre></div><p class="paragraph"/><div class="code"><pre>def author = Author.findByName(<span class="java&#45;quote">"Stephen King"</span>)
def books = Book.findAll(<span class="java&#45;quote">"from Book as book where book.author = :author"</span>,
&#91;author: author&#93;)</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&#45;quote">"&#92;
from Book as b, &#92;
Author as a &#92;
where b.author = a and a.surname = ?"</span>, &#91;'Smith'&#93;)</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&#45;quote">"from Book as b where "</span> +
<span class="java&#45;quote">"b.title like 'Lord of the%' "</span> +
<span class="java&#45;quote">"order by b.title asc"</span>,
&#91;max: 10, offset: 20&#93;)</pre></div>
<a name="5.5 Advanced GORM Features"><!-- Legacy link --></a>
<h2 id="advancedGORMFeatures">5.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">5.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</li>
<li><code>beforeUpdate</code> - Executed before an object is updated</li>
<li><code>beforeDelete</code> - Executed before an object is deleted</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 closure 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 &#123;
Date dateCreated<p class="paragraph"/> def beforeInsert() &#123;
dateCreated = <span class="java&#45;keyword">new</span> Date()
&#125;
&#125;</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 &#123;
Date dateCreated
Date lastUpdated<p class="paragraph"/> def beforeInsert() &#123;
dateCreated = <span class="java&#45;keyword">new</span> Date()
&#125;
def beforeUpdate() &#123;
lastUpdated = <span class="java&#45;keyword">new</span> Date()
&#125;
&#125;</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 &#123;
<span class="java&#45;object">String</span> name
Date dateCreated
Date lastUpdated<p class="paragraph"/> def beforeDelete() &#123;
ActivityTrace.withNewSession &#123;
<span class="java&#45;keyword">new</span> ActivityTrace(eventName:<span class="java&#45;quote">"Person Deleted"</span>,data:name).save()
&#125;
&#125;
&#125;</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 &#123;
<span class="java&#45;object">String</span> name<p class="paragraph"/> <span class="java&#45;keyword">static</span> constraints = &#123;
name size: 5..45
&#125;<p class="paragraph"/> def beforeValidate() &#123;
name = name?.trim()
&#125;
&#125;</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 &#123;
<span class="java&#45;object">String</span> name
<span class="java&#45;object">String</span> town
<span class="java&#45;object">Integer</span> age<p class="paragraph"/> <span class="java&#45;keyword">static</span> constraints = &#123;
name size: 5..45
age range: 4..99
&#125;<p class="paragraph"/> def beforeValidate(List propertiesBeingValidated) &#123;
// <span class="java&#45;keyword">do</span> pre validation work based on propertiesBeingValidated
&#125;
&#125;<p class="paragraph"/>def p = <span class="java&#45;keyword">new</span> Person(name: 'Jacob Brown', age: 10)
p.validate(&#91;'age', 'name'&#93;)</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 &#123;
<span class="java&#45;object">String</span> name
Date dateCreated
Date lastUpdated<p class="paragraph"/> def onLoad() &#123;
log.debug <span class="java&#45;quote">"Loading &#36;&#123;id&#125;"</span>
&#125;
&#125;</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 &#123;
<span class="java&#45;object">String</span> name
Date dateCreated
Date lastUpdated<p class="paragraph"/> def afterLoad() &#123;
name = <span class="java&#45;quote">"I'm loaded"</span>
&#125;
&#125;</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 a single method called <code>onPersistenceEvent</code>. The simplest possible implementation can be seen below:<p class="paragraph"/><div class="code"><pre>@Override
<span class="java&#45;keyword">protected</span> void onPersistenceEvent(<span class="java&#45;keyword">final</span> AbstractPersistenceEvent event) &#123;
<span class="java&#45;keyword">switch</span>(event.eventType) &#123;
<span class="java&#45;keyword">case</span> PreInsert:
println <span class="java&#45;quote">"PRE INSERT &#36;&#123;event.entityObject&#125;"</span>
<span class="java&#45;keyword">break</span>
<span class="java&#45;keyword">case</span> PostInsert:
println <span class="java&#45;quote">"POST INSERT &#36;&#123;event.entityObject&#125;"</span>
<span class="java&#45;keyword">break</span>
<span class="java&#45;keyword">case</span> PreUpdate:
println <span class="java&#45;quote">"PRE UPDATE &#36;&#123;event.entityObject&#125;"</span>
<span class="java&#45;keyword">break</span>;
<span class="java&#45;keyword">case</span> PostUpdate:
println <span class="java&#45;quote">"POST UPDATE &#36;&#123;event.entityObject&#125;"</span>
<span class="java&#45;keyword">break</span>;
<span class="java&#45;keyword">case</span> PreDelete:
println <span class="java&#45;quote">"PRE DELETE &#36;&#123;event.entityObject&#125;"</span>
<span class="java&#45;keyword">break</span>;
<span class="java&#45;keyword">case</span> PostDelete:
println <span class="java&#45;quote">"POST DELETE &#36;&#123;event.entityObject&#125;"</span>
<span class="java&#45;keyword">break</span>;
<span class="java&#45;keyword">case</span> PreLoad:
println <span class="java&#45;quote">"PRE LOAD &#36;&#123;event.entityObject&#125;"</span>
<span class="java&#45;keyword">break</span>;
<span class="java&#45;keyword">case</span> PostLoad:
println <span class="java&#45;quote">"POST LOAD &#36;&#123;event.entityObject&#125;"</span>
<span class="java&#45;keyword">break</span>;
&#125;
&#125;</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 = &#123;
applicationContext.addApplicationListener(<span class="java&#45;keyword">new</span> MyPersistenceListener())
&#125;</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 = &#123;<p class="paragraph"/> auditListener(AuditEventListener)<p class="paragraph"/> hibernateEventListeners(HibernateEventListeners) &#123;
listenerMap = &#91;'post&#45;insert': auditListener,
'post&#45;update': auditListener,
'post&#45;delete': auditListener&#93;
&#125;
&#125;</pre></div><p class="paragraph"/>or use this in a plugin:<p class="paragraph"/><div class="code"><pre>def doWithSpring = &#123;<p class="paragraph"/> auditListener(AuditEventListener)<p class="paragraph"/> hibernateEventListeners(HibernateEventListeners) &#123;
listenerMap = &#91;'post&#45;insert': auditListener,
'post&#45;update': auditListener,
'post&#45;delete': auditListener&#93;
&#125;
&#125;</pre></div><p class="paragraph"/><h4>Automatic timestamping</h4><p class="paragraph"/>The examples above demonstrated using events to update a <code>lastUpdated</code> and <code>dateCreated</code> property to keep track of updates to objects. However, this is actually not necessary. By defining a <code>lastUpdated</code> and <code>dateCreated</code> property these will be automatically updated for you by GORM.<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 &#123;
Date dateCreated
Date lastUpdated
<span class="java&#45;keyword">static</span> mapping = &#123;
autoTimestamp <span class="java&#45;keyword">false</span>
&#125;
&#125;</pre></div><p class="paragraph"/><blockquote class="warning">
If you put <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. Leave constraints off these properties unless you have disabled automatic timestamping.
</blockquote>
<a name="5.5.2 Custom ORM Mapping"><!-- Legacy link --></a>
<h2 id="ormdsl">5.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 a static <code>mapping</code> block defined within your domain class:<p class="paragraph"/><div class="code"><pre>class Person &#123;
&#8230;
<span class="java&#45;keyword">static</span> mapping = &#123;<p class="paragraph"/> &#125;
&#125;</pre></div>
<a name="5.5.2.1 Table and Column Names"><!-- Legacy link --></a>
<h2 id="tableAndColumnNames">5.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 &#123;
&#8230;
<span class="java&#45;keyword">static</span> mapping = &#123;
table 'people'
&#125;
&#125;</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 &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> firstName<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
table 'people'
firstName column: 'First_Name'
&#125;
&#125;</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 specifing 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 &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> number
<span class="java&#45;object">String</span> postCode<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
postCode type: PostCodeType
&#125;
&#125;</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 &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> number
<span class="java&#45;object">String</span> postCode<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
postCode type: 'text'
&#125;
&#125;</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 &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> firstName
Address address<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
table 'people'
firstName column: 'First_Name'
address column: 'Person_Address_Id'
&#125;
&#125;</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 &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> firstName<p class="paragraph"/> <span class="java&#45;keyword">static</span> hasMany = &#91;addresses: Address&#93;<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
table 'people'
firstName column: 'First_Name'
addresses column: 'Person_Address_Id'
&#125;
&#125;</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 &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> firstName<p class="paragraph"/> <span class="java&#45;keyword">static</span> hasMany = &#91;addresses: Address&#93;<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
table 'people'
firstName column: 'First_Name'
addresses joinTable: &#91;name: 'Person_Addresses',
key: 'Person_Id',
column: 'Address_Id'&#93;
&#125;
&#125;</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 &#123;
&#8230;
<span class="java&#45;keyword">static</span> hasMany = &#91;people: Person&#93;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Person &#123;
&#8230;
<span class="java&#45;keyword">static</span> belongsTo = Group
<span class="java&#45;keyword">static</span> hasMany = &#91;groups: Group&#93;
&#125;</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 &#123;
&#8230;
<span class="java&#45;keyword">static</span> mapping = &#123;
people column: 'Group_Person_Id'
&#125;
&#125;
class Person &#123;
&#8230;
<span class="java&#45;keyword">static</span> mapping = &#123;
groups column: 'Group_Group_Id'
&#125;
&#125;</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 &#123;
&#8230;
<span class="java&#45;keyword">static</span> mapping = &#123;
people column: 'Group_Person_Id',
joinTable: 'PERSON_GROUP_ASSOCIATIONS'
&#125;
&#125;
class Person &#123;
&#8230;
<span class="java&#45;keyword">static</span> mapping = &#123;
groups column: 'Group_Group_Id',
joinTable: 'PERSON_GROUP_ASSOCIATIONS'
&#125;
&#125;</pre></div>
<a name="5.5.2.2 Caching Strategy"><!-- Legacy link --></a>
<h2 id="caching">5.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 &#123;
cache.use_second_level_cache=<span class="java&#45;keyword">true</span>
cache.use_query_cache=<span class="java&#45;keyword">true</span>
cache.provider_class='org.hibernate.cache.EhCacheProvider'
&#125;</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 &#123;
&#8230;
<span class="java&#45;keyword">static</span> mapping = &#123;
table 'people'
cache <span class="java&#45;keyword">true</span>
&#125;
&#125;</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 &#123;
&#8230;
<span class="java&#45;keyword">static</span> mapping = &#123;
table 'people'
cache usage: 'read&#45;only', include: 'non&#45;lazy'
&#125;
&#125;</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 &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> firstName<p class="paragraph"/> <span class="java&#45;keyword">static</span> hasMany = &#91;addresses: Address&#93;<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
table 'people'
version <span class="java&#45;keyword">false</span>
addresses column: 'Address', cache: <span class="java&#45;keyword">true</span>
&#125;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Address &#123;
<span class="java&#45;object">String</span> number
<span class="java&#45;object">String</span> postCode
&#125;</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&#45;write' // or 'read&#45;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&#45;quote">"Fred"</span>, &#91;cache: <span class="java&#45;keyword">true</span>&#93;)</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 &#123;
like('firstName', 'Fr%')
cache <span class="java&#45;keyword">true</span>
&#125;</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 (ie. 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">5.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 &#123;
<span class="java&#45;object">Integer</span> amount<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
tablePerHierarchy <span class="java&#45;keyword">false</span>
&#125;
&#125;<p class="paragraph"/>class CreditCardPayment <span class="java&#45;keyword">extends</span> Payment &#123;
<span class="java&#45;object">String</span> cardNumber
&#125;</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">5.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 &#123;
&#8230;
<span class="java&#45;keyword">static</span> mapping = &#123;
table 'people'
version <span class="java&#45;keyword">false</span>
id generator: 'hilo',
params: &#91;table: 'hi_value',
column: 'next_value',
max_lo: 100&#93;
&#125;
&#125;</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 &#123;
&#8230;
<span class="java&#45;keyword">static</span> mapping = &#123;
table 'people'
version <span class="java&#45;keyword">false</span>
id column: 'person_id'
&#125;
&#125;</pre></div>
<a name="5.5.2.5 Composite Primary Keys"><!-- Legacy link --></a>
<h2 id="compositePrimaryKeys">5.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&#45;keyword">import</span> org.apache.commons.lang.builder.HashCodeBuilder<p class="paragraph"/>class Person <span class="java&#45;keyword">implements</span> Serializable &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> firstName
<span class="java&#45;object">String</span> lastName<p class="paragraph"/> <span class="java&#45;object">boolean</span> equals(other) &#123;
<span class="java&#45;keyword">if</span> (!(other <span class="java&#45;keyword">instanceof</span> Person)) &#123;
<span class="java&#45;keyword">return</span> <span class="java&#45;keyword">false</span>
&#125;<p class="paragraph"/> other.firstName == firstName &#38;&#38; other.lastName == lastName
&#125;<p class="paragraph"/> <span class="java&#45;object">int</span> hashCode() &#123;
def builder = <span class="java&#45;keyword">new</span> HashCodeBuilder()
builder.append firstName
builder.append lastName
builder.toHashCode()
&#125;<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
id composite: &#91;'firstName', 'lastName'&#93;
&#125;
&#125;</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&#45;keyword">new</span> Person(firstName: <span class="java&#45;quote">"Fred"</span>, lastName: <span class="java&#45;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 &#123;
Person person
&#125;</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 &#123;
Person person
<span class="java&#45;keyword">static</span> mapping = &#123;
person &#123;
column: <span class="java&#45;quote">"FirstName"</span>
column: <span class="java&#45;quote">"LastName"</span>
&#125;
&#125;
&#125;</pre></div>
<a name="5.5.2.6 Database Indices"><!-- Legacy link --></a>
<h2 id="databaseIndices">5.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 &#123;
<span class="java&#45;object">String</span> firstName
<span class="java&#45;object">String</span> address
<span class="java&#45;keyword">static</span> mapping = &#123;
table 'people'
version <span class="java&#45;keyword">false</span>
id column: 'person_id'
firstName column: 'First_Name', index: 'Name_Idx'
address column: 'Address', index: 'Name_Idx,Address_Index'
&#125;
&#125;</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">5.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 &#123;
&#8230;
<span class="java&#45;keyword">static</span> mapping = &#123;
table 'people'
version <span class="java&#45;keyword">false</span>
&#125;
&#125;</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&#45;keyword">import</span> java.sql.Timestamp<p class="paragraph"/>class Person &#123;<p class="paragraph"/> &#8230;
Timestamp version<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
table 'people'
&#125;
&#125;</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">5.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 &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> firstName
Pet pet<p class="paragraph"/> <span class="java&#45;keyword">static</span> hasMany = &#91;addresses: Address&#93;<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
addresses lazy: <span class="java&#45;keyword">false</span>
pet fetch: 'join'
&#125;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Address &#123;
<span class="java&#45;object">String</span> street
<span class="java&#45;object">String</span> postCode
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Pet &#123;
<span class="java&#45;object">String</span> name
&#125;</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 &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> firstName
Pet pet<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
pet batchSize: 5
&#125;
&#125;</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 &#123;
<span class="java&#45;object">String</span> firstName
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Address &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> street
<span class="java&#45;object">String</span> postCode<p class="paragraph"/> <span class="java&#45;keyword">static</span> belongsTo = &#91;person: Person&#93;<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
person lazy: <span class="java&#45;keyword">false</span>
&#125;
&#125;</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 &#123;
<span class="java&#45;object">String</span> name
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Dog <span class="java&#45;keyword">extends</span> Pet &#123;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Person &#123;
<span class="java&#45;object">String</span> name
Pet pet
&#125;</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&#45;keyword">instanceof</span> Dog
assert Pet.get(person.petId) <span class="java&#45;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&#45;keyword">instanceof</span> Dog
assert Pet.list()&#91;0&#93; <span class="java&#45;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()&#91;0&#93; <span class="java&#45;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&#42;()</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&#42;()</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()&#91;0&#93;.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()&#91;0&#93;</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">5.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 &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> firstName<p class="paragraph"/> <span class="java&#45;keyword">static</span> hasMany = &#91;addresses: Address&#93;<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
addresses cascade: <span class="java&#45;quote">"all&#45;delete&#45;orphan"</span>
&#125;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Address &#123;
<span class="java&#45;object">String</span> street
<span class="java&#45;object">String</span> postCode
&#125;</pre></div>
<a name="5.5.2.10 Custom Hibernate Types"><!-- Legacy link --></a>
<h2 id="customHibernateTypes">5.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 &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> title
<span class="java&#45;object">String</span> author
Rating rating<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
rating type: RatingUserType
&#125;
&#125;</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 &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> title
Name author
Rating rating<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
name type: NameUserType, &#123;
column name: <span class="java&#45;quote">"first_name"</span>
column name: <span class="java&#45;quote">"last_name"</span>
&#125;
rating type: RatingUserType
&#125;
&#125;</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&#45;quote">"first_name"</span>, index: <span class="java&#45;quote">"my_idx"</span>, unique: <span class="java&#45;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 &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> title
Name author
Rating rating<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
name type: NameUserType, &#123;
column name: <span class="java&#45;quote">"first_name"</span>, sqlType: <span class="java&#45;quote">"text"</span>
column name: <span class="java&#45;quote">"last_name"</span>, sqlType: <span class="java&#45;quote">"text"</span>
&#125;
rating type: RatingUserType, sqlType: <span class="java&#45;quote">"text"</span>
&#125;
&#125;</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">5.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 &#123;
<span class="java&#45;object">Float</span> price
<span class="java&#45;object">Float</span> taxRate
<span class="java&#45;object">Float</span> tax
&#125;</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 &#123;
<span class="java&#45;object">Float</span> price
<span class="java&#45;object">Float</span> taxRate
<span class="java&#45;object">Float</span> tax<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
tax formula: 'PRICE &#42; TAX_RATE'
&#125;
&#125;</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 &#42; 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 &#123;
gt 'tax', 21.12f
&#125;</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 &#42; this_.TAX_RATE as formula1_0_
from
product this_
where
this_.PRICE &#42; this_.TAX_RATE&#62;?</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">5.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-instance 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 &#123;
pooled = <span class="java&#45;keyword">true</span>
dbCreate = <span class="java&#45;quote">"create&#45;drop"</span>
&#8230;
&#125;<p class="paragraph"/>hibernate &#123;
cache.use_second_level_cache = <span class="java&#45;keyword">true</span>
&#8230;
naming_strategy = com.myco.myproj.CustomNamingStrategy
&#125;</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&#45;keyword">package</span> com.myco.myproj<p class="paragraph"/><span class="java&#45;keyword">import</span> org.hibernate.cfg.ImprovedNamingStrategy
<span class="java&#45;keyword">import</span> org.hibernate.util.StringHelper<p class="paragraph"/>class CustomNamingStrategy <span class="java&#45;keyword">extends</span> ImprovedNamingStrategy &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> classToTableName(<span class="java&#45;object">String</span> className) &#123;
<span class="java&#45;quote">"table_"</span> + StringHelper.unqualify(className)
&#125;<p class="paragraph"/> <span class="java&#45;object">String</span> propertyToColumnName(<span class="java&#45;object">String</span> propertyName) &#123;
<span class="java&#45;quote">"col_"</span> + StringHelper.unqualify(propertyName)
&#125;
&#125;</pre></div><p class="paragraph"/>
<a name="5.5.3 Default Sort Order"><!-- Legacy link --></a>
<h2 id="defaultSortOrder">5.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 &#123;
&#8230;
<span class="java&#45;keyword">static</span> mapping = &#123;
sort <span class="java&#45;quote">"name"</span>
&#125;
&#125;</pre></div><p class="paragraph"/>The above means that all collections of <code>Airport</code>s 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 &#123;
&#8230;
<span class="java&#45;keyword">static</span> mapping = &#123;
sort name: <span class="java&#45;quote">"desc"</span>
&#125;
&#125;</pre></div><p class="paragraph"/>Finally, you can configure sorting at the association level:<p class="paragraph"/><div class="code"><pre>class Airport &#123;
&#8230;
<span class="java&#45;keyword">static</span> hasMany = &#91;flights: Flight&#93;<p class="paragraph"/> <span class="java&#45;keyword">static</span> mapping = &#123;
flights sort: 'number', order: 'desc'
&#125;
&#125;</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">5.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://static.springsource.org/spring/docs/3.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() &#123;
Account.withTransaction &#123; status &#45;&#62;
def source = Account.get(params.from)
def dest = Account.get(params.to)<p class="paragraph"/> def amount = params.amount.toInteger()
<span class="java&#45;keyword">if</span> (source.active) &#123;
<span class="java&#45;keyword">if</span> (dest.active) &#123;
source.balance &#45;= amount
dest.amount += amount
&#125;
<span class="java&#45;keyword">else</span> &#123;
status.setRollbackOnly()
&#125;
&#125;
&#125;
&#125;</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://static.springsource.org/spring/docs/3.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">5.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&#45;object">String</span> name
<span class="java&#45;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&#45;keyword">static</span> constraints = &#123;
description maxSize: 1000
&#125;</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&#45;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: &#45;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&#45;keyword">default</span> scale</pre></div>
<a name="6. The Web Layer"><!-- Legacy link --></a>
<h1 id="theWebLayer">6 The Web Layer</h1>
<a name="6.1 Controllers"><!-- Legacy link --></a>
<h2 id="controllers">6.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="6.1.1 Understanding Controllers and Actions"><!-- Legacy link --></a>
<h2 id="understandingControllersAndActions">6.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&#45;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&#45;keyword">package</span> myapp<p class="paragraph"/>class BookController &#123;<p class="paragraph"/> def index() &#123; &#125;
&#125;</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 &#123;<p class="paragraph"/> def list() &#123;<p class="paragraph"/> // <span class="java&#45;keyword">do</span> controller logic
// create model<p class="paragraph"/> <span class="java&#45;keyword">return</span> model
&#125;
&#125;</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&#45;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&#45;keyword">static</span> defaultAction = <span class="java&#45;quote">"list"</span></pre></div>
<a name="6.1.2 Controllers and Scopes"><!-- Legacy link --></a>
<h2 id="controllersAndScopes">6.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 &#123;
def find() &#123;
def findBy = params&#91;<span class="java&#45;quote">"findBy"</span>&#93;
def appContext = request&#91;<span class="java&#45;quote">"foo"</span>&#93;
def loggedUser = session&#91;<span class="java&#45;quote">"logged_user"</span>&#93;
&#125;
&#125;</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 &#123;
def find() &#123;
def findBy = params.findBy
def appContext = request.foo
def loggedUser = session.logged_user
&#125;
&#125;</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() &#123;
def b = Book.get(params.id)
<span class="java&#45;keyword">if</span> (!b) &#123;
flash.message = <span class="java&#45;quote">"User not found <span class="java&#45;keyword">for</span> id $&#123;params.id&#125;"</span>
redirect(action:list)
&#125;
&#8230; // remaining code
&#125;</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"/>By default, a new controller instance is created for each request. In fact, because the controller is <code>prototype</code> scoped, it is thread-safe since each request happens on its own thread.<p class="paragraph"/>You can change this behaviour by placing a controller in a particular scope. The supported 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&#45;keyword">static</span> scope = <span class="java&#45;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&#45;quote">"singleton"</span></pre></div><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. Setting a default scope other than <code>prototype</code> may also lead to unexpected behaviors if you have controllers provided by installed plugins that expect that the scope is <code>prototype</code>.
</blockquote>
<a name="6.1.3 Models and Views"><!-- Legacy link --></a>
<h2 id="modelsAndViews">6.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() &#123;
&#91;book: Book.get(params.id)&#93;
&#125;</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"/>If no explicit model is returned the controller's properties will be used as the model, thus allowing you to write code like this:<p class="paragraph"/><div class="code"><pre>class BookController &#123;<p class="paragraph"/> List books
List authors<p class="paragraph"/> def list() &#123;
books = Book.list()
authors = Author.list()
&#125;
&#125;</pre></div><p class="paragraph"/><blockquote class="note">
This is possible due to the fact that controllers are prototype scoped. In other words a new controller is created for each request. Otherwise code such as the above would not be thread-safe, and all users would share the same data.
</blockquote><p class="paragraph"/>In the above example the <code>books</code> and <code>authors</code> properties will be available in the view.<p class="paragraph"/>A more advanced approach is to return an instance of the Spring <a href="http://static.springsource.org/spring/docs/3.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&#45;keyword">import</span> org.springframework.web.servlet.ModelAndView<p class="paragraph"/>def index() &#123;
// get some books just <span class="java&#45;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&#45;keyword">return</span> <span class="java&#45;keyword">new</span> ModelAndView(<span class="java&#45;quote">"/book/list"</span>, &#91; bookList : favoriteBooks &#93;)
&#125;</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>list</code> action:<p class="paragraph"/><div class="code"><pre>class BookController &#123;
def show() &#123;
&#91;book: Book.get(params.id)&#93;
&#125;
&#125;</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() &#123;
def map = &#91;book: Book.get(params.id)&#93;
render(view: <span class="java&#45;quote">"display"</span>, model: map)
&#125;</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() &#123;
def map = &#91;book: Book.get(params.id)&#93;
render(view: <span class="java&#45;quote">"/shared/display"</span>, model: map)
&#125;</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.<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&#45;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 &#123;
<span class="java&#45;keyword">for</span> (b in books) &#123;
div(id: b.id, b.title)
&#125;
&#125;</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&#45;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&#45;quote">"&#60;xml&#62;some xml&#60;/xml&#62;"</span>, contentType: <span class="java&#45;quote">"text/xml"</span>, encoding: <span class="java&#45;quote">"UTF&#45;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&#45;keyword">import</span> groovy.xml.MarkupBuilder
&#8230;
def login() &#123;
def writer = <span class="java&#45;keyword">new</span> StringWriter()
def builder = <span class="java&#45;keyword">new</span> MarkupBuilder(writer)
builder.html &#123;
head &#123;
title 'Log in'
&#125;
body &#123;
h1 'Hello'
form &#123;
&#125;
&#125;
&#125;<p class="paragraph"/> def html = writer.toString()
render html
&#125;</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>&#60;form&#62;</code> element, use the following:<p class="paragraph"/><div class="code"><pre>def login() &#123;
// &#8230;
body &#123;
h1 'Hello'
builder.form &#123;
&#125;
&#125;
// &#8230;
&#125;</pre></div>
<a name="6.1.4 Redirects and Chaining"><!-- Legacy link --></a>
<h2 id="redirectsAndChaining">6.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 &#123;<p class="paragraph"/> def login() &#123;&#125;<p class="paragraph"/> def find() &#123;
<span class="java&#45;keyword">if</span> (!session.user)
redirect(action: 'login')
<span class="java&#45;keyword">return</span>
&#125;
&#8230;
&#125;
&#125;</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&#45;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&#45;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: &#91;myparam: <span class="java&#45;quote">"myvalue"</span>&#93;)</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&#45;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&#45;quote">"test"</span>, action: <span class="java&#45;quote">"show"</span>, fragment: <span class="java&#45;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 &#123;<p class="paragraph"/> def first() &#123;
chain(action: second, model: &#91;one: 1&#93;)
&#125;<p class="paragraph"/> def second () &#123;
chain(action: third, model: &#91;two: 2&#93;)
&#125;<p class="paragraph"/> def third() &#123;
&#91;three: 3&#93;)
&#125;
&#125;</pre></div><p class="paragraph"/>results in the model:<p class="paragraph"/><div class="code"><pre>&#91;one: 1, two: 2, three: 3&#93;</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 &#123;<p class="paragraph"/> def nextInChain() &#123;
def model = chainModel.myModel
&#8230;
&#125;
&#125;</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&#45;quote">"action1"</span>, model: &#91;one: 1&#93;, params: &#91;myparam: <span class="java&#45;quote">"param1"</span>&#93;)</pre></div>
<a name="6.1.5 Controller Interceptors"><!-- Legacy link --></a>
<h2 id="interceptors">6.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 <a href="../guide/single.html#filters" class="guide">Filter</a>. Filters 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 = &#123;
println <span class="java&#45;quote">"Tracing action $&#123;actionUri&#125;"</span>
&#125;</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 = &#91;action: <span class="java&#45;keyword">this</span>.&#38;auth, except: 'login'&#93;<p class="paragraph"/>// defined with <span class="java&#45;keyword">private</span> scope, so it's not considered an action
<span class="java&#45;keyword">private</span> auth() &#123;
<span class="java&#45;keyword">if</span> (!session.user) &#123;
redirect(action: 'login')
<span class="java&#45;keyword">return</span> <span class="java&#45;keyword">false</span>
&#125;
&#125;<p class="paragraph"/>def login() &#123;
// display login page
&#125;</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 = &#123; model &#45;&#62;
println <span class="java&#45;quote">"Tracing action $&#123;actionUri&#125;"</span>
&#125;</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://static.springsource.org/spring/docs/3.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 = &#123; model, modelAndView &#45;&#62;
println <span class="java&#45;quote">"Current view is $&#123;modelAndView.viewName&#125;"</span>
<span class="java&#45;keyword">if</span> (model.someVar) modelAndView.viewName = <span class="java&#45;quote">"/mycontroller/someotherview"</span>
println <span class="java&#45;quote">"View is now $&#123;modelAndView.viewName&#125;"</span>
&#125;</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 = &#91;action: <span class="java&#45;keyword">this</span>.&#38;auth, except: 'login'&#93;</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 = &#91;action: <span class="java&#45;keyword">this</span>.&#38;auth, except: &#91;'login', 'register'&#93;&#93;</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 = &#91;action: <span class="java&#45;keyword">this</span>.&#38;auth, only: &#91;'secure'&#93;&#93;</pre></div>
<a name="6.1.6 Data Binding"><!-- Legacy link --></a>
<h2 id="dataBinding">6.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"/>Grails uses <a href="http://www.springframework.org" target="blank">Spring</a>'s underlying data binding capability to perform data binding.<p class="paragraph"/><h4>Binding Request Data to the Model</h4><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() &#123;
def b = <span class="java&#45;keyword">new</span> Book(params)
b.save()
&#125;</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&#38;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() &#123;
def b = Book.get(params.id)
b.properties = params
b.save()
&#125;</pre></div><p class="paragraph"/>This has the same effect as using the implicit constructor.<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&#45;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&#45;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>&#60;g:select&#62;</code> below:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:select name=<span class="xml&#45;quote">"books"</span>
from=<span class="xml&#45;quote">"$&#123;Book.list()&#125;"</span>
size=<span class="xml&#45;quote">"5"</span> multiple=<span class="xml&#45;quote">"yes"</span> optionKey=<span class="xml&#45;quote">"id"</span>
value=<span class="xml&#45;quote">"$&#123;author?.books&#125;"</span> /&#62;</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&#45;tag">&#60;g:textField name=<span class="xml&#45;quote">"books&#91;0&#93;.title"</span> value=<span class="xml&#45;quote">"the Stand"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;g:textField name=<span class="xml&#45;quote">"books&#91;1&#93;.title"</span> value=<span class="xml&#45;quote">"the Shining"</span> /&#62;</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&#45;tag">&#60;g:textField name=<span class="xml&#45;quote">"books&#91;0&#93;.title"</span> value=<span class="xml&#45;quote">"the Stand"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;g:textField name=<span class="xml&#45;quote">"books&#91;1&#93;.title"</span> value=<span class="xml&#45;quote">"the Shining"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;g:textField name=<span class="xml&#45;quote">"books&#91;2&#93;.title"</span> value=<span class="xml&#45;quote">"Red Madder"</span> /&#62;</span></pre></div><p class="paragraph"/>Then Grails will automatically create a new instance for you at the defined position. If you "skipped" a few elements in the middle:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:textField name=<span class="xml&#45;quote">"books&#91;0&#93;.title"</span> value=<span class="xml&#45;quote">"the Stand"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;g:textField name=<span class="xml&#45;quote">"books&#91;1&#93;.title"</span> value=<span class="xml&#45;quote">"the Shining"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;g:textField name=<span class="xml&#45;quote">"books&#91;5&#93;.title"</span> value=<span class="xml&#45;quote">"Red Madder"</span> /&#62;</span></pre></div><p class="paragraph"/>Then Grails will automatically create instances in between. For example in the above case Grails will create 4 additional instances if the association being bound had a size of 2.<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&#45;tag">&#60;g:select name=<span class="xml&#45;quote">"books&#91;0&#93;.id"</span> from=<span class="xml&#45;quote">"$&#123;bookList&#125;"</span>
value=<span class="xml&#45;quote">"$&#123;author?.books&#91;0&#93;?.id&#125;"</span> /&#62;</span><p class="paragraph"/><span class="xml&#45;tag">&#60;g:select name=<span class="xml&#45;quote">"books&#91;1&#93;.id"</span> from=<span class="xml&#45;quote">"$&#123;bookList&#125;"</span>
value=<span class="xml&#45;quote">"$&#123;author?.books&#91;1&#93;?.id&#125;"</span> /&#62;</span><p class="paragraph"/><span class="xml&#45;tag">&#60;g:select name=<span class="xml&#45;quote">"books&#91;2&#93;.id"</span> from=<span class="xml&#45;quote">"$&#123;bookList&#125;"</span>
value=<span class="xml&#45;quote">"$&#123;author?.books&#91;2&#93;?.id&#125;"</span> /&#62;</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&#45;tag">&#60;g:select name=<span class="xml&#45;quote">"books&#91;0&#93;.id"</span>
from=<span class="xml&#45;quote">"$&#123;Book.list()&#125;"</span>
value=<span class="xml&#45;quote">"$&#123;author?.books&#91;0&#93;?.id&#125;"</span>
noSelection=<span class="xml&#45;quote">"&#91;'null': ''&#93;"</span>/&#62;</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&#45;tag">&#60;g:select name=<span class="xml&#45;quote">"images&#91;cover&#93;.id"</span>
from=<span class="xml&#45;quote">"$&#123;Image.list()&#125;"</span>
value=<span class="xml&#45;quote">"$&#123;book?.images&#91;cover&#93;?.id&#125;"</span>
noSelection=<span class="xml&#45;quote">"&#91;'null': ''&#93;"</span>/&#62;</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"/><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&#38;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&#45;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&#45;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://download.oracle.com/javase/1.5.0/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 &#123;<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&#45;object">String</span> accountNumber, <span class="java&#45;object">int</span> accountType) &#123;
// &#8230;
&#125;
&#125;</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&#38;accountType=bogusValue</pre></div><p class="paragraph"/>Since "bogusValue" cannot be converted to type int, the value of accountType will be zero, <code>controller.errors.hasErrors()</code> will be true, <code>controller.errors.errorCount</code> will be equal to 1 and <code>controller.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>&#64;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&#45;keyword">import</span> grails.web.RequestParameter<p class="paragraph"/>class AccountingController &#123;<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&#45;object">String</span> mainAccountNumber, <span class="java&#45;object">int</span> accountType) &#123;
// &#8230;
&#125;
&#125;</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 &#123;
&#8230;
URL publisherURL
&#125;</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&#45;bad&#45;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&#45;keyword">new</span> Book(params)<p class="paragraph"/><span class="java&#45;keyword">if</span> (b.hasErrors()) &#123;
println <span class="java&#45;quote">"The value $&#123;b.errors.getFieldError('publisherURL').rejectedValue&#125;"</span> +
<span class="java&#45;quote">" is not a valid URL!"</span>
&#125;</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 &#123;0&#125; 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>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&#91;'firstName','lastName'&#93; = 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&#45;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&#45;keyword">new</span> Person()
bindData(p, params, &#91;exclude: 'dateOfBirth'&#93;)</pre></div><p class="paragraph"/>Or include only certain properties:<p class="paragraph"/><div class="code"><pre>def p = <span class="java&#45;keyword">new</span> Person()
bindData(p, params, &#91;include: &#91;'firstName', 'lastName&#93;&#93;)</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">6.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() &#123;<p class="paragraph"/> def results = Book.list()<p class="paragraph"/> render(contentType: <span class="java&#45;quote">"text/xml"</span>) &#123;
books &#123;
<span class="java&#45;keyword">for</span> (b in results) &#123;
book(title: b.title)
&#125;
&#125;
&#125;
&#125;</pre></div><p class="paragraph"/>The result of this code would be something like:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;books&#62;</span>
<span class="xml&#45;tag">&#60;book title=<span class="xml&#45;quote">"The Stand"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;book title=<span class="xml&#45;quote">"The Shining"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;/books&#62;</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() &#123;<p class="paragraph"/> def books = Book.list() // naming conflict here<p class="paragraph"/> render(contentType: <span class="java&#45;quote">"text/xml"</span>) &#123;
books &#123;
<span class="java&#45;keyword">for</span> (b in results) &#123;
book(title: b.title)
&#125;
&#125;
&#125;
&#125;</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() &#123;<p class="paragraph"/> def results = Book.list()<p class="paragraph"/> render(contentType: <span class="java&#45;quote">"text/json"</span>) &#123;
books = array &#123;
<span class="java&#45;keyword">for</span> (b in results) &#123;
book title: b.title
&#125;
&#125;
&#125;
&#125;</pre></div><p class="paragraph"/>In this case the result would be something along the lines of:<p class="paragraph"/><div class="code"><pre>&#91;
&#123;title:<span class="java&#45;quote">"The Stand"</span>&#125;,
&#123;title:<span class="java&#45;quote">"The Shining"</span>&#125;
&#93;</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&#45;keyword">import</span> grails.converters.&#42;</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>&#60;?xml version=<span class="java&#45;quote">"1.0"</span> encoding=<span class="java&#45;quote">"ISO&#45;8859&#45;1"</span>?&#62;
&#60;list&#62;
&#60;book id=<span class="java&#45;quote">"1"</span>&#62;
&#60;author&#62;Stephen King&#60;/author&#62;
&#60;title&#62;The Stand&#60;/title&#62;
&#60;/book&#62;
&#60;book id=<span class="java&#45;quote">"2"</span>&#62;
&#60;author&#62;Stephen King&#60;/author&#62;
&#60;title&#62;The Shining&#60;/title&#62;
&#60;/book&#62;
&#60;/list&#62;</pre></div><p class="paragraph"/>An alternative to using the converters is to use the <a href="../guide/single.html#codecs" class="guide">codecs</a> feature of Grails. The codecs feature provides <a href="../guide/single.html#codecs" class="guide">encodeAsXML</a> and <a href="../guide/single.html#codecs" class="guide">encodeAsJSON</a> methods:<p class="paragraph"/><div class="code"><pre>def xml = Book.list().encodeAsXML()
render xml</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>&#91;
&#123;<span class="java&#45;quote">"id"</span>:1,
<span class="java&#45;quote">"class"</span>:<span class="java&#45;quote">"Book"</span>,
<span class="java&#45;quote">"author"</span>:<span class="java&#45;quote">"Stephen King"</span>,
<span class="java&#45;quote">"title"</span>:<span class="java&#45;quote">"The Stand"</span>&#125;,
&#123;<span class="java&#45;quote">"id"</span>:2,
<span class="java&#45;quote">"class"</span>:<span class="java&#45;quote">"Book"</span>,
<span class="java&#45;quote">"author"</span>:<span class="java&#45;quote">"Stephen King"</span>,
<span class="java&#45;quote">"releaseDate"</span>:<span class="java&#45;keyword">new</span> Date(1194127343161),
<span class="java&#45;quote">"title"</span>:<span class="java&#45;quote">"The Shining"</span>&#125;
&#93;</pre></div><p class="paragraph"/>Again as an alternative you can use the <code>encodeAsJSON</code> to achieve the same effect.
<a name="6.1.8 More on JSONBuilder"><!-- Legacy link --></a>
<h2 id="moreOnJSONBuilder">6.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="../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&#45;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&#45;quote">"text/json"</span>) &#123;
hello = <span class="java&#45;quote">"world"</span>
&#125;</pre></div><p class="paragraph"/>The above will produce the JSON:<p class="paragraph"/><div class="code"><pre>&#123;<span class="java&#45;quote">"hello"</span>:<span class="java&#45;quote">"world"</span>&#125;</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&#45;quote">"text/json"</span>) &#123;
categories = &#91;'a', 'b', 'c'&#93;
&#125;</pre></div><p class="paragraph"/>This will produce:<p class="paragraph"/><div class="code"><pre>&#123;<span class="java&#45;quote">"categories"</span>:&#91;<span class="java&#45;quote">"a"</span>,<span class="java&#45;quote">"b"</span>,<span class="java&#45;quote">"c"</span>&#93;&#125;</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&#45;quote">"text/json"</span>) &#123;
categories = &#91; &#123; a = <span class="java&#45;quote">"A"</span> &#125;, &#123; b = <span class="java&#45;quote">"B"</span> &#125; &#93;
&#125;</pre></div><p class="paragraph"/>This will produce:<p class="paragraph"/><div class="code"><pre>&#123;<span class="java&#45;quote">"categories"</span>:&#91; &#123;<span class="java&#45;quote">"a"</span>:<span class="java&#45;quote">"A"</span>&#125; , &#123;<span class="java&#45;quote">"b"</span>:<span class="java&#45;quote">"B"</span>&#125;&#93; &#125;</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&#45;quote">"text/json"</span>) &#123;
element 1
element 2
element 3
&#125;</pre></div><p class="paragraph"/>The above code produces:<p class="paragraph"/><div class="code"><pre>&#91;1,2,3&#93;</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&#45;quote">"text/json"</span>) &#123;
categories = &#91;'a', 'b', 'c'&#93;
title = <span class="java&#45;quote">"Hello JSON"</span>
information = &#123;
pages = 10
&#125;
&#125;</pre></div><p class="paragraph"/>The above will produce the JSON:<p class="paragraph"/><div class="code"><pre>&#123;<span class="java&#45;quote">"categories"</span>:&#91;<span class="java&#45;quote">"a"</span>,<span class="java&#45;quote">"b"</span>,<span class="java&#45;quote">"c"</span>&#93;,<span class="java&#45;quote">"title"</span>:<span class="java&#45;quote">"Hello JSON"</span>,<span class="java&#45;quote">"information"</span>:&#123;<span class="java&#45;quote">"pages"</span>:10&#125;&#125;</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&#45;quote">"text/json"</span>) &#123;
categories = &#91; &#123; a = <span class="java&#45;quote">"A"</span> &#125;, &#123; b = <span class="java&#45;quote">"B"</span> &#125; &#93;
&#125;</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&#45;quote">"text/json"</span>) &#123;
books = array &#123;
<span class="java&#45;keyword">for</span> (b in results) &#123;
book title: b.title
&#125;
&#125;
&#125;</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&#45;keyword">new</span> JSONBuilder()<p class="paragraph"/>def result = builder.build &#123;
categories = &#91;'a', 'b', 'c'&#93;
title = <span class="java&#45;quote">"Hello JSON"</span>
information = &#123;
pages = 10
&#125;
&#125;<p class="paragraph"/>// prints the JSON text
println result.toString()<p class="paragraph"/>def sw = <span class="java&#45;keyword">new</span> StringWriter()
result.render sw</pre></div>
<a name="6.1.9 Uploading Files"><!-- Legacy link --></a>
<h2 id="uploadingFiles">6.1.9 Uploading Files</h2>
<h4>Programmatic File Uploads</h4><p class="paragraph"/>Grails supports file uploads using Spring's <a href="http://static.springsource.org/spring/docs/3.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&#45;tag">&#60;br /&#62;</span>
<span class="xml&#45;tag">&#60;g:uploadForm action=<span class="xml&#45;quote">"upload"</span>&#62;</span>
<span class="xml&#45;tag">&#60;input type=<span class="xml&#45;quote">"file"</span> name=<span class="xml&#45;quote">"myFile"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;input type=<span class="xml&#45;quote">"submit"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;/g:uploadForm&#62;</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>&#60;g:form&#62;</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://static.springsource.org/spring/docs/3.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() &#123;
def f = request.getFile('myFile')
<span class="java&#45;keyword">if</span> (f.empty) &#123;
flash.message = 'file cannot be empty'
render(view: 'uploadForm')
<span class="java&#45;keyword">return</span>
&#125;<p class="paragraph"/> f.transferTo(<span class="java&#45;keyword">new</span> File('/some/local/dir/myfile.txt'))
response.sendError(200, 'Done')
&#125;</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://static.springsource.org/spring/docs/3.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 &#123;
<span class="java&#45;object">byte</span>&#91;&#93; myFile<p class="paragraph"/> <span class="java&#45;keyword">static</span> constraints = &#123;
// Limit upload file size to 2MB
myFile maxSize: 1024 &#42; 1024 &#42; 2
&#125;
&#125;</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&#45;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 &#123;
<span class="java&#45;object">String</span> myFile
&#125;</pre></div>
<a name="6.1.10 Command Objects"><!-- Legacy link --></a>
<h2 id="commandObjects">6.1.10 Command Objects</h2>
Grails controllers support the concept of command objects. A command object is similar to a form bean in a framework like Struts, and they are useful for populating a subset of the properties needed to update a domain class. Or where there is no domain class required for the interaction, but you need features such as <a href="../guide/single.html#dataBinding" class="guide">data binding</a> and <a href="../guide/single.html#validation" class="guide">validation</a>.<p class="paragraph"/><h4>Declaring Command Objects</h4><p class="paragraph"/>Command objects are typically declared in the same source file as a controller, directly below the controller class definition. For example:<p class="paragraph"/><div class="code"><pre>class UserController &#123;
&#8230;
&#125;<p class="paragraph"/>class LoginCommand &#123;
<span class="java&#45;object">String</span> username
<span class="java&#45;object">String</span> password<p class="paragraph"/> <span class="java&#45;keyword">static</span> constraints = &#123;
username(blank: <span class="java&#45;keyword">false</span>, minSize: 6)
password(blank: <span class="java&#45;keyword">false</span>, minSize: 6)
&#125;
&#125;</pre></div><p class="paragraph"/>As this example shows, you can define <a href="../guide/single.html#constraints" class="guide">constraints</a> in command objects just like in <a href="../guide/single.html#GORM" class="guide">domain classes</a>.<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, populate and validate.<p class="paragraph"/>Before the controller action is executed Grails will automatically create an instance of the command object class, populate its properties with by binding the request parameters, and validate the command object. For example:<p class="paragraph"/><div class="code"><pre>class LoginController &#123;<p class="paragraph"/> def login = &#123; LoginCommand cmd &#45;&#62;
<span class="java&#45;keyword">if</span> (cmd.hasErrors()) &#123;
redirect(action: 'loginForm')
<span class="java&#45;keyword">return</span>
&#125;<p class="paragraph"/> // work with the command object data
&#125;
&#125;</pre></div><p class="paragraph"/>When using methods instead of Closures for actions, you can specify command objects in arguments:<p class="paragraph"/><div class="code"><pre>class LoginController &#123;
def login(LoginCommand cmd) &#123;
<span class="java&#45;keyword">if</span> (cmd.hasErrors()) &#123;
redirect(action: 'loginForm')
<span class="java&#45;keyword">return</span>
&#125;<p class="paragraph"/> // work with the command object data
&#125;
&#125;</pre></div><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 uses Grails <a href="../guide/single.html#services" class="guide">services</a>:<p class="paragraph"/><div class="code"><pre>class LoginCommand &#123;<p class="paragraph"/> def loginService<p class="paragraph"/> <span class="java&#45;object">String</span> username
<span class="java&#45;object">String</span> password<p class="paragraph"/> <span class="java&#45;keyword">static</span> constraints = &#123;
username validator: &#123; val, obj &#45;&#62;
obj.loginService.canLogin(obj.username, obj.password)
&#125;
&#125;
&#125;</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>.
<a name="6.1.11 Handling Duplicate Form Submissions"><!-- Legacy link --></a>
<h2 id="formtokens">6.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&#45;tag">&#60;g:form useToken=<span class="xml&#45;quote">"true"</span> ...&#62;</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 &#123;
// good request
&#125;.invalidToken &#123;
// bad request
&#125;</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&#45;tag">&#60;g:if test=<span class="xml&#45;quote">"$&#123;flash.invalidToken&#125;"</span>&#62;</span>
Don't click the button twice!
<span class="xml&#45;tag">&#60;/g:if&#62;</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="6.1.12 Simple Type Converters"><!-- Legacy link --></a>
<h2 id="typeConverters">6.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&#45;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&#45;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&#38;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&#45;keyword">for</span> (name in params.list('name')) &#123;
println name
&#125;</pre></div>
<a name="6.1.13 Asynchronous Request Processing"><!-- Legacy link --></a>
<h2 id="asynchronousRequestProcessing">6.1.13 Asynchronous Request Processing</h2>
Grails support asynchronous request processing as provided by the Servlet 3.0 specification. 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&#45;quote">"3.0"</span></pre></div><p class="paragraph"/>With that done ensure you do a clean re-compile as some async features are enabled at compile time.<p class="paragraph"/><blockquote class="note">
With a Servlet target version of 3.0 you can only deploy on Servlet 3.0 containers such as Tomcat 7 and above.
</blockquote><p class="paragraph"/><h4>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() &#123;
def ctx = startAsync()
ctx.start &#123;
<span class="java&#45;keyword">new</span> Book(title:<span class="java&#45;quote">"The Stand"</span>).save()
render template:<span class="java&#45;quote">"books"</span>, model:&#91;books:Book.list()&#93;
ctx.complete()
&#125;
&#125;</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() &#123;
def ctx = startAsync()
ctx.start &#123;
// <span class="java&#45;keyword">do</span> working
&#8230;
// render view
ctx.dispatch()
&#125;
&#125;</pre></div>
<a name="6.2 Groovy Server Pages"><!-- Legacy link --></a>
<h2 id="gsp">6.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&#45;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() &#123;
&#91;book: Book.get(params.id)&#93;
&#125;</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>$&#123;book.title&#125;</pre></div>
<a name="6.2.1 GSP Basics"><!-- Legacy link --></a>
<h2 id="GSPBasics">6.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>&#60;% %&#62;</code> scriptlet blocks to embed Groovy code (again this is discouraged):<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;html&#62;</span>
<span class="xml&#45;tag">&#60;body&#62;</span>
<span class="xml&#45;tag">&#60;% out &#60;&#60; <span class="xml&#45;quote">"Hello GSP!"</span> %&#62;</span>
<span class="xml&#45;tag">&#60;/body&#62;</span>
<span class="xml&#45;tag">&#60;/html&#62;</span></pre></div><p class="paragraph"/>You can also use the <code>&#60;%= %&#62;</code> syntax to output values:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;html&#62;</span>
<span class="xml&#45;tag">&#60;body&#62;</span>
<span class="xml&#45;tag">&#60;%=<span class="xml&#45;quote">"Hello GSP!"</span> %&#62;</span>
<span class="xml&#45;tag">&#60;/body&#62;</span>
<span class="xml&#45;tag">&#60;/html&#62;</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&#45;tag">&#60;html&#62;</span>
<span class="xml&#45;tag">&#60;body&#62;</span>
<span class="xml&#45;tag">&#60;%&#45;&#45; This is my comment &#45;&#45;%&#62;</span>
<span class="xml&#45;tag">&#60;%=<span class="xml&#45;quote">"Hello GSP!"</span> %&#62;</span>
<span class="xml&#45;tag">&#60;/body&#62;</span>
<span class="xml&#45;tag">&#60;/html&#62;</span></pre></div>
<a name="6.6.3 Variables and Scopes"><!-- Legacy link --></a>
<h2 id="variablesAndScopes">6.2.1.1 Variables and Scopes</h2>
Within the <code>&#60;% %&#62;</code> brackets you can declare variables:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;% now = new Date() %&#62;</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&#45;tag">&#60;%=now%&#62;</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://static.springsource.org/spring/docs/3.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="../api/org/codehaus/groovy/grails/commons/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="../api/org/codehaus/groovy/grails/web/servlet/mvc/GrailsWebRequest.html" class="api">GrailsWebRequest</a> instance</li>
</ul><p class="paragraph"/>
<a name="6.2.2.2 Logic and Iteration"><!-- Legacy link --></a>
<h2 id="logicAndIteration">6.2.1.2 Logic and Iteration</h2>
Using the <code>&#60;% %&#62;</code> syntax you can embed loops and so on using this syntax:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;html&#62;</span>
<span class="xml&#45;tag">&#60;body&#62;</span>
<span class="xml&#45;tag">&#60;% &#91;1,2,3,4&#93;.each &#123; num &#45;&#62;</span> %&#62;
<span class="xml&#45;tag">&#60;p&#62;</span><span class="xml&#45;tag">&#60;%=<span class="xml&#45;quote">"Hello $&#123;num&#125;!"</span> %&#62;</span><span class="xml&#45;tag">&#60;/p&#62;</span>
<span class="xml&#45;tag">&#60;%&#125;%&#62;</span>
<span class="xml&#45;tag">&#60;/body&#62;</span>
<span class="xml&#45;tag">&#60;/html&#62;</span></pre></div><p class="paragraph"/>As well as logical branching:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;html&#62;</span>
<span class="xml&#45;tag">&#60;body&#62;</span>
<span class="xml&#45;tag">&#60;% if (params.hello == 'true')%&#62;</span>
<span class="xml&#45;tag">&#60;%=<span class="xml&#45;quote">"Hello!"</span>%&#62;</span>
<span class="xml&#45;tag">&#60;% else %&#62;</span>
<span class="xml&#45;tag">&#60;%=<span class="xml&#45;quote">"Goodbye!"</span>%&#62;</span>
<span class="xml&#45;tag">&#60;/body&#62;</span>
<span class="xml&#45;tag">&#60;/html&#62;</span></pre></div>
<a name="6.2.1.3 Page Directives"><!-- Legacy link --></a>
<h2 id="pageDirectives">6.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&#45;tag">&#60;%@ page import=<span class="xml&#45;quote">"java.awt.&#42;"</span> %&#62;</span></pre></div><p class="paragraph"/>GSP also supports the contentType directive:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;%@ page contentType=<span class="xml&#45;quote">"text/json"</span> %&#62;</span></pre></div><p class="paragraph"/>The contentType directive allows using GSP to render other formats.
<a name="6.2.1.4 Expressions"><!-- Legacy link --></a>
<h2 id="expressions">6.2.1.4 Expressions</h2>
In GSP the <code>&#60;%= %&#62;</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&#45;tag">&#60;html&#62;</span>
<span class="xml&#45;tag">&#60;body&#62;</span>
Hello $&#123;params.name&#125;
<span class="xml&#45;tag">&#60;/body&#62;</span>
<span class="xml&#45;tag">&#60;/html&#62;</span></pre></div><p class="paragraph"/>However, unlike JSP EL you can have any Groovy expression within the <code>${..}</code> block. Variables within the <code>${..}</code> block are <strong class="bold">not</strong> escaped by default, so any HTML in the variable's string is rendered directly to the page. To reduce the risk of Cross-site-scripting (XSS) attacks, you can enable automatic HTML escaping with the <code>grails.views.default.codec</code> setting in <code>grails-app/conf/Config.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.views.<span class="java&#45;keyword">default</span>.codec='html'</pre></div><p class="paragraph"/>Other possible values are 'none' (for no default encoding) and 'base64'.
<a name="6.2.2 GSP Tags"><!-- Legacy link --></a>
<h2 id="tags">6.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&#45;tag">&#60;g:example /&#62;</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&#45;tag">&#60;g:example&#62;</span>
Hello world
<span class="xml&#45;tag">&#60;/g:example&#62;</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&#45;tag">&#60;g:example attr=<span class="xml&#45;quote">"$&#123;new Date()&#125;"</span>&#62;</span>
Hello world
<span class="xml&#45;tag">&#60;/g:example&#62;</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&#45;tag">&#60;g:example attr=<span class="xml&#45;quote">"$&#123;new Date()&#125;"</span> attr2=<span class="xml&#45;quote">"&#91;one:1, two:2, three:3&#93;"</span>&#62;</span>
Hello world
<span class="xml&#45;tag">&#60;/g:example&#62;</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&#45;tag">&#60;g:example attr=<span class="xml&#45;quote">"$&#123;new Date()&#125;"</span> attr2=<span class="xml&#45;quote">"&#91;one:'one', two:'two'&#93;"</span>&#62;</span>
Hello world
<span class="xml&#45;tag">&#60;/g:example&#62;</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">6.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&#45;tag">&#60;g:set var=<span class="xml&#45;quote">"now"</span> value=<span class="xml&#45;quote">"$&#123;new Date()&#125;"</span> /&#62;</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>&#60;g:set&#62;</code> tag to define a variable:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:set var=<span class="xml&#45;quote">"myHTML"</span>&#62;</span>
Some re&#45;usable code on: $&#123;new Date()&#125;
<span class="xml&#45;tag">&#60;/g:set&#62;</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&#45;tag">&#60;g:set var=<span class="xml&#45;quote">"now"</span> value=<span class="xml&#45;quote">"$&#123;new Date()&#125;"</span> scope=<span class="xml&#45;quote">"request"</span> /&#62;</span></pre></div>
<h2 id="tagLogicAndIteration">6.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&#45;tag">&#60;g:if test=<span class="xml&#45;quote">"$&#123;session.role == 'admin'&#125;"</span>&#62;</span>
<span class="xml&#45;tag">&#60;%&#45;&#45; show administrative functions &#45;&#45;%&#62;</span>
<span class="xml&#45;tag">&#60;/g:if&#62;</span>
<span class="xml&#45;tag">&#60;g:else&#62;</span>
<span class="xml&#45;tag">&#60;%&#45;&#45; show basic functions &#45;&#45;%&#62;</span>
<span class="xml&#45;tag">&#60;/g:else&#62;</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&#45;tag">&#60;g:each in=<span class="xml&#45;quote">"$&#123;&#91;1,2,3&#93;&#125;"</span> var=<span class="xml&#45;quote">"num"</span>&#62;</span>
<span class="xml&#45;tag">&#60;p&#62;</span>Number $&#123;num&#125;<span class="xml&#45;tag">&#60;/p&#62;</span>
<span class="xml&#45;tag">&#60;/g:each&#62;</span><p class="paragraph"/><span class="xml&#45;tag">&#60;g:set var=<span class="xml&#45;quote">"num"</span> value=<span class="xml&#45;quote">"$&#123;1&#125;"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;g:while test=<span class="xml&#45;quote">"$&#123;num &#60; 5 &#125;"</span>&#62;</span>
<span class="xml&#45;tag">&#60;p&#62;</span>Number $&#123;num++&#125;<span class="xml&#45;tag">&#60;/p&#62;</span>
<span class="xml&#45;tag">&#60;/g:while&#62;</span></pre></div>
<a name="6.2.2.3 Search and Filtering"><!-- Legacy link --></a>
<h2 id="searchAndFiltering">6.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&#45;tag">&#60;g:findAll in=<span class="xml&#45;quote">"$&#123;books&#125;"</span> expr=<span class="xml&#45;quote">"it.author == 'Stephen King'"</span>&#62;</span>
<span class="xml&#45;tag">&#60;p&#62;</span>Title: $&#123;it.title&#125;<span class="xml&#45;tag">&#60;/p&#62;</span>
<span class="xml&#45;tag">&#60;/g:findAll&#62;</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&#45;tag">&#60;g:grep in=<span class="xml&#45;quote">"$&#123;books&#125;"</span> filter=<span class="xml&#45;quote">"NonFictionBooks.class"</span>&#62;</span>
<span class="xml&#45;tag">&#60;p&#62;</span>Title: $&#123;it.title&#125;<span class="xml&#45;tag">&#60;/p&#62;</span>
<span class="xml&#45;tag">&#60;/g:grep&#62;</span></pre></div><p class="paragraph"/>Or using a regular expression:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:grep in=<span class="xml&#45;quote">"$&#123;books.title&#125;"</span> filter=<span class="xml&#45;quote">"~/.&#42;?Groovy.&#42;?/"</span>&#62;</span>
<span class="xml&#45;tag">&#60;p&#62;</span>Title: $&#123;it&#125;<span class="xml&#45;tag">&#60;/p&#62;</span>
<span class="xml&#45;tag">&#60;/g:grep&#62;</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="6.2.2.4 Links and Resources"><!-- Legacy link --></a>
<h2 id="linksAndResources">6.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&#45;tag">&#60;g:link action=<span class="xml&#45;quote">"show"</span> id=<span class="xml&#45;quote">"1"</span>&#62;</span>Book 1<span class="xml&#45;tag">&#60;/g:link&#62;</span><p class="paragraph"/><span class="xml&#45;tag">&#60;g:link action=<span class="xml&#45;quote">"show"</span> id=<span class="xml&#45;quote">"$&#123;currentBook.id&#125;"</span>&#62;</span>$&#123;currentBook.name&#125;<span class="xml&#45;tag">&#60;/g:link&#62;</span><p class="paragraph"/><span class="xml&#45;tag">&#60;g:link controller=<span class="xml&#45;quote">"book"</span>&#62;</span>Book Home<span class="xml&#45;tag">&#60;/g:link&#62;</span><p class="paragraph"/><span class="xml&#45;tag">&#60;g:link controller=<span class="xml&#45;quote">"book"</span> action=<span class="xml&#45;quote">"list"</span>&#62;</span>Book List<span class="xml&#45;tag">&#60;/g:link&#62;</span><p class="paragraph"/><span class="xml&#45;tag">&#60;g:link url=<span class="xml&#45;quote">"&#91;action: 'list', controller: 'book'&#93;"</span>&#62;</span>Book List<span class="xml&#45;tag">&#60;/g:link&#62;</span><p class="paragraph"/><span class="xml&#45;tag">&#60;g:link params=<span class="xml&#45;quote">"&#91;sort: 'title', order: 'asc', author: currentBook.author&#93;"</span>
action=<span class="xml&#45;quote">"list"</span>&#62;</span>Book List<span class="xml&#45;tag">&#60;/g:link&#62;</span></pre></div>
<a name="6.2.2.5 Forms and Fields"><!-- Legacy link --></a>
<h2 id="formsAndFields">6.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&#45;tag">&#60;g:form name=<span class="xml&#45;quote">"myForm"</span> url=<span class="xml&#45;quote">"&#91;controller:'book',action:'list'&#93;"</span>&#62;</span>...<span class="xml&#45;tag">&#60;/g:form&#62;</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&#45;tag">&#60;g:textField name=<span class="xml&#45;quote">"myField"</span> value=<span class="xml&#45;quote">"$&#123;myValue&#125;"</span> /&#62;</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&#45;tag">&#60;g:actionSubmit value=<span class="xml&#45;quote">"Some update label"</span> action=<span class="xml&#45;quote">"update"</span> /&#62;</span></pre></div>
<a name="6.2.2.6 Tags as Method Calls"><!-- Legacy link --></a>
<h2 id="tagsAsMethodCalls">6.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: $&#123;createLinkTo(dir: <span class="xml&#45;quote">"images"</span>, file: <span class="xml&#45;quote">"logo.jpg"</span>)&#125;</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&#45;tag">&#60;img src=<span class="xml&#45;quote">"$&#123;createLinkTo(dir: 'images', file: 'logo.jpg')&#125;"</span> /&#62;</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 WYSWIG 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&#45;tag">&#60;img src=<span class="xml&#45;quote">"&#60;g:createLinkTo dir="</span>images<span class="xml&#45;quote">" file="</span>logo.jpg<span class="xml&#45;quote">" /&#62;</span>"</span> /&#62;</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&#45;quote">"images"</span>, file:<span class="java&#45;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&#45;quote">"images"</span>, file:<span class="java&#45;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&#45;quote">"text"</span>, width: <span class="java&#45;quote">"100%"</span>, height: <span class="java&#45;quote">"400"</span>)</pre></div>
<a name="6.2.3 Views and Templates"><!-- Legacy link --></a>
<h2 id="viewsAndTemplates">6.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&#45;tag">&#60;div class=<span class="xml&#45;quote">"book"</span> id=<span class="xml&#45;quote">"$&#123;book?.id&#125;"</span>&#62;</span>
<span class="xml&#45;tag">&#60;div&#62;</span>Title: $&#123;book?.title&#125;<span class="xml&#45;tag">&#60;/div&#62;</span>
<span class="xml&#45;tag">&#60;div&#62;</span>Author: $&#123;book?.author?.name&#125;<span class="xml&#45;tag">&#60;/div&#62;</span>
<span class="xml&#45;tag">&#60;/div&#62;</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&#45;tag">&#60;g:render template=<span class="xml&#45;quote">"bookTemplate"</span> model=<span class="xml&#45;quote">"&#91;book: myBook&#93;"</span> /&#62;</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&#45;tag">&#60;g:render template=<span class="xml&#45;quote">"bookTemplate"</span> var=<span class="xml&#45;quote">"book"</span> collection=<span class="xml&#45;quote">"$&#123;bookList&#125;"</span> /&#62;</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&#45;tag">&#60;g:render template=<span class="xml&#45;quote">"/shared/mySharedTemplate"</span> /&#62;</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&#45;tag">&#60;g:render template=<span class="xml&#45;quote">"/book/bookTemplate"</span> model=<span class="xml&#45;quote">"&#91;book: myBook&#93;"</span> /&#62;</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&#45;tag">&#60;g:render template=<span class="xml&#45;quote">"bookTemplate"</span> model=<span class="xml&#45;quote">"&#91;book:myBook&#93;"</span> /&#62;</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&#45;tag">&#60;tmpl:bookTemplate book=<span class="xml&#45;quote">"$&#123;myBook&#125;"</span> /&#62;</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 <a href="../guide/single.html#ajax" class="guide">Ajax</a> 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() &#123;
def b = Book.get(params.id)
render(template:<span class="java&#45;quote">"bookTemplate"</span>, model:&#91;book:b&#93;)
&#125;</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() &#123;
def b = Book.get(params.id)
<span class="java&#45;object">String</span> content = g.render(template:<span class="java&#45;quote">"bookTemplate"</span>, model:&#91;book:b&#93;)
render content
&#125;</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="6.2.4 Layouts with Sitemesh"><!-- Legacy link --></a>
<h2 id="layouts">6.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&#45;tag">&#60;html&#62;</span>
<span class="xml&#45;tag">&#60;head&#62;</span>
<span class="xml&#45;tag">&#60;title&#62;</span><span class="xml&#45;tag">&#60;g:layoutTitle default=<span class="xml&#45;quote">"An example decorator"</span> /&#62;</span><span class="xml&#45;tag">&#60;/title&#62;</span>
<span class="xml&#45;tag">&#60;g:layoutHead /&#62;</span>
<span class="xml&#45;tag">&#60;/head&#62;</span>
<span class="xml&#45;tag">&#60;body onload=<span class="xml&#45;quote">"$&#123;pageProperty(name:'body.onload')&#125;"</span>&#62;</span>
<span class="xml&#45;tag">&#60;div class=<span class="xml&#45;quote">"menu"</span>&#62;</span><span class="xml&#45;comment">&#60;!&#45;&#45;my common menu goes here&#45;&#45;&#62;</span><span class="xml&#45;tag">&#60;/menu&#62;</span>
<span class="xml&#45;tag">&#60;div class=<span class="xml&#45;quote">"body"</span>&#62;</span>
<span class="xml&#45;tag">&#60;g:layoutBody /&#62;</span>
<span class="xml&#45;tag">&#60;/div&#62;</span>
<span class="xml&#45;tag">&#60;/div&#62;</span>
<span class="xml&#45;tag">&#60;/body&#62;</span>
<span class="xml&#45;tag">&#60;/html&#62;</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&#45;tag">&#60;html&#62;</span>
<span class="xml&#45;tag">&#60;head&#62;</span>
<span class="xml&#45;tag">&#60;title&#62;</span>An Example Page<span class="xml&#45;tag">&#60;/title&#62;</span>
<span class="xml&#45;tag">&#60;meta name=<span class="xml&#45;quote">"layout"</span> content=<span class="xml&#45;quote">"main"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;/head&#62;</span>
<span class="xml&#45;tag">&#60;body&#62;</span>This is my content!<span class="xml&#45;tag">&#60;/body&#62;</span>
<span class="xml&#45;tag">&#60;/html&#62;</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&#45;tag">&#60;html&#62;</span>
<span class="xml&#45;tag">&#60;head&#62;</span>
<span class="xml&#45;tag">&#60;title&#62;</span>An Example Page<span class="xml&#45;tag">&#60;/title&#62;</span>
<span class="xml&#45;tag">&#60;/head&#62;</span>
<span class="xml&#45;tag">&#60;body onload=<span class="xml&#45;quote">""</span>&#62;</span>
<span class="xml&#45;tag">&#60;div class=<span class="xml&#45;quote">"menu"</span>&#62;</span><span class="xml&#45;comment">&#60;!&#45;&#45;my common menu goes here&#45;&#45;&#62;</span><span class="xml&#45;tag">&#60;/div&#62;</span>
<span class="xml&#45;tag">&#60;div class=<span class="xml&#45;quote">"body"</span>&#62;</span>
This is my content!
<span class="xml&#45;tag">&#60;/div&#62;</span>
<span class="xml&#45;tag">&#60;/body&#62;</span>
<span class="xml&#45;tag">&#60;/html&#62;</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 &#123;
<span class="java&#45;keyword">static</span> layout = 'customer'<p class="paragraph"/> def list() &#123; &#8230; &#125;
&#125;</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 &#123;
<span class="java&#45;keyword">static</span> layout = 'custom/customer'<p class="paragraph"/> def list() &#123; &#8230; &#125;
&#125;</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 &#123;
def list() &#123; &#8230; &#125;
&#125;</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&#45;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&#45;tag">&#60;g:applyLayout name=<span class="xml&#45;quote">"myLayout"</span> template=<span class="xml&#45;quote">"bookTemplate"</span> collection=<span class="xml&#45;quote">"$&#123;books&#125;"</span> /&#62;</span><p class="paragraph"/><span class="xml&#45;tag">&#60;g:applyLayout name=<span class="xml&#45;quote">"myLayout"</span> url=<span class="xml&#45;quote">"http://www.google.com"</span> /&#62;</span><p class="paragraph"/><span class="xml&#45;tag">&#60;g:applyLayout name=<span class="xml&#45;quote">"myLayout"</span>&#62;</span>
The content to apply a layout to
<span class="xml&#45;tag">&#60;/g:applyLayout&#62;</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&#45;tag">&#60;g:include controller=<span class="xml&#45;quote">"book"</span> action=<span class="xml&#45;quote">"list"</span> /&#62;</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&#45;tag">&#60;g:applyLayout name=<span class="xml&#45;quote">"myLayout"</span>&#62;</span>
<span class="xml&#45;tag">&#60;g:include controller=<span class="xml&#45;quote">"book"</span> action=<span class="xml&#45;quote">"list"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;/g:applyLayout&#62;</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&#45;quote">"book"</span>, action:<span class="java&#45;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="6.2.5 Static Resources"><!-- Legacy link --></a>
<h2 id="resources">6.2.5 Static Resources</h2>
Grails 2.0 integrates with the <a href="http://grails.org/plugin/resources" target="blank">Resources plugin</a> to provide sophisticated static resource management. This plugin is installed by default in new Grails applications.<p class="paragraph"/>The basic way to include a link to a static resource 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 Resources framework tackles are:
<ul class="star">
<li>Web application performance tuning is difficult</li>
<li>Correct ordering of resources, and deferred inclusion of JavaScript</li>
<li>Resources that depend on others that must be loaded first</li>
<li>The need for a standard way to expose static resources in plugins and applications</li>
<li>The need for an extensible processing chain to optimize resources</li>
<li>Preventing multiple inclusion of the same resource</li>
</ul><p class="paragraph"/>The plugin achieves this by introducing new artefacts and processing the resources using the server's local file system.<p class="paragraph"/>It adds artefacts for declaring resources, for declaring "mappers" that can process resources, and a servlet filter to serve processed resources.<p class="paragraph"/>What you get is an incredibly advanced resource system that enables you to easily create highly optimized web applications that run the same in development and in production.<p class="paragraph"/>The Resources plugin documentation provides a more detailed overview of the <a href="http://grails-plugins.github.com/grails-resources/" target="blank">concepts</a> which will be beneficial when reading the following guide.
<a name="6.2.5.1 Including resources using the resource tags"><!-- Legacy link --></a>
<h2 id="includingResourcesUsingTheResourceTags">6.2.5.1 Including resources using the resource tags</h2>
<h4>Pulling in resources with r:require</h4><p class="paragraph"/>To use resources, your GSP page must indicate which resource modules it requires. For example with the <a href="http://grails.org/plugin/jquery" target="blank">jQuery plugin</a>, which exposes a "jquery" resource module, to use jQuery in any page on your site you simply add:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;html&#62;</span>
<span class="xml&#45;tag">&#60;head&#62;</span>
<span class="xml&#45;tag">&#60;r:require module=<span class="xml&#45;quote">"jquery"</span>/&#62;</span>
<span class="xml&#45;tag">&#60;r:layoutResources/&#62;</span>
<span class="xml&#45;tag">&#60;/head&#62;</span>
<span class="xml&#45;tag">&#60;body&#62;</span>
&#8230;
<span class="xml&#45;tag">&#60;r:layoutResources/&#62;</span>
<span class="xml&#45;tag">&#60;/body&#62;</span>
<span class="xml&#45;tag">&#60;/html&#62;</span></pre></div><p class="paragraph"/>This will automatically include all resources needed for jQuery, including them at the correct locations in the page. By default the plugin sets the disposition to be "head", so they load early in the page.<p class="paragraph"/>You can call <code>r:require</code> multiple times in a GSP page, and you use the "modules" attribute to provide a list of modules:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;html&#62;</span>
<span class="xml&#45;tag">&#60;head&#62;</span>
<span class="xml&#45;tag">&#60;r:require modules=<span class="xml&#45;quote">"jquery, main, blueprint, charting"</span>/&#62;</span>
<span class="xml&#45;tag">&#60;r:layoutResources/&#62;</span>
<span class="xml&#45;tag">&#60;/head&#62;</span>
<span class="xml&#45;tag">&#60;body&#62;</span>
&#8230;
<span class="xml&#45;tag">&#60;r:layoutResources/&#62;</span>
<span class="xml&#45;tag">&#60;/body&#62;</span>
<span class="xml&#45;tag">&#60;/html&#62;</span></pre></div><p class="paragraph"/>The above may result in many JavaScript and CSS files being included, in the correct order, with some JavaScript files loading at the end of the body to improve the apparent page load time.<p class="paragraph"/>However you cannot use r:require in isolation - as per the examples you must have the &#60;r:layoutResources/&#62; tag to actually perform the render.<p class="paragraph"/><h4>Rendering the links to resources with r:layoutResources</h4><p class="paragraph"/>When you have declared the resource modules that your GSP page requires, the framework needs to render the links to those resources at the correct time.<p class="paragraph"/>To achieve this correctly, you must include the r:layoutResources tag twice in your page, or more commonly, in your GSP layout:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;html&#62;</span>
<span class="xml&#45;tag">&#60;head&#62;</span>
<span class="xml&#45;tag">&#60;g:layoutTitle/&#62;</span>
<span class="xml&#45;tag">&#60;r:layoutResources/&#62;</span>
<span class="xml&#45;tag">&#60;/head&#62;</span>
<span class="xml&#45;tag">&#60;body&#62;</span>
<span class="xml&#45;tag">&#60;g:layoutBody/&#62;</span>
<span class="xml&#45;tag">&#60;r:layoutResources/&#62;</span>
<span class="xml&#45;tag">&#60;/body&#62;</span>
<span class="xml&#45;tag">&#60;/html&#62;</span></pre></div><p class="paragraph"/>This represents the simplest Sitemesh layout you can have that supports Resources.<p class="paragraph"/>The Resources framework has the concept of a "disposition" for every resource. This is an indication of where in the page the resource should be included.<p class="paragraph"/>The default disposition applied depends on the type of resource. All CSS must be rendered in &#60;head&#62; in HTML, so "head" is the default for all CSS, and will be rendered by the first r:layoutResources. Page load times are improved when JavaScript is loaded after the page content, so the default for JavaScript files is "defer", which means it is rendered when the second r:layoutResources is invoked.<p class="paragraph"/>Note that both your GSP page and your Sitemesh layout (as well as any GSP template fragments) can call r:require to depend on resources. The only limitation is that you must call r:require before the r:layoutResources that should render it.<p class="paragraph"/><h4>Adding page-specific JavaScript code with r:script</h4><p class="paragraph"/>Grails has the <a href="../ref/Tags/javascript.html" class="tags">javascript</a> tag which is adapted to defer to Resources plugin if installed, but it is recommended that you call <code>r:script</code> directly when you need to include fragments of JavaScript code.<p class="paragraph"/>This lets you write some "inline" JavaScript which is actually <strong class="bold">not</strong> rendered inline, but either in the &#60;head&#62; or at the end of the body, based on the disposition.<p class="paragraph"/>Given a Sitemesh layout like this:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;html&#62;</span>
<span class="xml&#45;tag">&#60;head&#62;</span>
<span class="xml&#45;tag">&#60;g:layoutTitle/&#62;</span>
<span class="xml&#45;tag">&#60;r:layoutResources/&#62;</span>
<span class="xml&#45;tag">&#60;/head&#62;</span>
<span class="xml&#45;tag">&#60;body&#62;</span>
<span class="xml&#45;tag">&#60;g:layoutBody/&#62;</span>
<span class="xml&#45;tag">&#60;r:layoutResources/&#62;</span>
<span class="xml&#45;tag">&#60;/body&#62;</span>
<span class="xml&#45;tag">&#60;/html&#62;</span></pre></div><p class="paragraph"/>...in your GSP you can inject some JavaScript code into the head or deferred regions of the page like this:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;html&#62;</span>
<span class="xml&#45;tag">&#60;head&#62;</span>
<span class="xml&#45;tag">&#60;title&#62;</span>Testing r:script magic!<span class="xml&#45;tag">&#60;/title&#62;</span>
<span class="xml&#45;tag">&#60;/head&#62;</span>
<span class="xml&#45;tag">&#60;body&#62;</span>
<span class="xml&#45;tag">&#60;r:script disposition=<span class="xml&#45;quote">"head"</span>&#62;</span>
window.alert('This is at the end of <span class="xml&#45;tag">&#60;head&#62;</span>');
<span class="xml&#45;tag">&#60;/r:script&#62;</span>
<span class="xml&#45;tag">&#60;r:script disposition=<span class="xml&#45;quote">"defer"</span>&#62;</span>
window.alert('This is at the end of the body, and the page has loaded.');
<span class="xml&#45;tag">&#60;/r:script&#62;</span>
<span class="xml&#45;tag">&#60;/body&#62;</span>
<span class="xml&#45;tag">&#60;/html&#62;</span></pre></div><p class="paragraph"/>The default disposition is "defer", so the disposition in the latter r:script is purely included for demonstration.<p class="paragraph"/>Note that such r:script code fragments <strong class="bold">always</strong> load after any modules that you have used, to ensure that any required libraries have loaded.<p class="paragraph"/><h4>Linking to images with r:img</h4><p class="paragraph"/>This tag is used to render <code>&#60;img&#62;</code> markup, using the Resources framework to process the resource on the fly (if configured to do so - e.g. make it eternally cacheable).<p class="paragraph"/>This includes any extra attributes on the <code>&#60;img&#62;</code> tag if the resource has been previously declared in a module.<p class="paragraph"/>With this mechanism you can specify the width, height and any other attributes in the resource declaration in the module, and they will be pulled in as necessary.<p class="paragraph"/>Example:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;html&#62;</span>
<span class="xml&#45;tag">&#60;head&#62;</span>
<span class="xml&#45;tag">&#60;title&#62;</span>Testing r:img<span class="xml&#45;tag">&#60;/title&#62;</span>
<span class="xml&#45;tag">&#60;/head&#62;</span>
<span class="xml&#45;tag">&#60;body&#62;</span>
<span class="xml&#45;tag">&#60;r:img uri=<span class="xml&#45;quote">"/images/logo.png"</span>/&#62;</span>
<span class="xml&#45;tag">&#60;/body&#62;</span>
<span class="xml&#45;tag">&#60;/html&#62;</span></pre></div><p class="paragraph"/>Note that Grails has a built-in <code>g:img</code> tag as a shortcut for rendering <code>&#60;img&#62;</code> tags that refer to a static resource. The Grails <a href="../ref/Tags/img.html" class="tags">img</a> tag is Resources-aware and will delegate to <code>r:img</code> if found. However it is recommended that you use <code>r:img</code> directly if using the Resources plugin.<p class="paragraph"/>Alongside the regular Grails <a href="../ref/Tags/resource.html" class="tags">resource</a> tag attributes, this also supports the "uri" attribute for increased brevity.<p class="paragraph"/>See <a href="http://grails-plugins.github.com/grails-resources" target="blank">r:resource documentation</a> for full details.
<a name="6.2.5.2 Other resource tags"><!-- Legacy link --></a>
<h2 id="otherResourceTags">6.2.5.2 Other resource tags</h2>
<h4>r:resource</h4><p class="paragraph"/>This is equivalent to the Grails <a href="../ref/Tags/resource.html" class="Tags">resource</a> tag, returning a link to the processed static resource. Grails' own <code>g:resource</code> tag delegates to this implementation if found, but if your code requires the Resources plugin, you should use <code>r:resource</code> directly.<p class="paragraph"/>Alongside the regular Grails <a href="../ref/Tags/resource.html" class="Tags">resource</a> tag attributes, this also supports the "uri" attribute for increased brevity.<p class="paragraph"/>See <a href="http://grails-plugins.github.com/grails-resources" target="blank">r:resource documentation</a> for full details.<p class="paragraph"/><h4>r:external</h4><p class="paragraph"/>This is a resource-aware version of Grails <a href="../ref/Tags/external.html" class="Tags">external</a> tag which renders the HTML markup necessary to include an external file resource such as CSS, JS or a favicon.<p class="paragraph"/>See <a href="http://grails-plugins.github.com/grails-resources" target="blank">r:resource documentation</a> for full details.
<a name="6.2.5.3 Declaring resources"><!-- Legacy link --></a>
<h2 id="declaringResources">6.2.5.3 Declaring resources</h2>
A DSL is provided for declaring resources and modules. This can go either in your <code>Config.groovy</code> in the case of application-specific resources, or more commonly in a resources artefact in <code>grails-app/conf</code>.<p class="paragraph"/>Note that you do not need to declare all your static resources, especially images. However you must to establish dependencies or other resources-specific attributes. Any resource that is not declared is called "ad-hoc" and will still be processed using defaults for that resource type.<p class="paragraph"/>Consider this example resource configuration file, <code>grails-app/conf/MyAppResources.groovy</code>:<p class="paragraph"/><div class="code"><pre>modules = &#123;
core &#123;
dependsOn 'jquery, utils'<p class="paragraph"/> resource url: '/js/core.js', disposition: 'head'
resource url: '/js/ui.js'
resource url: '/css/main.css',
resource url: '/css/branding.css'
resource url: '/css/print.css', attrs: &#91;media: 'print'&#93;
&#125;<p class="paragraph"/> utils &#123;
dependsOn 'jquery'<p class="paragraph"/> resource url: '/js/utils.js'
&#125;<p class="paragraph"/> forms &#123;
dependsOn 'core,utils'<p class="paragraph"/> resource url: '/css/forms.css'
resource url: '/js/forms.js'
&#125;
&#125;</pre></div><p class="paragraph"/>This defines three resource modules; 'core', 'utils' and 'forms'. The resources in these modules will be automatically bundled out of the box according to the module name, resulting in fewer files. You can override this with <code>bundle:'someOtherName'</code> on each resource, or call <code>defaultBundle</code> on the module (see <a href="http://grails-plugins.github.com/grails-resources" target="blank">resources plugin documentation</a>).<p class="paragraph"/>It declares dependencies between them using <code>dependsOn</code>, which controls the load order of the resources.<p class="paragraph"/>When you include an <code>&#60;r:require module="forms"/&#62;</code> in your GSP, it will pull in all the resources from 'core' and 'utils' as well as 'jquery', all in the correct order.<p class="paragraph"/>You'll also notice the <code>disposition:'head'</code> on the <code>core.js</code> file. This tells Resources that while it can defer all the other JS files to the end of the body, this one must go into the <code>&#60;head&#62;</code>.<p class="paragraph"/>The CSS file for print styling adds custom attributes using the <code>attrs</code> map option, and these are passed through to the <code>r:external</code> tag when the engine renders the link to the resource, so you can customize the HTML attributes of the generated link.<p class="paragraph"/>There is no limit to the number of modules or xxxResources.groovy artefacts you can provide, and plugins can supply them to expose modules to applications, which is exactly how the jQuery plugin works.<p class="paragraph"/>To define modules like this in your application's Config.groovy, you simply assign the DSL closure to the <code>grails.resources.modules</code> Config variable.<p class="paragraph"/>For full details of the resource DSL please see the <a href="http://grails-plugins.github.com/grails-resources" target="blank">resources plugin documentation</a>.
<a name="6.2.5.4 Overriding plugin resources"><!-- Legacy link --></a>
<h2 id="overridingPluginResources">6.2.5.4 Overriding plugin resources</h2>
Because a resource module can define the bundle groupings and other attributes of resources, you may find that the settings provided are not correct for your application.<p class="paragraph"/>For example, you may wish to bundle jQuery and some other libraries all together in one file. There is a load-time and caching trade-off here, but often it is the case that you'd like to override some of these settings.<p class="paragraph"/>To do this, the DSL supports an "overrides" clause, within which you can change the <code>defaultBundle</code> setting for a module, or attributes of individual resources that have been declared with a unique id:<p class="paragraph"/><div class="code"><pre>modules = &#123;
core &#123;
dependsOn 'jquery, utils'
defaultBundle 'monolith'<p class="paragraph"/> resource url: '/js/core.js', disposition: 'head'
resource url: '/js/ui.js'
resource url: '/css/main.css',
resource url: '/css/branding.css'
resource url: '/css/print.css', attrs: &#91;media: 'print'&#93;
&#125;<p class="paragraph"/> utils &#123;
dependsOn 'jquery'
defaultBundle 'monolith'<p class="paragraph"/> resource url: '/js/utils.js'
&#125;<p class="paragraph"/> forms &#123;
dependsOn 'core,utils'
defaultBundle 'monolith'<p class="paragraph"/> resource url: '/css/forms.css'
resource url: '/js/forms.js'
&#125;<p class="paragraph"/> overrides &#123;
jquery &#123;
defaultBundle 'monolith'
&#125;
&#125;
&#125;</pre></div><p class="paragraph"/>This will put all code into a single bundle named 'monolith'. Note that this can still result in multiple files, as separate bundles are required for head and defer dispositions, and JavaScript and CSS files are bundled separately.<p class="paragraph"/>Note that overriding individual resources requires the original declaration to have included a unique id for the resource.<p class="paragraph"/>For full details of the resource DSL please see the <a href="http://grails-plugins.github.com/grails-resources" target="blank">resources plugin documentation</a>.
<a name="6.2.5.5 Optimizing your resources"><!-- Legacy link --></a>
<h2 id="optimizingYourResources">6.2.5.5 Optimizing your resources</h2>
The Resources framework uses "mappers" to mutate the resources into the final format served to the user.<p class="paragraph"/>The resource mappers are applied to each static resource once, in a specific order. You can create your own resource mappers, and several plugins provide some already for zipping, caching and minifying.<p class="paragraph"/>Out of the box, the Resources plugin provides bundling of resources into fewer files, which is achieved with a few mappers that also perform CSS re-writing to handle when your CSS files are moved into a bundle.<p class="paragraph"/><h4>Bundling multiple resources into fewer files</h4><p class="paragraph"/>The 'bundle' mapper operates by default on any resource with a "bundle" defined - or inherited from a <code>defaultBundle</code> clause on the module. Modules have an implicit default bundle name the same as the name of the module.<p class="paragraph"/>Files of the same kind will be aggregated into this bundle file. Bundles operate across module boundaries:<p class="paragraph"/><div class="code"><pre>modules = &#123;
core &#123;
dependsOn 'jquery, utils'
defaultBundle 'common'<p class="paragraph"/> resource url: '/js/core.js', disposition: 'head'
resource url: '/js/ui.js', bundle: 'ui'
resource url: '/css/main.css', bundle: 'theme'
resource url: '/css/branding.css'
resource url: '/css/print.css', attrs: &#91;media: 'print'&#93;
&#125;<p class="paragraph"/> utils &#123;
dependsOn 'jquery'<p class="paragraph"/> resource url: '/js/utils.js', bundle: 'common'
&#125;<p class="paragraph"/> forms &#123;
dependsOn 'core,utils'<p class="paragraph"/> resource url: '/css/forms.css', bundle: 'ui'
resource url: '/js/forms.js', bundle: 'ui'
&#125;
&#125;</pre></div><p class="paragraph"/>Here you see that resources are grouped into bundles; 'common', 'ui' and 'theme' - across module boundaries.<p class="paragraph"/>Note that auto-bundling by module does <strong class="bold">not</strong> occur if there is only one resource in the module.<p class="paragraph"/><h4>Making resources cache "eternally" in the client browser</h4><p class="paragraph"/>Caching resources "eternally" in the client is only viable if the resource has a unique name that changes whenever the contents change, and requires caching headers to be set on the response.<p class="paragraph"/>The <a href="http://grails.org/plugin/cached-resources" target="blank">cached-resources</a> plugin provides a mapper that achieves this by hashing your files and renaming them based on this hash. It also sets the caching headers on every response for those resources. To use, simply install the cached-resources plugin.<p class="paragraph"/>Note that the caching headers can only be set if your resources are being served by your application. If you have another server serving the static content from your app (e.g. Apache HTTPD), configure it to send caching headers. Alternatively you can configure it to request and proxy the resources from your container.<p class="paragraph"/><h4>Zipping resources</h4><p class="paragraph"/>Returning gzipped resources is another way to reduce page load times and reduce bandwidth.<p class="paragraph"/>The <a href="http://grails.org/plugin/zipped-resources" target="blank">zipped-resources</a> plugin provides a mapper that automatically compresses your content, excluding by default already compressed formats such as gif, jpeg and png.<p class="paragraph"/>Simply install the zipped-resources plugin and it works.<p class="paragraph"/><h4>Minifying</h4><p class="paragraph"/>There are a number of CSS and JavaScript minifiers available to obfuscate and reduce the size of your code. At the time of writing none are publicly released but releases are imminent.
<a name="6.2.5.6 Debugging"><!-- Legacy link --></a>
<h2 id="debugging">6.2.5.6 Debugging</h2>
When your resources are being moved around, renamed and otherwise mutated, it can be hard to debug client-side issues. Modern browsers, especially Safari, Chrome and Firefox have excellent tools that let you view all the resources requested by a page, including the headers and other information about them.<p class="paragraph"/>There are several debugging features built in to the Resources framework.<p class="paragraph"/><h4>X-Grails-Resources-Original-Src Header</h4><p class="paragraph"/>Every resource served in development mode will have the X-Grails-Resources-Original-Src: header added, indicating the original source file(s) that make up the response.<p class="paragraph"/><h4>Adding the debug flag</h4><p class="paragraph"/>If you add a query parameter <strong class="bold">_debugResources=y</strong> to your URL and request the page, Resources will bypass any processing so that you can see your original source files.<p class="paragraph"/>This also adds a unique timestamp to all your resource URLs, to defeat any caching that browsers may use. This means that you should always see your very latest code when you reload the page.<p class="paragraph"/><h4>Turning on debug all the time</h4><p class="paragraph"/>You can turn on the aforementioned debug mechanism without requiring a query parameter, but turning it on in Config.groovy:<p class="paragraph"/><div class="code"><pre>grails.resources.debug = <span class="java&#45;keyword">true</span></pre></div><p class="paragraph"/>You can of course set this per-environment.
<a name="6.2.5.7 Preventing processing of resources"><!-- Legacy link --></a>
<h2 id="preventingProcessingOfResources">6.2.5.7 Preventing processing of resources</h2>
Sometimes you do not want a resource to be processed in a particular way, or even at all. Occasionally you may also want to disable all resource mapping.<p class="paragraph"/><h4>Preventing the application of a specific mapper to an individual resource</h4><p class="paragraph"/>All resource declarations support a convention of noXXXX:true where XXXX is a mapper name.<p class="paragraph"/>So for example to prevent the "hashandcache" mapper from being applied to a resource (which renames and moves it, potentially breaking relative links written in JavaScript code), you would do this:<p class="paragraph"/><div class="code"><pre>modules = &#123;
forms &#123;
resource url: '/css/forms.css', nohashandcache: <span class="java&#45;keyword">true</span>
resource url: '/js/forms.js', nohashandcache: <span class="java&#45;keyword">true</span>
&#125;
&#125;</pre></div><p class="paragraph"/><h4>Excluding/including paths and file types from specific mappers</h4><p class="paragraph"/>Mappers have includes/excludes Ant patterns to control whether they apply to a given resource. Mappers set sensible defaults for these based on their activity, for example the zipped-resources plugin's "zip" mapper is set to exclude images by default.<p class="paragraph"/>You can configure this in your <code>Config.groovy</code> using the mapper name e.g:<p class="paragraph"/><div class="code"><pre>// We wouldn't link to .exe files using Resources but <span class="java&#45;keyword">for</span> the sake of example:
grails.resources.zip.excludes = &#91;'&#42;&#42;/&#42;.zip', '&#42;&#42;/&#42;.exe'&#93;<p class="paragraph"/>// Perhaps <span class="java&#45;keyword">for</span> some reason we want to prevent bundling on <span class="java&#45;quote">"less"</span> CSS files:
grails.resources.bundle.excludes = &#91;'&#42;&#42;/&#42;.less'&#93;</pre></div><p class="paragraph"/>There is also an "includes" inverse. Note that settings these replaces the default includes/excludes for that mapper - it is not additive.<p class="paragraph"/><h4>Controlling what is treated as an "ad-hoc" (legacy) resource</h4><p class="paragraph"/>Ad-hoc resources are those undeclared, but linked to directly in your application <strong class="bold">without</strong> using the Grails or Resources linking tags (resource, img or external).<p class="paragraph"/>These may occur with some legacy plugins or code with hardcoded paths in.<p class="paragraph"/>There is a Config.groovy setting <strong class="bold">grails.resources.adhoc.patterns</strong> which defines a list of Servlet API compliant filter URI mappings, which the Resources filter will use to detect such "ad-hoc resource" requests.<p class="paragraph"/>By default this is set to:
<div class="code"><pre>grails.resources.adhoc.patterns = &#91;'images/&#42;', '&#42;.js', '&#42;.css'&#93;</pre></div>
<a name="6.2.5.8 Other Resources-aware plugins"><!-- Legacy link --></a>
<h2 id="otherResourcesPlugins">6.2.5.8 Other Resources-aware plugins</h2>
At the time of writing, the following plugins include support for the Resources framework:
<ul class="star">
<li><a href="http://grails.org/plugin/jquery" target="blank">jquery</a></li>
<li><a href="http://grails.org/plugin/jquery-ui" target="blank">jquery-ui</a></li>
<li><a href="http://grails.org/plugin/blueprint" target="blank">blueprint</a></li>
<li><a href="http://grails.org/plugin/lesscss-resources" target="blank">lesscss-resources</a></li>
<li><a href="http://grails.org/plugin/zipped-resources" target="blank">zipped-resources</a></li>
<li><a href="http://grails.org/plugin/cached-resources" target="blank">cached-resources</a></li>
</ul><p class="paragraph"/>
<a name="6.2.6 Sitemesh Content Blocks"><!-- Legacy link --></a>
<h2 id="sitemeshContentBlocks">6.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>&#60;content&#62;</code> tag:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;content tag=<span class="xml&#45;quote">"navbar"</span>&#62;</span>
&#8230; draw the navbar here&#8230;
<span class="xml&#45;tag">&#60;/content&#62;</span><p class="paragraph"/><span class="xml&#45;tag">&#60;content tag=<span class="xml&#45;quote">"header"</span>&#62;</span>
&#8230; draw the header here&#8230;
<span class="xml&#45;tag">&#60;/content&#62;</span><p class="paragraph"/><span class="xml&#45;tag">&#60;content tag=<span class="xml&#45;quote">"footer"</span>&#62;</span>
&#8230; draw the footer here&#8230;
<span class="xml&#45;tag">&#60;/content&#62;</span><p class="paragraph"/><span class="xml&#45;tag">&#60;content tag=<span class="xml&#45;quote">"body"</span>&#62;</span>
&#8230; draw the body here&#8230;
<span class="xml&#45;tag">&#60;/content&#62;</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&#45;tag">&#60;html&#62;</span>
<span class="xml&#45;tag">&#60;body&#62;</span>
<span class="xml&#45;tag">&#60;div id=<span class="xml&#45;quote">"header"</span>&#62;</span>
<span class="xml&#45;tag">&#60;g:applyLayout name=<span class="xml&#45;quote">"headerLayout"</span>&#62;</span>
<span class="xml&#45;tag">&#60;g:pageProperty name=<span class="xml&#45;quote">"page.header"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;/g:applyLayout&#62;</span>
<span class="xml&#45;tag">&#60;/div&#62;</span>
<span class="xml&#45;tag">&#60;div id=<span class="xml&#45;quote">"nav"</span>&#62;</span>
<span class="xml&#45;tag">&#60;g:applyLayout name=<span class="xml&#45;quote">"navLayout"</span>&#62;</span>
<span class="xml&#45;tag">&#60;g:pageProperty name=<span class="xml&#45;quote">"page.navbar"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;/g:applyLayout&#62;</span>
<span class="xml&#45;tag">&#60;/div&#62;</span>
<span class="xml&#45;tag">&#60;div id=<span class="xml&#45;quote">"body"</span>&#62;</span>
<span class="xml&#45;tag">&#60;g:applyLayout name=<span class="xml&#45;quote">"bodyLayout"</span>&#62;</span>
<span class="xml&#45;tag">&#60;g:pageProperty name=<span class="xml&#45;quote">"page.body"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;/g:applyLayout&#62;</span>
<span class="xml&#45;tag">&#60;/div&#62;</span>
<span class="xml&#45;tag">&#60;div id=<span class="xml&#45;quote">"footer"</span>&#62;</span>
<span class="xml&#45;tag">&#60;g:applyLayout name=<span class="xml&#45;quote">"footerLayout"</span>&#62;</span>
<span class="xml&#45;tag">&#60;g:pageProperty name=<span class="xml&#45;quote">"page.footer"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;/g:applyLayout&#62;</span>
<span class="xml&#45;tag">&#60;/div&#62;</span>
<span class="xml&#45;tag">&#60;/body&#62;</span>
<span class="xml&#45;tag">&#60;/html&#62;</span></pre></div>
<a name="6.2.7 Making Changes to a Deployed Application"><!-- Legacy link --></a>
<h2 id="makingChangesToADeployedApplication">6.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&#45;keyword">true</span>
grails.gsp.view.dir = <span class="java&#45;quote">"/<span class="java&#45;keyword">var</span>/www/grails/my&#45;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 &#45;p /<span class="java&#45;keyword">var</span>/www/grails/my&#45;app/grails&#45;app/views
cp &#45;R grails&#45;app/views/&#42; /<span class="java&#45;keyword">var</span>/www/grails/my&#45;app/grails&#45;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>altervative system property for enabling the GSP reload mode without changing Config.groovy</td><td>&#160;</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="6.2.8 GSP Debugging"><!-- Legacy link --></a>
<h2 id="GSPDebugging">6.2.8 GSP Debugging</h2>
<h4>Viewing the generated source code</h4>
<ul class="star">
<li>Adding "?showSource=true" or "&#38;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 "&#38;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>&#60;!&#45;&#45; GSP &#35;2 START template: /home/.../views/_carousel.gsp
precompiled: <span class="java&#45;keyword">false</span> lastmodified: &#8230; &#45;&#45;&#62;
.
.
.
&#60;!&#45;&#45; GSP &#35;2 END template: /home/.../views/_carousel.gsp
rendering time: 115 ms &#45;&#45;&#62;</pre></div><p class="paragraph"/>Each comment block has a unique id so that you can find the start &#38; end of each template call.
<a name="6.3 Tag Libraries"><!-- Legacy link --></a>
<h2 id="taglibs">6.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 &#123;<p class="paragraph"/>&#125;</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 &#123;
def simple = &#123; attrs, body &#45;&#62;<p class="paragraph"/> &#125;
&#125;</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 &#123;
def emoticon = &#123; attrs, body &#45;&#62;
out &#60;&#60; body() &#60;&#60; (attrs.happy == '<span class="java&#45;keyword">true</span>' ? <span class="java&#45;quote">" :&#45;)"</span> : <span class="java&#45;quote">" :&#45;("</span>)
&#125;
&#125;</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&#45;tag">&#60;g:emoticon happy=<span class="xml&#45;quote">"true"</span>&#62;</span>Hi John<span class="xml&#45;tag">&#60;/g:emoticon&#62;</span></pre></div><p class="paragraph"/><blockquote class="note">
To help IDEs like SpringSource Tool Suite (STS) and others autocomplete tag attributes, you should add Javadoc comments to your tag closures with <code>&#64;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 &#123;<p class="paragraph"/> /&#42;&#42;
&#42; Renders the body with an emoticon.
&#42;
&#42; @attr happy whether to show a happy emoticon ('<span class="java&#45;keyword">true</span>') or
&#42; a sad emoticon ('<span class="java&#45;keyword">false</span>')
&#42;/
def emoticon = &#123; attrs, body &#45;&#62;
out &#60;&#60; body() &#60;&#60; (attrs.happy == '<span class="java&#45;keyword">true</span>' ? <span class="java&#45;quote">" :&#45;)"</span> : <span class="java&#45;quote">" :&#45;("</span>)
&#125;
&#125;</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 &#123;<p class="paragraph"/> /&#42;&#42;
&#42; Creates a <span class="java&#45;keyword">new</span> password field.
&#42;
&#42; @attr name REQUIRED the field name
&#42; @attr value the field value
&#42;/
def passwordField = &#123; attrs &#45;&#62;
attrs.type = <span class="java&#45;quote">"password"</span>
attrs.tagName = <span class="java&#45;quote">"passwordField"</span>
fieldImpl(out, attrs)
&#125;
&#125;</pre></div>
</blockquote>
<h2 id="taglibVariablesAndScopes">6.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="../api/org/codehaus/groovy/grails/commons/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="6.3.2 Simple Tags"><!-- Legacy link --></a>
<h2 id="simpleTags">6.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 = &#123; attrs, body &#45;&#62;
out &#60;&#60; <span class="java&#45;keyword">new</span> java.text.SimpleDateFormat(attrs.format).format(attrs.date)
&#125;</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&#45;tag">&#60;g:dateFormat format=<span class="xml&#45;quote">"dd&#45;MM&#45;yyyy"</span> date=<span class="xml&#45;quote">"$&#123;new Date()&#125;"</span> /&#62;</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 = &#123; attrs, body &#45;&#62;
out &#60;&#60; <span class="java&#45;quote">"&#60;div id=&#34;$&#123;attrs.book.id&#125;&#34;&#62;"</span>
out &#60;&#60; <span class="java&#45;quote">"Title : $&#123;attrs.book.title&#125;"</span>
out &#60;&#60; <span class="java&#45;quote">"&#60;/div&#62;"</span>
&#125;</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 = &#123; attrs, body &#45;&#62;
out &#60;&#60; render(template: <span class="java&#45;quote">"bookTemplate"</span>, model: &#91;book: attrs.book&#93;)
&#125;</pre></div><p class="paragraph"/>And then have a separate GSP template that does the actual rendering.
<a name="6.3.3 Logical Tags"><!-- Legacy link --></a>
<h2 id="logicalTags">6.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 = &#123; attrs, body &#45;&#62;
def user = attrs.user
<span class="java&#45;keyword">if</span> (user &#38;&#38; checkUserPrivs(user)) &#123;
out &#60;&#60; body()
&#125;
&#125;</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&#45;tag">&#60;g:isAdmin user=<span class="xml&#45;quote">"$&#123;myUser&#125;"</span>&#62;</span>
// some restricted content
<span class="xml&#45;tag">&#60;/g:isAdmin&#62;</span></pre></div>
<a name="6.3.4 Iterative Tags"><!-- Legacy link --></a>
<h2 id="iterativeTags">6.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 = &#123; attrs, body &#45;&#62;
attrs.times?.toInteger()?.times &#123; num &#45;&#62;
out &#60;&#60; body(num)
&#125;
&#125;</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&#45;tag">&#60;g:repeat times=<span class="xml&#45;quote">"3"</span>&#62;</span>
<span class="xml&#45;tag">&#60;p&#62;</span>Repeat this 3 times! Current repeat = $&#123;it&#125;<span class="xml&#45;tag">&#60;/p&#62;</span>
<span class="xml&#45;tag">&#60;/g:repeat&#62;</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 &#60;&#60; 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 should instead name the variables that the body uses:<p class="paragraph"/><div class="code"><pre>def repeat = &#123; attrs, body &#45;&#62;
def <span class="java&#45;keyword">var</span> = attrs.<span class="java&#45;keyword">var</span> ?: <span class="java&#45;quote">"num"</span>
attrs.times?.toInteger()?.times &#123; num &#45;&#62;
out &#60;&#60; body((<span class="java&#45;keyword">var</span>):num)
&#125;
&#125;</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 &#60;&#60; body((<span class="java&#45;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&#45;tag">&#60;g:repeat times=<span class="xml&#45;quote">"3"</span> var=<span class="xml&#45;quote">"j"</span>&#62;</span>
<span class="xml&#45;tag">&#60;p&#62;</span>Repeat this 3 times! Current repeat = $&#123;j&#125;<span class="xml&#45;tag">&#60;/p&#62;</span>
<span class="xml&#45;tag">&#60;/g:repeat&#62;</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="6.3.5 Tag Namespaces"><!-- Legacy link --></a>
<h2 id="namespaces">6.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 &#123;
<span class="java&#45;keyword">static</span> namespace = <span class="java&#45;quote">"my"</span><p class="paragraph"/> def example = &#123; attrs &#45;&#62;
&#8230;
&#125;
&#125;</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&#45;tag">&#60;my:example name=<span class="xml&#45;quote">"..."</span> /&#62;</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 &#60;&#60; my.example(name:<span class="java&#45;quote">"foo"</span>)</pre></div><p class="paragraph"/>This works from GSP, controllers or tag libraries
<a name="6.3.6 Using JSP Tag Libraries"><!-- Legacy link --></a>
<h2 id="usingJSPTagLibraries">6.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&#45;tag">&#60;%@ taglib prefix=<span class="xml&#45;quote">"fmt"</span> uri=<span class="xml&#45;quote">"http://java.sun.com/jsp/jstl/fmt"</span> %&#62;</span></pre></div><p class="paragraph"/>Then you can use it like any other tag:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;fmt:formatNumber value=<span class="xml&#45;quote">"$&#123;10&#125;"</span> pattern=<span class="xml&#45;quote">".00"</span>/&#62;</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>$&#123;fmt.formatNumber(value:10, pattern:<span class="java&#45;quote">".00"</span>)&#125;</pre></div>
<a name="6.3.7 Tag return value"><!-- Legacy link --></a>
<h2 id="tagReturnValue">6.3.7 Tag return value</h2>
Since Grails 1.2, a tag library call returns an instance of <code>org.codehaus.groovy.grails.web.util.StreamCharBuffer</code> class by default.
This change improves performance by reducing object creation and optimizing buffering during request processing.
In earlier Grails versions, a <code>java.lang.String</code> instance was returned.<p class="paragraph"/>Tag libraries can also return direct object values to the caller since Grails 1.2..
Object returning tag names are listed in a static <code>returnObjectForTags</code> property in the tag library class.<p class="paragraph"/>Example:
<div class="code"><pre>class ObjectReturningTagLib &#123;
<span class="java&#45;keyword">static</span> namespace = <span class="java&#45;quote">"cms"</span>
<span class="java&#45;keyword">static</span> returnObjectForTags = &#91;'content'&#93;<p class="paragraph"/> def content = &#123; attrs, body &#45;&#62;
CmsContent.findByCode(attrs.code)?.content
&#125;
&#125;</pre></div>
<a name="6.4 URL Mappings"><!-- Legacy link --></a>
<h2 id="urlmappings">6.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 &#123;
<span class="java&#45;keyword">static</span> mappings = &#123;
&#125;
&#125;</pre></div><p class="paragraph"/>
<a name="6.4.1 Mapping to Controllers and Actions"><!-- Legacy link --></a>
<h2 id="mappingToControllersAndActions">6.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&#45;quote">"/product"</span>(controller: <span class="java&#45;quote">"product"</span>, action: <span class="java&#45;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&#45;quote">"/product"</span>(controller: <span class="java&#45;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&#45;quote">"/product"</span> &#123;
controller = <span class="java&#45;quote">"product"</span>
action = <span class="java&#45;quote">"list"</span>
&#125;</pre></div><p class="paragraph"/>Which syntax you use is largely dependent on personal preference. 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&#45;quote">"/hello"</span>(uri: <span class="java&#45;quote">"/hello.dispatch"</span>)</pre></div><p class="paragraph"/>Rewriting specific URIs is often useful when integrating with other frameworks.
<a name="6.4.2 Embedded Variables"><!-- Legacy link --></a>
<h2 id="embeddedVariables">6.4.2 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&#45;keyword">static</span> mappings = &#123;
<span class="java&#45;quote">"/product/$id"</span>(controller: <span class="java&#45;quote">"product"</span>)
&#125;</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 &#123;
def index() &#123; render params.id &#125;
&#125;</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&#45;keyword">static</span> mappings = &#123;
<span class="java&#45;quote">"/$blog/$year/$month/$day/$id"</span>(controller: <span class="java&#45;quote">"blog"</span>, action: <span class="java&#45;quote">"show"</span>)
&#125;</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&#45;keyword">static</span> mappings = &#123;
<span class="java&#45;quote">"/$controller/$action?/$id?"</span>()
&#125;</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&#45;keyword">static</span> mappings = &#123;
<span class="java&#45;quote">"/$controller"</span> &#123;
action = &#123; params.goHere &#125;
&#125;
&#125;</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&#45;keyword">static</span> mappings = &#123;
<span class="java&#45;quote">"/$blog/$year?/$month?/$day?/$id?"</span>(controller:<span class="java&#45;quote">"blog"</span>, action:<span class="java&#45;quote">"show"</span>)
&#125;</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>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&#45;quote">"/holiday/win"</span> &#123;
id = <span class="java&#45;quote">"Marrakech"</span>
year = 2007
&#125;</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&#45;quote">"/holiday/win"</span> &#123;
id = &#123; params.id &#125;
isEligible = &#123; session.user != <span class="java&#45;keyword">null</span> &#125; // must be logged in
&#125;</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="6.4.3 Mapping to Views"><!-- Legacy link --></a>
<h2 id="mappingToViews">6.4.3 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&#45;keyword">static</span> mappings = &#123;
<span class="java&#45;quote">"/"</span>(view: <span class="java&#45;quote">"/index"</span>) // map the root URL
&#125;</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&#45;keyword">static</span> mappings = &#123;
<span class="java&#45;quote">"/help"</span>(controller: <span class="java&#45;quote">"site"</span>, view: <span class="java&#45;quote">"help"</span>) // to a view <span class="java&#45;keyword">for</span> a controller
&#125;</pre></div>
<a name="6.4.4 Mapping to Response Codes"><!-- Legacy link --></a>
<h2 id="mappingToResponseCodes">6.4.4 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&#45;keyword">static</span> mappings = &#123;
<span class="java&#45;quote">"403"</span>(controller: <span class="java&#45;quote">"errors"</span>, action: <span class="java&#45;quote">"forbidden"</span>)
<span class="java&#45;quote">"404"</span>(controller: <span class="java&#45;quote">"errors"</span>, action: <span class="java&#45;quote">"notFound"</span>)
<span class="java&#45;quote">"500"</span>(controller: <span class="java&#45;quote">"errors"</span>, action: <span class="java&#45;quote">"serverError"</span>)
&#125;</pre></div><p class="paragraph"/>Or you can specify custom error pages:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">static</span> mappings = &#123;
<span class="java&#45;quote">"403"</span>(view: <span class="java&#45;quote">"/errors/forbidden"</span>)
<span class="java&#45;quote">"404"</span>(view: <span class="java&#45;quote">"/errors/notFound"</span>)
<span class="java&#45;quote">"500"</span>(view: <span class="java&#45;quote">"/errors/serverError"</span>)
&#125;</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&#45;keyword">static</span> mappings = &#123;
<span class="java&#45;quote">"403"</span>(view: <span class="java&#45;quote">"/errors/forbidden"</span>)
<span class="java&#45;quote">"404"</span>(view: <span class="java&#45;quote">"/errors/notFound"</span>)
<span class="java&#45;quote">"500"</span>(controller: <span class="java&#45;quote">"errors"</span>, action: <span class="java&#45;quote">"illegalArgument"</span>,
exception: IllegalArgumentException)
<span class="java&#45;quote">"500"</span>(controller: <span class="java&#45;quote">"errors"</span>, action: <span class="java&#45;quote">"nullPointer"</span>,
exception: NullPointerException)
<span class="java&#45;quote">"500"</span>(controller: <span class="java&#45;quote">"errors"</span>, action: <span class="java&#45;quote">"customException"</span>,
exception: MyException)
<span class="java&#45;quote">"500"</span>(view: <span class="java&#45;quote">"/errors/serverError"</span>)
&#125;</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 &#123;
def handleError() &#123;
def exception = request.exception
// perform desired processing to handle the exception
&#125;
&#125;</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="6.4.5 Mapping to HTTP methods"><!-- Legacy link --></a>
<h2 id="mappingHTTP">6.4.5 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&#45;keyword">static</span> mappings = &#123;
<span class="java&#45;quote">"/product/$id"</span>(controller:<span class="java&#45;quote">"product"</span>) &#123;
action = &#91;GET:<span class="java&#45;quote">"show"</span>, PUT:<span class="java&#45;quote">"update"</span>, DELETE:<span class="java&#45;quote">"delete"</span>, POST:<span class="java&#45;quote">"save"</span>&#93;
&#125;
&#125;</pre></div>
<a name="6.4.6 Mapping Wildcards"><!-- Legacy link --></a>
<h2 id="mappingWildcards">6.4.6 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&#45;keyword">static</span> mappings = &#123;
<span class="java&#45;quote">"/images/&#42;.jpg"</span>(controller: <span class="java&#45;quote">"image"</span>)
&#125;</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&#45;keyword">static</span> mappings = &#123;
<span class="java&#45;quote">"/images/$name.jpg"</span>(controller: <span class="java&#45;quote">"image"</span>)
&#125;</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&#45;keyword">static</span> mappings = &#123;
<span class="java&#45;quote">"/images/&#42;&#42;.jpg"</span>(controller: <span class="java&#45;quote">"image"</span>)
&#125;</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&#45;keyword">static</span> mappings = &#123;
// will match /image/logo.jpg and /image/other/logo.jpg
<span class="java&#45;quote">"/images/$name&#42;&#42;.jpg"</span>(controller: <span class="java&#45;quote">"image"</span>)
&#125;</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&#45;quote">"logo"</span> or <span class="java&#45;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 &#123;
<span class="java&#45;keyword">static</span> excludes = &#91;<span class="java&#45;quote">"/images/&#42;"</span>, <span class="java&#45;quote">"/css/&#42;"</span>&#93;
<span class="java&#45;keyword">static</span> mappings = &#123;
&#8230;
&#125;
&#125;</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="6.4.7 Automatic Link Re-Writing"><!-- Legacy link --></a>
<h2 id="automaticLinkRewriting">6.4.7 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&#45;keyword">static</span> mappings = &#123;
<span class="java&#45;quote">"/$blog/$year?/$month?/$day?/$id?"</span>(controller:<span class="java&#45;quote">"blog"</span>, action:<span class="java&#45;quote">"show"</span>)
&#125;</pre></div><p class="paragraph"/>If you use the link tag as follows:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:link controller=<span class="xml&#45;quote">"blog"</span> action=<span class="xml&#45;quote">"show"</span>
params=<span class="xml&#45;quote">"&#91;blog:'fred', year:2007&#93;"</span>&#62;</span>
My Blog
<span class="xml&#45;tag">&#60;/g:link&#62;</span><p class="paragraph"/><span class="xml&#45;tag">&#60;g:link controller=<span class="xml&#45;quote">"blog"</span> action=<span class="xml&#45;quote">"show"</span>
params=<span class="xml&#45;quote">"&#91;blog:'fred', year:2007, month:10&#93;"</span>&#62;</span>
My Blog &#45; October 2007 Posts
<span class="xml&#45;tag">&#60;/g:link&#62;</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&#45;tag">&#60;a href=<span class="xml&#45;quote">"/fred/2007"</span>&#62;</span>My Blog<span class="xml&#45;tag">&#60;/a&#62;</span>
<span class="xml&#45;tag">&#60;a href=<span class="xml&#45;quote">"/fred/2007/10"</span>&#62;</span>My Blog &#45; October 2007 Posts<span class="xml&#45;tag">&#60;/a&#62;</span></pre></div>
<a name="6.4.8 Applying Constraints"><!-- Legacy link --></a>
<h2 id="applyingConstraints">6.4.8 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&#45;keyword">static</span> mappings = &#123;
<span class="java&#45;quote">"/$blog/$year?/$month?/$day?/$id?"</span>(controller:<span class="java&#45;quote">"blog"</span>, action:<span class="java&#45;quote">"show"</span>)
&#125;</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&#45;quote">"/$blog/$year?/$month?/$day?/$id?"</span> &#123;
controller = <span class="java&#45;quote">"blog"</span>
action = <span class="java&#45;quote">"show"</span>
constraints &#123;
year(matches:/&#92;d&#123;4&#125;/)
month(matches:/&#92;d&#123;2&#125;/)
day(matches:/&#92;d&#123;2&#125;/)
&#125;
&#125;</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="6.4.9 Named URL Mappings"><!-- Legacy link --></a>
<h2 id="namedMappings">6.4.9 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&#45;keyword">static</span> mappings = &#123;
name &#60;mapping name&#62;: &#60;url pattern&#62; &#123;
// &#8230;
&#125;
&#125;</pre></div><p class="paragraph"/>For example:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">static</span> mappings = &#123;
name personList: <span class="java&#45;quote">"/showPeople"</span> &#123;
controller = 'person'
action = 'list'
&#125;
name accountDetails: <span class="java&#45;quote">"/details/$acctNumber"</span> &#123;
controller = 'product'
action = 'accountDetails'
&#125;
&#125;</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&#45;tag">&#60;g:link mapping=<span class="xml&#45;quote">"personList"</span>&#62;</span>List People<span class="xml&#45;tag">&#60;/g:link&#62;</span></pre></div><p class="paragraph"/>That would result in:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;a href=<span class="xml&#45;quote">"/showPeople"</span>&#62;</span>List People<span class="xml&#45;tag">&#60;/a&#62;</span></pre></div><p class="paragraph"/>Parameters may be specified using the params attribute.<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:link mapping=<span class="xml&#45;quote">"accountDetails"</span> params=<span class="xml&#45;quote">"&#91;acctNumber:'8675309'&#93;"</span>&#62;</span>
Show Account
<span class="xml&#45;tag">&#60;/g:link&#62;</span></pre></div><p class="paragraph"/>That would result in:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;a href=<span class="xml&#45;quote">"/details/8675309"</span>&#62;</span>Show Account<span class="xml&#45;tag">&#60;/a&#62;</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&#45;tag">&#60;link:personList&#62;</span>List People<span class="xml&#45;tag">&#60;/link:personList&#62;</span></pre></div><p class="paragraph"/>That would result in:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;a href=<span class="xml&#45;quote">"/showPeople"</span>&#62;</span>List People<span class="xml&#45;tag">&#60;/a&#62;</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&#45;tag">&#60;link:accountDetails acctNumber=<span class="xml&#45;quote">"8675309"</span>&#62;</span>Show Account<span class="xml&#45;tag">&#60;/link:accountDetails&#62;</span></pre></div><p class="paragraph"/>That would result in:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;a href=<span class="xml&#45;quote">"/details/8675309"</span>&#62;</span>Show Account<span class="xml&#45;tag">&#60;/a&#62;</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&#45;tag">&#60;link:accountDetails attrs=<span class="xml&#45;quote">"&#91;class: 'fancy'&#93;"</span> acctNumber=<span class="xml&#45;quote">"8675309"</span>&#62;</span>
Show Account
<span class="xml&#45;tag">&#60;/link:accountDetails&#62;</span></pre></div><p class="paragraph"/>That would result in:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;a href=<span class="xml&#45;quote">"/details/8675309"</span> class=<span class="xml&#45;quote">"fancy"</span>&#62;</span>Show Account<span class="xml&#45;tag">&#60;/a&#62;</span></pre></div>
<h2 id="customizingUrlFormat">6.4.10 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&#45;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="../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&#45;keyword">package</span> com.myapplication<p class="paragraph"/>class MyUrlConverterImpl <span class="java&#45;keyword">implements</span> grails.web.UrlConverter &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> toUrlElement(<span class="java&#45;object">String</span> propertyOrClassName) &#123;
// <span class="java&#45;keyword">return</span> some representation of a property or class name that should be used in URLs&#8230;
&#125;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>// grails&#45;app/conf/spring/resources.groovy<p class="paragraph"/>beans = &#123;
<span class="java&#45;quote">"$&#123;grails.web.UrlConverter.BEAN_NAME&#125;"</span>(com.myapplication.MyUrlConverterImpl)
&#125;</pre></div>
<a name="6.5 Web Flow"><!-- Legacy link --></a>
<h2 id="webflow">6.5 Web Flow</h2>
<h4>Overview</h4><p class="paragraph"/>Grails supports the creation of web flows built on the <a href="http://www.springsource.org/webflow" target="blank">Spring Web Flow</a> project. A web flow is a conversation that spans multiple requests and retains state for the scope of the flow. A web flow also has a defined start and end state.<p class="paragraph"/>Web flows don't require an HTTP session, but instead store their state in a serialized form, which is then restored using a flow execution key that Grails passes around as a request parameter. This makes flows far more scalable than other forms of stateful application that use the HttpSession and its inherit memory and clustering concerns.<p class="paragraph"/>Web flow is essentially an advanced state machine that manages the "flow" of execution from one state to the next. Since the state is managed for you, you don't have to be concerned with ensuring that users enter an action in the middle of some multi step flow, as web flow manages that for you. This makes web flow perfect for use cases such as shopping carts, hotel booking and any application that has multi page work flows.<p class="paragraph"/><blockquote class="note">
From Grails 1.2 onwards Webflow is no longer in Grails core, so you must install the Webflow plugin to use this feature: <code>grails install-plugin webflow</code>
</blockquote><p class="paragraph"/><h4>Creating a Flow</h4><p class="paragraph"/>To create a flow create a regular Grails controller and add an action that ends with the convention <code>Flow</code>. For example:<p class="paragraph"/><div class="code"><pre>class BookController &#123;<p class="paragraph"/> def index() &#123;
redirect(action: <span class="java&#45;quote">"shoppingCart"</span>)
&#125;<p class="paragraph"/> def shoppingCartFlow = &#123;
&#8230;
&#125;
&#125;</pre></div><p class="paragraph"/>Notice when redirecting or referring to the flow as an action we omit the <code>Flow</code> suffix. In other words the name of the action of the above flow is <code>shoppingCart</code>.
<a name="6.5.1 Start and End States"><!-- Legacy link --></a>
<h2 id="startAndEndStates">6.5.1 Start and End States</h2>
As mentioned before a flow has a defined start and end state. A start state is the state which is entered when a user first initiates a conversation (or flow). The start state of a Grails flow is the first method call that takes a block. For example:<p class="paragraph"/><div class="code"><pre>class BookController &#123;
&#8230;
def shoppingCartFlow =&#123;
showCart &#123;
on(<span class="java&#45;quote">"checkout"</span>).to <span class="java&#45;quote">"enterPersonalDetails"</span>
on(<span class="java&#45;quote">"continueShopping"</span>).to <span class="java&#45;quote">"displayCatalogue"</span>
&#125;
&#8230;
displayCatalogue &#123;
redirect(controller: <span class="java&#45;quote">"catalogue"</span>, action: <span class="java&#45;quote">"show"</span>)
&#125;
displayInvoice()
&#125;
&#125;</pre></div><p class="paragraph"/>Here the <code>showCart</code> node is the start state of the flow. Since the showCart state doesn't define an action or redirect it is assumed be a <a href="../guide/single.html#actionStatesAndViewStates" class="guide">view state</a> that, by convention, refers to the view <code>grails-app/views/book/shoppingCart/showCart.gsp</code>.<p class="paragraph"/>Notice that unlike regular controller actions, the views are stored within a directory that matches the name of the flow: <code>grails-app/views/book/shoppingCart</code>.<p class="paragraph"/>The <code>shoppingCart</code> flow also has two possible end states. The first is <code>displayCatalogue</code> which performs an external redirect to another controller and action, thus exiting the flow. The second is <code>displayInvoice</code> which is an end state as it has no events at all and will simply render a view called <code>grails-app/views/book/shoppingCart/displayInvoice.gsp</code> whilst ending the flow at the same time.<p class="paragraph"/>Once a flow has ended it can only be resumed from the start state, in this case <code>showCart</code>, and not from any other state.
<a name="6.5.2 Action States and View States"><!-- Legacy link --></a>
<h2 id="actionStatesAndViewStates">6.5.2 Action States and View States</h2>
<h4>View states</h4><p class="paragraph"/>A view state is a one that doesn't define an <code>action</code> or a <code>redirect</code>. So for example this is a view state:<p class="paragraph"/><div class="code"><pre>enterPersonalDetails &#123;
on(<span class="java&#45;quote">"submit"</span>).to <span class="java&#45;quote">"enterShipping"</span>
on(<span class="java&#45;quote">"<span class="java&#45;keyword">return</span>"</span>).to <span class="java&#45;quote">"showCart"</span>
&#125;</pre></div><p class="paragraph"/>It will look for a view called <code>grails-app/views/book/shoppingCart/enterPersonalDetails.gsp</code> by default. Note that the <code>enterPersonalDetails</code> state defines two events: <code>submit</code> and <code>return</code>. The view is responsible for <a href="../guide/single.html#flowExecutionEvents" class="guide">triggering</a> these events. Use the <code>render</code> method to change the view to be rendered:<p class="paragraph"/><div class="code"><pre>enterPersonalDetails &#123;
render(view: <span class="java&#45;quote">"enterDetailsView"</span>)
on(<span class="java&#45;quote">"submit"</span>).to <span class="java&#45;quote">"enterShipping"</span>
on(<span class="java&#45;quote">"<span class="java&#45;keyword">return</span>"</span>).to <span class="java&#45;quote">"showCart"</span>
&#125;</pre></div><p class="paragraph"/>Now it will look for <code>grails-app/views/book/shoppingCart/enterDetailsView.gsp</code>. Start the <code>view</code> parameter with a / to use a shared view:<p class="paragraph"/><div class="code"><pre>enterPersonalDetails &#123;
render(view: <span class="java&#45;quote">"/shared/enterDetailsView"</span>)
on(<span class="java&#45;quote">"submit"</span>).to <span class="java&#45;quote">"enterShipping"</span>
on(<span class="java&#45;quote">"<span class="java&#45;keyword">return</span>"</span>).to <span class="java&#45;quote">"showCart"</span>
&#125;</pre></div><p class="paragraph"/>Now it will look for <code>grails-app/views/shared/enterDetailsView.gsp</code><p class="paragraph"/><h4>Action States</h4><p class="paragraph"/>An action state is a state that executes code but does not render a view. The result of the action is used to dictate flow transition. To create an action state you define an action to to be executed. This is done by calling the <code>action</code> method and passing it a block of code to be executed:<p class="paragraph"/><div class="code"><pre>listBooks &#123;
action &#123;
&#91;bookList: Book.list()&#93;
&#125;
on(<span class="java&#45;quote">"success"</span>).to <span class="java&#45;quote">"showCatalogue"</span>
on(Exception).to <span class="java&#45;quote">"handleError"</span>
&#125;</pre></div><p class="paragraph"/>As you can see an action looks very similar to a controller action and in fact you can reuse controller actions if you want. If the action successfully returns with no errors the <code>success</code> event will be triggered. In this case since we return a Map, which is regarded as the "model" and is automatically placed in <a href="../guide/single.html#flowScopes" class="guide">flow scope</a>.<p class="paragraph"/>In addition, in the above example we also use an exception handler to deal with errors on the line:<p class="paragraph"/><div class="code"><pre>on(Exception).to <span class="java&#45;quote">"handleError"</span></pre></div><p class="paragraph"/>This makes the flow transition to a state called <code>handleError</code> in the case of an exception.<p class="paragraph"/>You can write more complex actions that interact with the flow request context:<p class="paragraph"/><div class="code"><pre>processPurchaseOrder &#123;
action &#123;
def a = flow.address
def p = flow.person
def pd = flow.paymentDetails
def cartItems = flow.cartItems
flow.clear()<p class="paragraph"/> def o = <span class="java&#45;keyword">new</span> Order(person: p, shippingAddress: a, paymentDetails: pd)
o.invoiceNumber = <span class="java&#45;keyword">new</span> Random().nextInt(9999999)
<span class="java&#45;keyword">for</span> (item in cartItems) &#123; o.addToItems item &#125;
o.save()
&#91;order: o&#93;
&#125;
on(<span class="java&#45;quote">"error"</span>).to <span class="java&#45;quote">"confirmPurchase"</span>
on(Exception).to <span class="java&#45;quote">"confirmPurchase"</span>
on(<span class="java&#45;quote">"success"</span>).to <span class="java&#45;quote">"displayInvoice"</span>
&#125;</pre></div><p class="paragraph"/>Here is a more complex action that gathers all the information accumulated from the flow scope and creates an <code>Order</code> object. It then returns the order as the model. The important thing to note here is the interaction with the request context and "flow scope".<p class="paragraph"/><h4>Transition Actions</h4><p class="paragraph"/>Another form of action is what is known as a <em class="italic">transition</em> action. A transition action is executed directly prior to state transition once an <a href="../guide/single.html#flowExecutionEvents" class="guide">event</a> has been triggered. A simple example of a transition action can be seen below:<p class="paragraph"/><div class="code"><pre>enterPersonalDetails &#123;
on(<span class="java&#45;quote">"submit"</span>) &#123;
log.trace <span class="java&#45;quote">"Going to enter shipping"</span>
&#125;.to <span class="java&#45;quote">"enterShipping"</span>
on(<span class="java&#45;quote">"<span class="java&#45;keyword">return</span>"</span>).to <span class="java&#45;quote">"showCart"</span>
&#125;</pre></div><p class="paragraph"/>Notice how we pass a block of the code to <code>submit</code> event that simply logs the transition. Transition states are very useful for <a href="../guide/single.html#dataBindingAndValidation" class="guide">data binding and validation</a>, which is covered in a later section.
<a name="6.5.3 Flow Execution Events"><!-- Legacy link --></a>
<h2 id="flowExecutionEvents">6.5.3 Flow Execution Events</h2>
In order to <em class="italic">transition</em> execution of a flow from one state to the next you need some way of trigger an <em class="italic">event</em> that indicates what the flow should do next. Events can be triggered from either view states or action states.<p class="paragraph"/><h4>Triggering Events from a View State</h4><p class="paragraph"/>As discussed previously the start state of the flow in a previous code listing deals with two possible events. A <code>checkout</code> event and a <code>continueShopping</code> event:<p class="paragraph"/><div class="code"><pre>def shoppingCartFlow = &#123;
showCart &#123;
on(<span class="java&#45;quote">"checkout"</span>).to <span class="java&#45;quote">"enterPersonalDetails"</span>
on(<span class="java&#45;quote">"continueShopping"</span>).to <span class="java&#45;quote">"displayCatalogue"</span>
&#125;
&#8230;
&#125;</pre></div><p class="paragraph"/>Since the <code>showCart</code> event is a view state it will render the view <code>grails-app/book/shoppingCart/showCart.gsp</code>. Within this view you need to have components that trigger flow execution. On a form this can be done use the <a href="../ref/Tags/submitButton.html" class="tags">submitButton</a> tag:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:form&#62;</span>
<span class="xml&#45;tag">&#60;g:submitButton name=<span class="xml&#45;quote">"continueShopping"</span> value=<span class="xml&#45;quote">"Continue Shopping"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;g:submitButton name=<span class="xml&#45;quote">"checkout"</span> value=<span class="xml&#45;quote">"Checkout"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;/g:form&#62;</span></pre></div><p class="paragraph"/>The form automatically submits back to the <code>shoppingCart</code> flow. The name attribute of each <a href="../ref/Tags/submitButton.html" class="tags">submitButton</a> tag signals which event will be triggered. If you don't have a form you can also trigger an event with the <a href="../ref/Tags/link.html" class="tags">link</a> tag as follows:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:link event=<span class="xml&#45;quote">"checkout"</span> /&#62;</span></pre></div><p class="paragraph"/><blockquote class="note">
Prior to 2.0.0, it was required to specify the controller and/or action in forms and links, which caused the url to change when entering a subflow state. When the controller and action are not specified,
all url's are relative to the main flow execution url, which makes your flows reusable as subflows and prevents issues with the browser's back button.
</blockquote><p class="paragraph"/><h4>Triggering Events from an Action</h4><p class="paragraph"/>To trigger an event from an <code>action</code> you invoke a method. For example there is the built in <code>error()</code> and <code>success()</code> methods. The example below triggers the <code>error()</code> event on validation failure in a transition action:<p class="paragraph"/><div class="code"><pre>enterPersonalDetails &#123;
on(<span class="java&#45;quote">"submit"</span>) &#123;
def p = <span class="java&#45;keyword">new</span> Person(params)
flow.person = p
<span class="java&#45;keyword">if</span> (!p.validate()) <span class="java&#45;keyword">return</span> error()
&#125;.to <span class="java&#45;quote">"enterShipping"</span>
on(<span class="java&#45;quote">"<span class="java&#45;keyword">return</span>"</span>).to <span class="java&#45;quote">"showCart"</span>
&#125;</pre></div><p class="paragraph"/>In this case because of the error the transition action will make the flow go back to the <code>enterPersonalDetails</code> state.<p class="paragraph"/>With an action state you can also trigger events to redirect flow:<p class="paragraph"/><div class="code"><pre>shippingNeeded &#123;
action &#123;
<span class="java&#45;keyword">if</span> (params.shippingRequired) yes()
<span class="java&#45;keyword">else</span> no()
&#125;
on(<span class="java&#45;quote">"yes"</span>).to <span class="java&#45;quote">"enterShipping"</span>
on(<span class="java&#45;quote">"no"</span>).to <span class="java&#45;quote">"enterPayment"</span>
&#125;</pre></div><p class="paragraph"/>
<a name="6.5.4 Flow Scopes"><!-- Legacy link --></a>
<h2 id="flowScopes">6.5.4 Flow Scopes</h2>
<h4>Scope Basics</h4><p class="paragraph"/>You'll notice from previous examples that we used a special object called <code>flow</code> to store objects within "flow scope". Grails flows have five different scopes you can utilize:
<ul class="star">
<li><code>request</code> - Stores an object for the scope of the current request</li>
<li><code>flash</code> - Stores the object for the current and next request only</li>
<li><code>flow</code> - Stores objects for the scope of the flow, removing them when the flow reaches an end state</li>
<li><code>conversation</code> - Stores objects for the scope of the conversation including the root flow and nested subflows</li>
<li><code>session</code> - Stores objects in the user's session</li>
</ul><p class="paragraph"/><blockquote class="note">
Grails service classes can be automatically scoped to a web flow scope. See the documentation on <a href="../guide/single.html#services" class="guide">Services</a> for more information.
</blockquote><p class="paragraph"/>Returning a model Map from an action will automatically result in the model being placed in flow scope. For example, using a transition action, you can place objects within <code>flow</code> scope as follows:<p class="paragraph"/><div class="code"><pre>enterPersonalDetails &#123;
on(<span class="java&#45;quote">"submit"</span>) &#123;
&#91;person: <span class="java&#45;keyword">new</span> Person(params)&#93;
&#125;.to <span class="java&#45;quote">"enterShipping"</span>
on(<span class="java&#45;quote">"<span class="java&#45;keyword">return</span>"</span>).to <span class="java&#45;quote">"showCart"</span>
&#125;</pre></div><p class="paragraph"/>Be aware that a new request is always created for each state, so an object placed in request scope in an action state (for example) will not be available in a subsequent view state. Use one of the other scopes to pass objects from one state to another. Also note that Web Flow:
<ol>
<li>Moves objects from flash scope to request scope upon transition between states;</li>
<li>Merges objects from the flow and conversation scopes into the view model before rendering (so you shouldn't include a scope prefix when referencing these objects within a view, e.g. GSP pages).</li>
</ol><p class="paragraph"/><h4>Flow Scopes and Serialization</h4><p class="paragraph"/>When placing objects in <code>flash</code>, <code>flow</code> or <code>conversation</code> scope they must implement <code>java.io.Serializable</code> or an exception will be thrown. This has an impact on <a href="../guide/single.html#GORM" class="guide">domain classes</a> in that domain classes are typically placed within a scope so that they can be rendered in a view. For example consider the following domain class:<p class="paragraph"/><div class="code"><pre>class Book &#123;
<span class="java&#45;object">String</span> title
&#125;</pre></div><p class="paragraph"/>To place an instance of the <code>Book</code> class in a flow scope you will need to modify it as follows:<p class="paragraph"/><div class="code"><pre>class Book <span class="java&#45;keyword">implements</span> Serializable &#123;
<span class="java&#45;object">String</span> title
&#125;</pre></div><p class="paragraph"/>This also impacts associations and closures you declare within a domain class. For example consider this:<p class="paragraph"/><div class="code"><pre>class Book <span class="java&#45;keyword">implements</span> Serializable &#123;
<span class="java&#45;object">String</span> title
Author author
&#125;</pre></div><p class="paragraph"/>Here if the <code>Author</code> association is not <code>Serializable</code> you will also get an error. This also impacts closures used in <a href="../guide/single.html#eventsAutoTimestamping" class="guide">GORM events</a> such as <code>onLoad</code>, <code>onSave</code> and so on. The following domain class will cause an error if an instance is placed in a flow scope:<p class="paragraph"/><div class="code"><pre>class Book <span class="java&#45;keyword">implements</span> Serializable &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> title<p class="paragraph"/> def onLoad = &#123;
println <span class="java&#45;quote">"I'm loading"</span>
&#125;
&#125;</pre></div><p class="paragraph"/>The reason is that the assigned block on the <code>onLoad</code> event cannot be serialized. To get around this you should declare all events as <code>transient</code>:<p class="paragraph"/><div class="code"><pre>class Book <span class="java&#45;keyword">implements</span> Serializable &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> title<p class="paragraph"/> <span class="java&#45;keyword">transient</span> onLoad = &#123;
println <span class="java&#45;quote">"I'm loading"</span>
&#125;
&#125;</pre></div><p class="paragraph"/>or as methods:<p class="paragraph"/><div class="code"><pre>class Book <span class="java&#45;keyword">implements</span> Serializable &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> title<p class="paragraph"/> def onLoad() &#123;
println <span class="java&#45;quote">"I'm loading"</span>
&#125;
&#125;</pre></div><p class="paragraph"/><blockquote class="note">
The flow scope contains a reference to the Hibernate session. As a result, any object loaded into the session through a GORM query will also be in the flow and will need to implement Serializable.<p class="paragraph"/>If you don't want your domain class to be Serializable or stored in the flow, then you will need to evict the entity manually before the end of the state:<p class="paragraph"/><div class="code"><pre>flow.persistenceContext.evict(it)</pre></div>
</blockquote>
<a name="6.5.5 Data Binding and Validation"><!-- Legacy link --></a>
<h2 id="dataBindingAndValidation">6.5.5 Data Binding and Validation</h2>
In the section on <a href="../guide/single.html#startAndEndStates" class="guide">start and end states</a>, the start state in the first example triggered a transition to the <code>enterPersonalDetails</code> state. This state renders a view and waits for the user to enter the required information:<p class="paragraph"/><div class="code"><pre>enterPersonalDetails &#123;
on(<span class="java&#45;quote">"submit"</span>).to <span class="java&#45;quote">"enterShipping"</span>
on(<span class="java&#45;quote">"<span class="java&#45;keyword">return</span>"</span>).to <span class="java&#45;quote">"showCart"</span>
&#125;</pre></div><p class="paragraph"/>The view contains a form with two submit buttons that either trigger the submit event or the return event:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:form&#62;</span>
<span class="xml&#45;comment">&#60;!&#45;&#45; Other fields &#45;&#45;&#62;</span>
<span class="xml&#45;tag">&#60;g:submitButton name=<span class="xml&#45;quote">"submit"</span> value=<span class="xml&#45;quote">"Continue"</span>&#62;</span><span class="xml&#45;tag">&#60;/g:submitButton&#62;</span>
<span class="xml&#45;tag">&#60;g:submitButton name=<span class="xml&#45;quote">"return"</span> value=<span class="xml&#45;quote">"Back"</span>&#62;</span><span class="xml&#45;tag">&#60;/g:submitButton&#62;</span>
<span class="xml&#45;tag">&#60;/g:form&#62;</span></pre></div><p class="paragraph"/>However, what about the capturing the information submitted by the form? To capture the form info we can use a flow transition action:<p class="paragraph"/><div class="code"><pre>enterPersonalDetails &#123;
on(<span class="java&#45;quote">"submit"</span>) &#123;
flow.person = <span class="java&#45;keyword">new</span> Person(params)
!flow.person.validate() ? error() : success()
&#125;.to <span class="java&#45;quote">"enterShipping"</span>
on(<span class="java&#45;quote">"<span class="java&#45;keyword">return</span>"</span>).to <span class="java&#45;quote">"showCart"</span>
&#125;</pre></div><p class="paragraph"/>Notice how we perform data binding from request parameters and place the <code>Person</code> instance within <code>flow</code> scope. Also interesting is that we perform <a href="../guide/single.html#validation" class="guide">validation</a> and invoke the <code>error()</code> method if validation fails. This signals to the flow that the transition should halt and return to the <code>enterPersonalDetails</code> view so valid entries can be entered by the user, otherwise the transition should continue and go to the <code>enterShipping</code> state.<p class="paragraph"/>Like regular actions, flow actions also support the notion of <a href="../guide/single.html#commandObjects" class="guide">Command Objects</a> by defining the first argument of the closure:<p class="paragraph"/><div class="code"><pre>enterPersonalDetails &#123;
on(<span class="java&#45;quote">"submit"</span>) &#123; PersonDetailsCommand cmd &#45;&#62;
flow.personDetails = cmd
!flow.personDetails.validate() ? error() : success()
&#125;.to <span class="java&#45;quote">"enterShipping"</span>
on(<span class="java&#45;quote">"<span class="java&#45;keyword">return</span>"</span>).to <span class="java&#45;quote">"showCart"</span>
&#125;</pre></div>
<a name="6.5.6 Subflows and Conversations"><!-- Legacy link --></a>
<h2 id="subflowsAndConversations">6.5.6 Subflows and Conversations</h2>
<h4>Calling subflows</h4>
Grails' Web Flow integration also supports subflows. A subflow is like a flow within a flow. For example take this search flow:<p class="paragraph"/><div class="code"><pre>def searchFlow = &#123;
displaySearchForm &#123;
on(<span class="java&#45;quote">"submit"</span>).to <span class="java&#45;quote">"executeSearch"</span>
&#125;
executeSearch &#123;
action &#123;
&#91;results:searchService.executeSearch(params.q)&#93;
&#125;
on(<span class="java&#45;quote">"success"</span>).to <span class="java&#45;quote">"displayResults"</span>
on(<span class="java&#45;quote">"error"</span>).to <span class="java&#45;quote">"displaySearchForm"</span>
&#125;
displayResults &#123;
on(<span class="java&#45;quote">"searchDeeper"</span>).to <span class="java&#45;quote">"extendedSearch"</span>
on(<span class="java&#45;quote">"searchAgain"</span>).to <span class="java&#45;quote">"displaySearchForm"</span>
&#125;
extendedSearch &#123;
// Extended search subflow
subflow(controller: <span class="java&#45;quote">"searchExtensions"</span>, action: <span class="java&#45;quote">"extendedSearch"</span>)
on(<span class="java&#45;quote">"moreResults"</span>).to <span class="java&#45;quote">"displayMoreResults"</span>
on(<span class="java&#45;quote">"noResults"</span>).to <span class="java&#45;quote">"displayNoMoreResults"</span>
&#125;
displayMoreResults()
displayNoMoreResults()
&#125;</pre></div><p class="paragraph"/>It references a subflow in the <code>extendedSearch</code> state. The controller parameter is optional if the subflow is defined in the same controller as the calling flow.
<blockquote class="note">
Prior to 1.3.5, the previous subflow call would look like <code>subflow(new SearchExtensionsController().extendedSearchFlow)</code>, with the requirement that the name of the subflow state be the same as the called subflow (minus <code>Flow</code>). This way of calling a subflow is deprecated and only supported for backward compatibility.
</blockquote><p class="paragraph"/>The subflow is another flow entirely:<p class="paragraph"/><div class="code"><pre>def extendedSearchFlow = &#123;
startExtendedSearch &#123;
on(<span class="java&#45;quote">"findMore"</span>).to <span class="java&#45;quote">"searchMore"</span>
on(<span class="java&#45;quote">"searchAgain"</span>).to <span class="java&#45;quote">"noResults"</span>
&#125;
searchMore &#123;
action &#123;
def results = searchService.deepSearch(ctx.conversation.query)
<span class="java&#45;keyword">if</span> (!results) <span class="java&#45;keyword">return</span> error()
conversation.extendedResults = results
&#125;
on(<span class="java&#45;quote">"success"</span>).to <span class="java&#45;quote">"moreResults"</span>
on(<span class="java&#45;quote">"error"</span>).to <span class="java&#45;quote">"noResults"</span>
&#125;
moreResults()
noResults()
&#125;</pre></div><p class="paragraph"/>Notice how it places the <code>extendedResults</code> in conversation scope. This scope differs to flow scope as it lets you share state that spans the whole conversation, i.e. a flow execution including all subflows, not just the flow itself. Also notice that the end state (either <code>moreResults</code> or <code>noResults</code> of the subflow triggers the events in the main flow:<p class="paragraph"/><div class="code"><pre>extendedSearch &#123;
// Extended search subflow
subflow(controller: <span class="java&#45;quote">"searchExtensions"</span>, action: <span class="java&#45;quote">"extendedSearch"</span>)
on(<span class="java&#45;quote">"moreResults"</span>).to <span class="java&#45;quote">"displayMoreResults"</span>
on(<span class="java&#45;quote">"noResults"</span>).to <span class="java&#45;quote">"displayNoMoreResults"</span>
&#125;</pre></div><p class="paragraph"/><h4>Subflow input and output</h4>
Using conversation scope for passing input and output between flows can be compared with using global variables to pass information between methods.
While this is OK in certain situations, it is usually better to use method arguments and return values. In webflow speak, this means defining input and output arguments for flows.<p class="paragraph"/>Consider following flow for searching a person with a certain expertise:<p class="paragraph"/><div class="code"><pre>def searchFlow = &#123;
input &#123;
expertise(required: <span class="java&#45;keyword">true</span>)
title(<span class="java&#45;quote">"Search person"</span>)
&#125;<p class="paragraph"/> search &#123;
onEntry &#123;
&#91;personInstanceList: Person.findAllByExpertise(flow.expertise)&#93;
&#125;
on(<span class="java&#45;quote">"select"</span>) &#123;
flow.person = Person.get(params.id)
&#125;.to(<span class="java&#45;quote">"selected"</span>)
on(<span class="java&#45;quote">"cancel"</span>).to(<span class="java&#45;quote">"cancel"</span>)
&#125;<p class="paragraph"/> selected &#123;
output &#123;
person &#123;flow.person&#125;
&#125;
&#125;
cancel()
&#125;<p class="paragraph"/>&#125;</pre></div><p class="paragraph"/>This flow accepts two input parameters:
<ul class="star">
<li>a required expertise argument</li>
<li>an optional title argument with a default value</li>
</ul><p class="paragraph"/>All input arguments are stored in flow scope and are, just like local variables, only visible within this flow.<p class="paragraph"/>A flow that contains required input will throw an exception when an execution is started without providing the input. The consequence is that these flows can only be started as subflows.<p class="paragraph"/>Notice how an end state can define one or more named output values. If the value is a closure, this closure will be evaluated at the end of each flow execution.
If the value is not a closure, the value will be a constant that is only calculated once at flow definition time.<p class="paragraph"/>When a subflow is called, we can provide it a map with input values:<p class="paragraph"/><div class="code"><pre>def newProjectWizardFlow = &#123;
...<p class="paragraph"/> managerSearch &#123;
subflow(controller: <span class="java&#45;quote">"person"</span>, action: <span class="java&#45;quote">"search"</span>,
input: &#91;expertise : <span class="java&#45;quote">"management"</span>, title: <span class="java&#45;quote">"Search project manager"</span>&#93;)
on(<span class="java&#45;quote">"selected"</span>) &#123;
flow.projectInstance.manager = currentEvent.attributes.person
&#125;.to <span class="java&#45;quote">"techleadSearch"</span>
&#125;<p class="paragraph"/> techleadSearch &#123;
subflow(controller: <span class="java&#45;quote">"person"</span>, action: <span class="java&#45;quote">"search"</span>,
input: &#91;expertise : &#123; flow.technology &#125;, title: <span class="java&#45;quote">"Search technical lead"</span>&#93;)
on(<span class="java&#45;quote">"selected"</span>) &#123;
flow.projectInstance.techlead = currentEvent.attributes.person
&#125;.to <span class="java&#45;quote">"projectDetails"</span>
&#125;<p class="paragraph"/> ...<p class="paragraph"/>&#125;</pre></div><p class="paragraph"/>Notice again the difference between constant values like <code>expertise : "management"</code> and dynamic values like <code>expertise : { flow.technology }</code><p class="paragraph"/>The subflow output is available via <code>currentEvent.attributes</code>
<a name="6.6 Filters"><!-- Legacy link --></a>
<h2 id="filters">6.6 Filters</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. Filters on the other hand can be applied across a whole group of controllers, a URI space or to a specific action. Filters are far easier to plugin and maintain completely separately to your main controller logic and are useful for all sorts of cross cutting concerns such as security, logging, and so on.
<a name="6.6.1 Applying Filters"><!-- Legacy link --></a>
<h2 id="applyingFilters">6.6.1 Applying Filters</h2>
To create a filter create a class that ends with the convention <code>Filters</code> in the <code>grails-app/conf</code> directory. Within this class define a code block called <code>filters</code> that contains the filter definitions:<p class="paragraph"/><div class="code"><pre>class ExampleFilters &#123;
def filters = &#123;
// your filters here
&#125;
&#125;</pre></div><p class="paragraph"/>Each filter you define within the <code>filters</code> block has a name and a scope. The name is the method name and the scope is defined using named arguments. For example to define a filter that applies to all controllers and all actions you can use wildcards:<p class="paragraph"/><div class="code"><pre>sampleFilter(controller:'&#42;', action:'&#42;') &#123;
// interceptor definitions
&#125;</pre></div><p class="paragraph"/>The scope of the filter can be one of the following things:
<ul class="star">
<li>A controller and/or action name pairing with optional wildcards</li>
<li>A URI, with Ant path matching syntax</li>
</ul><p class="paragraph"/>Filter rule attributes:
<ul class="star">
<li><code>controller</code> - controller matching pattern, by default &#42; is replaced with .&#42; and a regex is compiled</li>
<li><code>controllerExclude</code> - controller exclusion pattern, by default &#42; is replaced with .&#42; and a regex is compiled</li>
<li><code>action</code> - action matching pattern, by default &#42; is replaced with .&#42; and a regex is compiled</li>
<li><code>actionExclude</code> - action exclusion pattern, by default &#42; is replaced with .&#42; and a regex is compiled</li>
<li><code>regex</code> (<code>true</code>/<code>false</code>) - use regex syntax (don't replace '&#42;' with '.&#42;')</li>
<li><code>uri</code> - a uri to match, expressed with as Ant style path (e.g. /book/&#42;&#42;)</li>
<li><code>uriExclude</code> - a uri pattern to exclude, expressed with as Ant style path (e.g. /book/&#42;&#42;)</li>
<li><code>find</code> (<code>true</code>/<code>false</code>) - rule matches with partial match (see <code>java.util.regex.Matcher.find()</code>)</li>
<li><code>invert</code> (<code>true</code>/<code>false</code>) - invert the rule (NOT rule)</li>
</ul><p class="paragraph"/>Some examples of filters include:
<ul class="star">
<li>All controllers and actions</li>
</ul><p class="paragraph"/><div class="code"><pre>all(controller: '&#42;', action: '&#42;') &#123;<p class="paragraph"/>&#125;</pre></div>
<ul class="star">
<li>Only for the <code>BookController</code></li>
</ul><p class="paragraph"/><div class="code"><pre>justBook(controller: 'book', action: '&#42;') &#123;<p class="paragraph"/>&#125;</pre></div>
<ul class="star">
<li>All controllers except the <code>BookController</code></li>
</ul><p class="paragraph"/><div class="code"><pre>notBook(controller: 'book', invert: <span class="java&#45;keyword">true</span>) &#123;<p class="paragraph"/>&#125;</pre></div>
<ul class="star">
<li>All actions containing 'save' in the action name</li>
</ul><p class="paragraph"/><div class="code"><pre>saveInActionName(action: '&#42;save&#42;', find: <span class="java&#45;keyword">true</span>) &#123;<p class="paragraph"/>&#125;</pre></div>
<ul class="star">
<li>All actions starting with the letter 'b' except for actions beginning with the phrase 'bad*'</li>
</ul><p class="paragraph"/><div class="code"><pre>actionBeginningWithBButNotBad(action: 'b&#42;', actionExclude: 'bad&#42;', find: <span class="java&#45;keyword">true</span>) &#123;<p class="paragraph"/>&#125;</pre></div>
<ul class="star">
<li>Applied to a URI space</li>
</ul><p class="paragraph"/><div class="code"><pre>someURIs(uri: '/book/&#42;&#42;') &#123;<p class="paragraph"/>&#125;</pre></div>
<ul class="star">
<li>Applied to all URIs</li>
</ul><p class="paragraph"/><div class="code"><pre>allURIs(uri: '/&#42;&#42;') &#123;<p class="paragraph"/>&#125;</pre></div><p class="paragraph"/>In addition, the order in which you define the filters within the <code>filters</code> code block dictates the order in which they are executed. To control the order of execution between <code>Filters</code> classes, you can use the <code>dependsOn</code> property discussed in <a href="../guide/single.html#filterDependencies" class="guide">filter dependencies</a> section.<p class="paragraph"/><blockquote class="note">
Note: When exclude patterns are used they take precedence over the matching patterns. For example, if action is 'b&#42;' and actionExclude is 'bad&#42;' then actions like 'best' and 'bien' will have that filter applied but actions like 'bad' and 'badlands' will not.
</blockquote>
<a name="6.6.2 Filter Types"><!-- Legacy link --></a>
<h2 id="filterTypes">6.6.2 Filter Types</h2>
Within the body of the filter you can then define one or several of the following interceptor types for the filter:
<ul class="star">
<li><code>before</code> - Executed before the action. Return <code>false</code> to indicate that the response has been handled that that all future filters and the action should not execute</li>
<li><code>after</code> - Executed after an action. Takes a first argument as the view model to allow modification of the model before rendering the view</li>
<li><code>afterView</code> - Executed after view rendering. Takes an Exception as an argument which will be non-<code>null</code> if an exception occurs during processing. Note: this Closure is called before the layout is applied.</li>
</ul><p class="paragraph"/>For example to fulfill the common simplistic authentication use case you could define a filter as follows:<p class="paragraph"/><div class="code"><pre>class SecurityFilters &#123;
def filters = &#123;
loginCheck(controller: '&#42;', action: '&#42;') &#123;
before = &#123;
<span class="java&#45;keyword">if</span> (!session.user &#38;&#38; !actionName.equals('login')) &#123;
redirect(action: 'login')
<span class="java&#45;keyword">return</span> <span class="java&#45;keyword">false</span>
&#125;
&#125;
&#125;
&#125;
&#125;</pre></div><p class="paragraph"/>Here the <code>loginCheck</code> filter uses a <code>before</code> interceptor to execute a block of code that checks if a user is in the session and if not redirects to the login action. Note how returning false ensure that the action itself is not executed.<p class="paragraph"/>Here's a more involved example that demonstrates all three filter types:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> java.util.concurrent.atomic.AtomicLong<p class="paragraph"/>class LoggingFilters &#123;<p class="paragraph"/> <span class="java&#45;keyword">private</span> <span class="java&#45;keyword">static</span> <span class="java&#45;keyword">final</span> AtomicLong REQUEST_NUMBER_COUNTER = <span class="java&#45;keyword">new</span> AtomicLong()
<span class="java&#45;keyword">private</span> <span class="java&#45;keyword">static</span> <span class="java&#45;keyword">final</span> <span class="java&#45;object">String</span> START_TIME_ATTRIBUTE = 'Controller__START_TIME__'
<span class="java&#45;keyword">private</span> <span class="java&#45;keyword">static</span> <span class="java&#45;keyword">final</span> <span class="java&#45;object">String</span> REQUEST_NUMBER_ATTRIBUTE = 'Controller__REQUEST_NUMBER__'<p class="paragraph"/> def filters = &#123;<p class="paragraph"/> logFilter(controller: '&#42;', action: '&#42;') &#123;<p class="paragraph"/> before = &#123;
<span class="java&#45;keyword">if</span> (!log.debugEnabled) <span class="java&#45;keyword">return</span> <span class="java&#45;keyword">true</span><p class="paragraph"/> <span class="java&#45;object">long</span> start = <span class="java&#45;object">System</span>.currentTimeMillis()
<span class="java&#45;object">long</span> currentRequestNumber = REQUEST_NUMBER_COUNTER.incrementAndGet()<p class="paragraph"/> request&#91;START_TIME_ATTRIBUTE&#93; = start
request&#91;REQUEST_NUMBER_ATTRIBUTE&#93; = currentRequestNumber<p class="paragraph"/> log.debug <span class="java&#45;quote">"preHandle request &#35;&#36;currentRequestNumber : "</span> +
<span class="java&#45;quote">"'&#36;request.servletPath'/'&#36;request.forwardURI', "</span> +
<span class="java&#45;quote">"from &#36;request.remoteHost (&#36;request.remoteAddr) "</span> +
<span class="java&#45;quote">" at &#36;&#123;<span class="java&#45;keyword">new</span> Date()&#125;, Ajax: &#36;request.xhr, controller: &#36;controllerName, "</span> +
<span class="java&#45;quote">"action: &#36;actionName, params: &#36;&#123;<span class="java&#45;keyword">new</span> TreeMap(params)&#125;"</span><p class="paragraph"/> <span class="java&#45;keyword">return</span> <span class="java&#45;keyword">true</span>
&#125;<p class="paragraph"/> after = &#123; Map model &#45;&#62;<p class="paragraph"/> <span class="java&#45;keyword">if</span> (!log.debugEnabled) <span class="java&#45;keyword">return</span> <span class="java&#45;keyword">true</span><p class="paragraph"/> <span class="java&#45;object">long</span> start = request&#91;START_TIME_ATTRIBUTE&#93;
<span class="java&#45;object">long</span> end = <span class="java&#45;object">System</span>.currentTimeMillis()
<span class="java&#45;object">long</span> requestNumber = request&#91;REQUEST_NUMBER_ATTRIBUTE&#93;<p class="paragraph"/> def msg = <span class="java&#45;quote">"postHandle request &#35;&#36;requestNumber: end &#36;&#123;<span class="java&#45;keyword">new</span> Date()&#125;, "</span> +
<span class="java&#45;quote">"controller total time &#36;&#123;end &#45; start&#125;ms"</span>
<span class="java&#45;keyword">if</span> (log.traceEnabled) &#123;
log.trace msg + <span class="java&#45;quote">"; model: &#36;model"</span>
&#125;
<span class="java&#45;keyword">else</span> &#123;
log.debug msg
&#125;
&#125;<p class="paragraph"/> afterView = &#123; Exception e &#45;&#62;<p class="paragraph"/> <span class="java&#45;keyword">if</span> (!log.debugEnabled) <span class="java&#45;keyword">return</span> <span class="java&#45;keyword">true</span><p class="paragraph"/> <span class="java&#45;object">long</span> start = request&#91;START_TIME_ATTRIBUTE&#93;
<span class="java&#45;object">long</span> end = <span class="java&#45;object">System</span>.currentTimeMillis()
<span class="java&#45;object">long</span> requestNumber = request&#91;REQUEST_NUMBER_ATTRIBUTE&#93;<p class="paragraph"/> def msg = <span class="java&#45;quote">"afterCompletion request &#35;&#36;requestNumber: "</span> +
<span class="java&#45;quote">"end &#36;&#123;<span class="java&#45;keyword">new</span> Date()&#125;, total time &#36;&#123;end &#45; start&#125;ms"</span>
<span class="java&#45;keyword">if</span> (e) &#123;
log.debug <span class="java&#45;quote">"&#36;msg &#92;n&#92;texception: &#36;e.message"</span>, e
&#125;
<span class="java&#45;keyword">else</span> &#123;
log.debug msg
&#125;
&#125;
&#125;
&#125;
&#125;</pre></div><p class="paragraph"/>In this logging example we just log various request information, but note that the <code>model</code> map in the <code>after</code> filter is mutable. If you need to add or remove items from the model map you can do that in the <code>after</code> filter.
<h2 id="filterVariablesAndScopes">6.6.3 Variables and Scopes</h2>
Filters support all the common properties available to <a href="../guide/single.html#controllers" class="guide">controllers</a> and <a href="../guide/single.html#taglibs" class="guide">tag libraries</a>, plus the application context:
<ul class="star">
<li><a href="../ref/Controllers/request.html" class="controllers">request</a> - The HttpServletRequest object</li>
<li><a href="../ref/Controllers/response.html" class="controllers">response</a> - The HttpServletResponse object</li>
<li><a href="../ref/Controllers/session.html" class="controllers">session</a> - The HttpSession object</li>
<li><a href="../ref/Controllers/servletContext.html" class="controllers">servletContext</a> - The ServletContext object</li>
<li><a href="../ref/Controllers/flash.html" class="controllers">flash</a> - The flash object</li>
<li><a href="../ref/Controllers/params.html" class="controllers">params</a> - The request parameters object</li>
<li><a href="../ref/Controllers/actionName.html" class="controllers">actionName</a> - The action name that is being dispatched to</li>
<li><a href="../ref/Controllers/controllerName.html" class="controllers">controllerName</a> - The controller name that is being dispatched to</li>
<li><a href="../ref/Controllers/grailsApplication.html" class="controllers">grailsApplication</a> - The Grails application currently running</li>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/ApplicationContext.html" class="api">applicationContext</a> - The ApplicationContext object</li>
</ul><p class="paragraph"/>However, filters only support a subset of the methods available to controllers and tag libraries. These include:
<ul class="star">
<li><a href="../ref/Controllers/redirect.html" class="controllers">redirect</a> - For redirects to other controllers and actions</li>
<li><a href="../ref/Controllers/render.html" class="controllers">render</a> - For rendering custom responses</li>
</ul><p class="paragraph"/>
<a name="6.6.4 Filter Dependencies"><!-- Legacy link --></a>
<h2 id="filterDependencies">6.6.4 Filter Dependencies</h2>
In a <code>Filters</code> class, you can specify any other <code>Filters</code> classes that should first be executed using the <code>dependsOn</code> property. This is used when a <code>Filters</code> class depends on the behavior of another <code>Filters</code> class (e.g. setting up the environment, modifying the request/session, etc.) and is defined as an array of <code>Filters</code> classes.<p class="paragraph"/>Take the following example <code>Filters</code> classes:<p class="paragraph"/><div class="code"><pre>class MyFilters &#123;
def dependsOn = &#91;MyOtherFilters&#93;<p class="paragraph"/> def filters = &#123;
checkAwesome(uri: <span class="java&#45;quote">"/&#42;"</span>) &#123;
before = &#123;
<span class="java&#45;keyword">if</span> (request.isAwesome) &#123; // <span class="java&#45;keyword">do</span> something awesome &#125;
&#125;
&#125;<p class="paragraph"/> checkAwesome2(uri: <span class="java&#45;quote">"/&#42;"</span>) &#123;
before = &#123;
<span class="java&#45;keyword">if</span> (request.isAwesome) &#123; // <span class="java&#45;keyword">do</span> something <span class="java&#45;keyword">else</span> awesome &#125;
&#125;
&#125;
&#125;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class MyOtherFilters &#123;
def filters = &#123;
makeAwesome(uri: <span class="java&#45;quote">"/&#42;"</span>) &#123;
before = &#123;
request.isAwesome = <span class="java&#45;keyword">true</span>
&#125;
&#125;
doNothing(uri: <span class="java&#45;quote">"/&#42;"</span>) &#123;
before = &#123;
// <span class="java&#45;keyword">do</span> nothing
&#125;
&#125;
&#125;
&#125;</pre></div><p class="paragraph"/>MyFilters specifically <code>dependsOn</code> MyOtherFilters. This will cause all the filters in MyOtherFilters whose scope matches the current request to be executed before those in MyFilters. For a request of "/test", which will match the scope of every filter in the example, the execution order would be as follows:
<ul class="star">
<li>MyOtherFilters - makeAwesome</li>
<li>MyOtherFilters - doNothing</li>
<li>MyFilters - checkAwesome</li>
<li>MyFilters - checkAwesome2</li>
</ul><p class="paragraph"/>The filters within the MyOtherFilters class are processed in order first, followed by the filters in the MyFilters class. Execution order between <code>Filters</code> classes are enabled and the execution order of filters within each <code>Filters</code> class are preserved.<p class="paragraph"/>If any cyclical dependencies are detected, the filters with cyclical dependencies will be added to the end of the filter chain and processing will continue. Information about any cyclical dependencies that are detected will be written to the logs. Ensure that your root logging level is set to at least WARN or configure an appender for the Grails Filters Plugin (<code>org.codehaus.groovy.grails.plugins.web.filters.FiltersGrailsPlugin</code>) when debugging filter dependency issues.
<a name="6.7 Ajax"><!-- Legacy link --></a>
<h2 id="ajax">6.7 Ajax</h2>
Ajax is the driving force behind the shift to richer web applications. These types of applications in general are better suited to agile, dynamic frameworks written in languages like <a href="http://groovy.codehaus.org" target="blank">Groovy</a> and <a href="http://www.ruby-lang.org/." target="blank">Ruby</a> Grails provides support for building Ajax applications through its Ajax tag library. For a full list of these see the Tag Library Reference.
<a name="6.7.1 Ajax Support"><!-- Legacy link --></a>
<h2 id="ajaxSupport">6.7.1 Ajax Support</h2>
By default Grails ships with the <a href="http://jquery.com/" target="blank">jQuery</a> library, but through the <a href="../guide/single.html#plugins" class="guide">Plugin system</a> provides support for other frameworks such as <a href="http://www.prototypejs.org/" target="blank">Prototype</a>, <a href="Dojo:http://dojotoolkit.org/" target="blank"></a>, <a href="Yahoo UI:http://developer.yahoo.com/yui/" target="blank"></a> and the <a href="http://code.google.com/webtoolkit/" target="blank">Google Web Toolkit</a>.<p class="paragraph"/>This section covers Grails' support for Ajax in general. To get started, add this line to the <code>&#60;head&#62;</code> tag of your page:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:javascript library=<span class="xml&#45;quote">"jquery"</span> /&#62;</span></pre></div><p class="paragraph"/>You can replace <code>jQuery</code> with any other library supplied by a plugin you have installed. This works because of Grails' support for adaptive tag libraries. Thanks to Grails' plugin system there is support for a number of different Ajax libraries including (but not limited to):
<ul class="star">
<li>jQuery</li>
<li>Prototype</li>
<li>Dojo</li>
<li>YUI</li>
<li>MooTools</li>
</ul><p class="paragraph"/>
<a name="6.7.1.1 Remoting Linking"><!-- Legacy link --></a>
<h2 id="remotingLinking">6.7.1.1 Remoting Linking</h2>
Remote content can be loaded in a number of ways, the most commons way is through the <a href="../ref/Tags/remoteLink.html" class="tags">remoteLink</a> tag. This tag allows the creation of HTML anchor tags that perform an asynchronous request and optionally set the response in an element. The simplest way to create a remote link is as follows:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:remoteLink action=<span class="xml&#45;quote">"delete"</span> id=<span class="xml&#45;quote">"1"</span>&#62;</span>Delete Book<span class="xml&#45;tag">&#60;/g:remoteLink&#62;</span></pre></div><p class="paragraph"/>The above link sends an asynchronous request to the <code>delete</code> action of the current controller with an id of <code>1</code>.
<a name="6.7.1.2 Updating Content"><!-- Legacy link --></a>
<h2 id="updatingContent">6.7.1.2 Updating Content</h2>
This is great, but usually you provide feedback to the user about what happened:<p class="paragraph"/><div class="code"><pre>def delete() &#123;
def b = Book.get(params.id)
b.delete()
render <span class="java&#45;quote">"Book $&#123;b.id&#125; was deleted"</span>
&#125;</pre></div><p class="paragraph"/>GSP code:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;div id=<span class="xml&#45;quote">"message"</span>&#62;</span><span class="xml&#45;tag">&#60;/div&#62;</span>
<span class="xml&#45;tag">&#60;g:remoteLink action=<span class="xml&#45;quote">"delete"</span> id=<span class="xml&#45;quote">"1"</span> update=<span class="xml&#45;quote">"message"</span>&#62;</span>
Delete Book
<span class="xml&#45;tag">&#60;/g:remoteLink&#62;</span></pre></div><p class="paragraph"/>The above example will call the action and set the contents of the <code>message</code> <code>div</code> to the response in this case <code>"Book 1 was deleted"</code>. This is done by the <code>update</code> attribute on the tag, which can also take a Map to indicate what should be updated on failure:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;div id=<span class="xml&#45;quote">"message"</span>&#62;</span><span class="xml&#45;tag">&#60;/div&#62;</span>
<span class="xml&#45;tag">&#60;div id=<span class="xml&#45;quote">"error"</span>&#62;</span><span class="xml&#45;tag">&#60;/div&#62;</span>
<span class="xml&#45;tag">&#60;g:remoteLink update=<span class="xml&#45;quote">"&#91;success: 'message', failure: 'error'&#93;"</span>
action=<span class="xml&#45;quote">"delete"</span> id=<span class="xml&#45;quote">"1"</span>&#62;</span>
Delete Book
<span class="xml&#45;tag">&#60;/g:remoteLink&#62;</span></pre></div><p class="paragraph"/>Here the <code>error</code> div will be updated if the request failed.
<a name="6.7.1.3 Remote Form Submission"><!-- Legacy link --></a>
<h2 id="remoteFormSubmission">6.7.1.3 Remote Form Submission</h2>
An HTML form can also be submitted asynchronously in one of two ways. Firstly using the <a href="../ref/Tags/formRemote.html" class="tags">formRemote</a> tag which expects similar attributes to those for the <a href="../ref/Tags/remoteLink.html" class="tags">remoteLink</a> tag:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:formRemote url=<span class="xml&#45;quote">"&#91;controller: 'book', action: 'delete'&#93;"</span>
update=<span class="xml&#45;quote">"&#91;success: 'message', failure: 'error'&#93;"</span>&#62;</span>
<span class="xml&#45;tag">&#60;input type=<span class="xml&#45;quote">"hidden"</span> name=<span class="xml&#45;quote">"id"</span> value=<span class="xml&#45;quote">"1"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;input type=<span class="xml&#45;quote">"submit"</span> value=<span class="xml&#45;quote">"Delete Book!"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;/g:formRemote &#62;</span></pre></div><p class="paragraph"/>Or alternatively you can use the <a href="../ref/Tags/submitToRemote.html" class="tags">submitToRemote</a> tag to create a submit button. This allows some buttons to submit remotely and some not depending on the action:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;form action=<span class="xml&#45;quote">"delete"</span>&#62;</span>
<span class="xml&#45;tag">&#60;input type=<span class="xml&#45;quote">"hidden"</span> name=<span class="xml&#45;quote">"id"</span> value=<span class="xml&#45;quote">"1"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;g:submitToRemote action=<span class="xml&#45;quote">"delete"</span>
update=<span class="xml&#45;quote">"&#91;success: 'message', failure: 'error'&#93;"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;/form&#62;</span></pre></div><p class="paragraph"/>
<a name="6.7.1.4 Ajax Events"><!-- Legacy link --></a>
<h2 id="ajaxEvents">6.7.1.4 Ajax Events</h2>
Specific JavaScript can be called if certain events occur, all the events start with the "on" prefix and let you give feedback to the user where appropriate, or take other action:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:remoteLink action=<span class="xml&#45;quote">"show"</span>
id=<span class="xml&#45;quote">"1"</span>
update=<span class="xml&#45;quote">"success"</span>
onLoading=<span class="xml&#45;quote">"showProgress()"</span>
onComplete=<span class="xml&#45;quote">"hideProgress()"</span>&#62;</span>Show Book 1<span class="xml&#45;tag">&#60;/g:remoteLink&#62;</span></pre></div><p class="paragraph"/>The above code will execute the "showProgress()" function which may show a progress bar or whatever is appropriate. Other events include:
<ul class="star">
<li><code>onSuccess</code> - The JavaScript function to call if successful</li>
<li><code>onFailure</code> - The JavaScript function to call if the call failed</li>
<li><code>on_ERROR_CODE</code> - The JavaScript function to call to handle specified error codes (eg on404="alert('not found!')")</li>
<li><code>onUninitialized</code> - The JavaScript function to call the a Ajax engine failed to initialise</li>
<li><code>onLoading</code> - The JavaScript function to call when the remote function is loading the response</li>
<li><code>onLoaded</code> - The JavaScript function to call when the remote function is completed loading the response</li>
<li><code>onComplete</code> - The JavaScript function to call when the remote function is complete, including any updates</li>
</ul><p class="paragraph"/>If you need a reference to the <code>XmlHttpRequest</code> object you can use the implicit event parameter <code>e</code> to obtain it:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:javascript&#62;</span>
function fireMe(e) &#123;
alert(<span class="xml&#45;quote">"XmlHttpRequest = "</span> + e)
&#125;
&#125;
<span class="xml&#45;tag">&#60;/g:javascript&#62;</span>
<span class="xml&#45;tag">&#60;g:remoteLink action=<span class="xml&#45;quote">"example"</span>
update=<span class="xml&#45;quote">"success"</span>
onSuccess=<span class="xml&#45;quote">"fireMe(e)"</span>&#62;</span>Ajax Link<span class="xml&#45;tag">&#60;/g:remoteLink&#62;</span></pre></div>
<a name="6.7.2 Ajax with Prototype"><!-- Legacy link --></a>
<h2 id="ajaxWithPrototype">6.7.2 Ajax with Prototype</h2>
Grails features an external plugin to add <a href="http://www.prototypejs.org/" target="blank">Prototype</a> support to Grails. To install the plugin type the following command from the root of your project in a terminal window:<p class="paragraph"/><div class="code"><pre>grails install&#45;plugin prototype</pre></div><p class="paragraph"/>This will download the current supported version of the Prototype plugin and install it into your Grails project. With that done you can add the following reference to the top of your page:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:javascript library=<span class="xml&#45;quote">"prototype"</span> /&#62;</span></pre></div><p class="paragraph"/>If you require <a href="http://script.aculo.us/" target="blank">Scriptaculous</a> too you can do the following instead:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:javascript library=<span class="xml&#45;quote">"scriptaculous"</span> /&#62;</span></pre></div><p class="paragraph"/>Now all of Grails tags such as <a href="../ref/Tags/remoteLink.html" class="tags">remoteLink</a>, <a href="../ref/Tags/formRemote.html" class="tags">formRemote</a> and <a href="../ref/Tags/submitToRemote.html" class="tags">submitToRemote</a> work with Prototype remoting.
<a name="6.7.3 Ajax with Dojo"><!-- Legacy link --></a>
<h2 id="ajaxWithDojo">6.7.3 Ajax with Dojo</h2>
Grails features an external plugin to add <a href="http://dojotoolkit.org/" target="blank">Dojo</a> support to Grails. To install the plugin type the following command from the root of your project in a terminal window:<p class="paragraph"/><div class="code"><pre>grails install&#45;plugin dojo</pre></div><p class="paragraph"/>This will download the current supported version of Dojo and install it into your Grails project. With that done you can add the following reference to the top of your page:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:javascript library=<span class="xml&#45;quote">"dojo"</span> /&#62;</span></pre></div><p class="paragraph"/>Now all of Grails tags such as <a href="../ref/Tags/remoteLink.html" class="tags">remoteLink</a>, <a href="../ref/Tags/formRemote.html" class="tags">formRemote</a> and <a href="../ref/Tags/submitToRemote.html" class="tags">submitToRemote</a> work with Dojo remoting.
<a name="6.7.4 Ajax with GWT"><!-- Legacy link --></a>
<h2 id="ajaxWithGWT">6.7.4 Ajax with GWT</h2>
Grails also features support for the <a href="http://code.google.com/webtoolkit/" target="blank">Google Web Toolkit</a> through a plugin. There is comprehensive <a href="http://grails.org/plugin/gwt" target="blank">documentation</a> available on the Grails wiki.
<a name="6.7.5 Ajax on the Server"><!-- Legacy link --></a>
<h2 id="ajaxOnTheServer">6.7.5 Ajax on the Server</h2>
There are a number of different ways to implement Ajax which are typically broken down into:
<ul class="star">
<li>Content Centric Ajax - Where you just use the HTML result of a remote call to update the page</li>
<li>Data Centric Ajax - Where you actually send an XML or JSON response from the server and programmatically update the page</li>
<li>Script Centric Ajax - Where the server sends down a stream of JavaScript to be evaluated on the fly</li>
</ul><p class="paragraph"/>Most of the examples in the <a href="../guide/single.html#ajax" class="guide">Ajax</a> section cover Content Centric Ajax where you are updating the page, but you may also want to use Data Centric or Script Centric. This guide covers the different styles of Ajax.<p class="paragraph"/><h4>Content Centric Ajax</h4><p class="paragraph"/>Just to re-cap, content centric Ajax involves sending some HTML back from the server and is typically done by rendering a template with the <a href="../ref/Controllers/render.html" class="controllers">render</a> method:<p class="paragraph"/><div class="code"><pre>def showBook() &#123;
def b = Book.get(params.id)<p class="paragraph"/> render(template: <span class="java&#45;quote">"bookTemplate"</span>, model: &#91;book: b&#93;)
&#125;</pre></div><p class="paragraph"/>Calling this on the client involves using the <a href="../ref/Tags/remoteLink.html" class="tags">remoteLink</a> tag:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:remoteLink action=<span class="xml&#45;quote">"showBook"</span> id=<span class="xml&#45;quote">"$&#123;book.id&#125;"</span>
update=<span class="xml&#45;quote">"book$&#123;book.id&#125;"</span>&#62;</span>Update Book<span class="xml&#45;tag">&#60;/g:remoteLink&#62;</span><p class="paragraph"/><span class="xml&#45;tag">&#60;div id=<span class="xml&#45;quote">"book$&#123;book.id&#125;"</span>&#62;</span>
<span class="xml&#45;comment">&#60;!&#45;&#45;existing book mark&#45;up &#45;&#45;&#62;</span>
<span class="xml&#45;tag">&#60;/div&#62;</span></pre></div><p class="paragraph"/><h4>Data Centric Ajax with JSON</h4><p class="paragraph"/>Data Centric Ajax typically involves evaluating the response on the client and updating programmatically. For a JSON response with Grails you would typically use Grails' <a href="../guide/single.html#xmlAndJSON" class="guide">JSON marshalling</a> capability:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> grails.converters.JSON<p class="paragraph"/>def showBook() &#123;
def b = Book.get(params.id)<p class="paragraph"/> render b as JSON
&#125;</pre></div><p class="paragraph"/>And then on the client parse the incoming JSON request using an Ajax event handler:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:javascript&#62;</span>
function updateBook(e) &#123;
var book = eval(<span class="xml&#45;quote">"("</span>+e.responseText+<span class="xml&#45;quote">")"</span>) // evaluate the JSON
$(<span class="xml&#45;quote">"book"</span> + book.id + <span class="xml&#45;quote">"_title"</span>).innerHTML = book.title
&#125;
<span class="xml&#45;tag">&#60;g:javascript&#62;</span>
<span class="xml&#45;tag">&#60;g:remoteLink action=<span class="xml&#45;quote">"test"</span> update=<span class="xml&#45;quote">"foo"</span> onSuccess=<span class="xml&#45;quote">"updateBook(e)"</span>&#62;</span>
Update Book
<span class="xml&#45;tag">&#60;/g:remoteLink&#62;</span>
<span class="xml&#45;tag">&#60;g:set var=<span class="xml&#45;quote">"bookId"</span>&#62;</span>book$&#123;book.id&#125;<span class="xml&#45;tag">&#60;/g:set&#62;</span>
<span class="xml&#45;tag">&#60;div id=<span class="xml&#45;quote">"$&#123;bookId&#125;"</span>&#62;</span>
<span class="xml&#45;tag">&#60;div id=<span class="xml&#45;quote">"$&#123;bookId&#125;_title"</span>&#62;</span>The Stand<span class="xml&#45;tag">&#60;/div&#62;</span>
<span class="xml&#45;tag">&#60;/div&#62;</span></pre></div><p class="paragraph"/><h4>Data Centric Ajax with XML</h4><p class="paragraph"/>On the server side using XML is equally simple:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> grails.converters.XML<p class="paragraph"/>def showBook() &#123;
def b = Book.get(params.id)<p class="paragraph"/> render b as XML
&#125;</pre></div><p class="paragraph"/>However, since DOM is involved the client gets more complicated:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:javascript&#62;</span>
function updateBook(e) &#123;
var xml = e.responseXML
var id = xml.getElementsByTagName(<span class="xml&#45;quote">"book"</span>).getAttribute(<span class="xml&#45;quote">"id"</span>)
$(<span class="xml&#45;quote">"book"</span> + id + <span class="xml&#45;quote">"_title"</span>) = xml.getElementsByTagName(<span class="xml&#45;quote">"title"</span>)&#91;0&#93;.textContent
&#125;
<span class="xml&#45;tag">&#60;g:javascript&#62;</span>
<span class="xml&#45;tag">&#60;g:remoteLink action=<span class="xml&#45;quote">"test"</span> update=<span class="xml&#45;quote">"foo"</span> onSuccess=<span class="xml&#45;quote">"updateBook(e)"</span>&#62;</span>
Update Book
<span class="xml&#45;tag">&#60;/g:remoteLink&#62;</span>
<span class="xml&#45;tag">&#60;g:set var=<span class="xml&#45;quote">"bookId"</span>&#62;</span>book$&#123;book.id&#125;<span class="xml&#45;tag">&#60;/g:set&#62;</span>
<span class="xml&#45;tag">&#60;div id=<span class="xml&#45;quote">"$&#123;bookId&#125;"</span>&#62;</span>
<span class="xml&#45;tag">&#60;div id=<span class="xml&#45;quote">"$&#123;bookId&#125;_title"</span>&#62;</span>The Stand<span class="xml&#45;tag">&#60;/div&#62;</span>
<span class="xml&#45;tag">&#60;/div&#62;</span></pre></div><p class="paragraph"/><h4>Script Centric Ajax with JavaScript</h4><p class="paragraph"/>Script centric Ajax involves actually sending JavaScript back that gets evaluated on the client. An example of this can be seen below:<p class="paragraph"/><div class="code"><pre>def showBook() &#123;
def b = Book.get(params.id)<p class="paragraph"/> response.contentType = <span class="java&#45;quote">"text/javascript"</span>
<span class="java&#45;object">String</span> title = b.title.encodeAsJavascript()
render <span class="java&#45;quote">"&#36;('book$&#123;b.id&#125;_title')='$&#123;title&#125;'"</span>
&#125;</pre></div><p class="paragraph"/>The important thing to remember is to set the <code>contentType</code> to <code>text/javascript</code>. If you use Prototype on the client the returned JavaScript will automatically be evaluated due to this <code>contentType</code> setting.<p class="paragraph"/>Obviously in this case it is critical that you have an agreed client-side API as you don't want changes on the client breaking the server. This is one of the reasons Rails has something like RJS. Although Grails does not currently have a feature such as RJS there is a <a href="http://grails.org/plugin/dynamic-javascript" target="blank">Dynamic JavaScript Plugin</a> that offers similar capabilities.<p class="paragraph"/><h4>Responding to both Ajax and non-Ajax requests</h4><p class="paragraph"/>It's straightforward to have the same Grails controller action handle both Ajax and non-Ajax requests. Grails adds the <code>isXhr()</code> method to <code>HttpServletRequest</code> which can be used to identify Ajax requests. For example you could render a page fragment using a template for Ajax requests or the full page for regular HTTP requests:<p class="paragraph"/><div class="code"><pre>def listBooks() &#123;
def books = Book.list(params)
<span class="java&#45;keyword">if</span> (request.xhr) &#123;
render template: <span class="java&#45;quote">"bookTable"</span>, model: &#91;books: books&#93;
&#125; <span class="java&#45;keyword">else</span> &#123;
render view: <span class="java&#45;quote">"list"</span>, model: &#91;books: books&#93;
&#125;
&#125;</pre></div>
<a name="6.8 Content Negotiation"><!-- Legacy link --></a>
<h2 id="contentNegotiation">6.8 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 = &#91; xml: &#91;'text/xml', 'application/xml'&#93;,
text: 'text&#45;plain',
js: 'text/javascript',
rss: 'application/rss+xml',
atom: 'application/atom+xml',
css: 'text/css',
csv: 'text/csv',
all: '&#42;/&#42;',
json: 'text/json',
html: &#91;'text/html','application/xhtml+xml'&#93;
&#93;</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.<p class="paragraph"/><h4>Content Negotiation 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>&#42;/&#42;</pre></div><p class="paragraph"/>Which simply means anything. However, on newer browser something all together more useful is sent such as (an example of a Firefox <code>Accept</code> header):<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, &#42;/&#42;;q=0.5</pre></div><p class="paragraph"/>Grails parses this incoming format and adds a <code>property</code> to the <a href="../ref/Servlet API/response.html" class="servletAPI">response</a> object that outlines the preferred response format. For the above example the following assertion would pass:<p class="paragraph"/><div class="code"><pre>assert 'html' == response.format</pre></div><p class="paragraph"/>Why? The <code>text/html</code> media type has the highest "quality" rating of 0.9, therefore is the highest priority. If you have an older browser as mentioned previously the result is slightly different:<p class="paragraph"/><div class="code"><pre>assert 'all' == response.format</pre></div><p class="paragraph"/>In this case 'all' possible formats are accepted by the client. To deal with different kinds of requests from <a href="../guide/single.html#controllers" class="guide">Controllers</a> you can use the <a href="../ref/Controllers/withFormat.html" class="controllers">withFormat</a> method that acts as kind of a switch statement:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> grails.converters.XML<p class="paragraph"/>class BookController &#123;<p class="paragraph"/> def list() &#123;
def books = Book.list()
withFormat &#123;
html bookList: books
js &#123; render <span class="java&#45;quote">"alert('hello')"</span> &#125;
xml &#123; render books as XML &#125;
&#125;
&#125;
&#125;</pre></div><p class="paragraph"/>If the preferred format is <code>html</code> then Grails will execute the <code>html()</code> call only. This causes Grails to look for a view called either <code>grails-app/views/books/list.html.gsp</code> or <code>grails-app/views/books/list.gsp</code>. If the format is <code>xml</code> then the closure will be invoked and an XML response rendered.<p class="paragraph"/>How do we handle the "all" format? Simply order the content-types within your <code>withFormat</code> block so that whichever one you want executed comes first. So in the above example, "all" will trigger the <code>html</code> handler.<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>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 &#123;
xml &#123;
// read XML
&#125;
json &#123;
// read JSON
&#125;
&#125;</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&#45;quote">"/book/list"</span>(controller:<span class="java&#45;quote">"book"</span>, action:<span class="java&#45;quote">"list"</span>) &#123;
format = <span class="java&#45;quote">"xml"</span>
&#125;</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"/>Grails will remove the extension and map it to <code>/book/list</code> instead whilst simultaneously setting the content format to <code>xml</code> based on this extension. This behaviour is enabled by default, so if you wish to turn it off, you must set the <code>grails.mime.file.extensions</code> property in <code>grails-app/conf/Config.groovy</code> to <code>false</code>:<p class="paragraph"/><div class="code"><pre>grails.mime.file.extensions = <span class="java&#45;keyword">false</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() &#123;
def controller = <span class="java&#45;keyword">new</span> TestController()
controller.request.addHeader <span class="java&#45;quote">"Accept"</span>,
<span class="java&#45;quote">"text/javascript, text/html, application/xml, text/xml, &#42;/&#42;"</span><p class="paragraph"/> controller.testAction()
assertEquals <span class="java&#45;quote">"alert('hello')"</span>, controller.response.contentAsString
&#125;</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() &#123;
def controller = <span class="java&#45;keyword">new</span> TestController()
controller.params.format = 'js'<p class="paragraph"/> controller.testAction()
assertEquals <span class="java&#45;quote">"alert('hello')"</span>, controller.response.contentAsString
&#125;</pre></div>
<a name="7. Validation"><!-- Legacy link --></a>
<h1 id="validation">7 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&#39;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="7.1 Declaring Constraints"><!-- Legacy link --></a>
<h2 id="constraints">7.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 &#123;
<span class="java&#45;object">String</span> login
<span class="java&#45;object">String</span> password
<span class="java&#45;object">String</span> email
<span class="java&#45;object">Integer</span> age<p class="paragraph"/> <span class="java&#45;keyword">static</span> constraints = &#123;
&#8230;
&#125;
&#125;</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 &#123;
...<p class="paragraph"/> <span class="java&#45;keyword">static</span> constraints = &#123;
login size: 5..15, blank: <span class="java&#45;keyword">false</span>, unique: <span class="java&#45;keyword">true</span>
password size: 5..15, blank: <span class="java&#45;keyword">false</span>
email email: <span class="java&#45;keyword">true</span>, blank: <span class="java&#45;keyword">false</span>
age min: 18
&#125;
&#125;</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 &#123;
...<p class="paragraph"/> <span class="java&#45;keyword">static</span> constraints = &#123;
// <span class="java&#45;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&#45;keyword">new</span> Date()
&#125;
&#125;</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 &#123;
Survey survey
Answer answer<p class="paragraph"/> <span class="java&#45;keyword">static</span> constraints = &#123;
survey blank: <span class="java&#45;keyword">false</span>
answer blank: <span class="java&#45;keyword">false</span>, inList: survey.answers
&#125;
&#125;</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 &#123;
&#8230;
<span class="java&#45;keyword">static</span> constraints = &#123;
survey blank: <span class="java&#45;keyword">false</span>
answer blank: <span class="java&#45;keyword">false</span>, validator: &#123; val, obj &#45;&#62; val in obj.survey.answers &#125;
&#125;
&#125;</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="7.2 Validating Constraints"><!-- Legacy link --></a>
<h2 id="validatingConstraints">7.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&#45;keyword">new</span> User(params)<p class="paragraph"/><span class="java&#45;keyword">if</span> (user.validate()) &#123;
// <span class="java&#45;keyword">do</span> something with user
&#125;
<span class="java&#45;keyword">else</span> &#123;
user.errors.allErrors.each &#123;
println it
&#125;
&#125;</pre></div><p class="paragraph"/>The <code>errors</code> property on domain classes is an instance of the Spring <a href="http://static.springsource.org/spring/docs/3.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&#45;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&#45;keyword">if</span> (user.hasErrors()) &#123;
<span class="java&#45;keyword">if</span> (user.errors.hasFieldErrors(<span class="java&#45;quote">"login"</span>)) &#123;
println user.errors.getFieldError(<span class="java&#45;quote">"login"</span>).rejectedValue
&#125;
&#125;</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 againts 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&#45;keyword">if</span> (user.save()) &#123;
<span class="java&#45;keyword">return</span> user
&#125;
<span class="java&#45;keyword">else</span> &#123;
user.errors.allErrors.each &#123;
println it
&#125;
&#125;</pre></div>
<a name="7.3 Validation on the Client"><!-- Legacy link --></a>
<h2 id="validationOnTheClient">7.3 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&#45;tag">&#60;g:renderErrors bean=<span class="xml&#45;quote">"$&#123;user&#125;"</span> /&#62;</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&#45;tag">&#60;g:hasErrors bean=<span class="xml&#45;quote">"$&#123;user&#125;"</span>&#62;</span>
<span class="xml&#45;tag">&#60;ul&#62;</span>
<span class="xml&#45;tag">&#60;g:eachError var=<span class="xml&#45;quote">"err"</span> bean=<span class="xml&#45;quote">"$&#123;user&#125;"</span>&#62;</span>
<span class="xml&#45;tag">&#60;li&#62;</span>$&#123;err&#125;<span class="xml&#45;tag">&#60;/li&#62;</span>
<span class="xml&#45;tag">&#60;/g:eachError&#62;</span>
<span class="xml&#45;tag">&#60;/ul&#62;</span>
<span class="xml&#45;tag">&#60;/g:hasErrors&#62;</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&#45;tag">&#60;div class='value $&#123;hasErrors(bean:user,field:'login','errors')&#125;'&#62;</span>
<span class="xml&#45;tag">&#60;input type=<span class="xml&#45;quote">"text"</span> name=<span class="xml&#45;quote">"login"</span> value=<span class="xml&#45;quote">"$&#123;fieldValue(bean:user,field:'login')&#125;"</span>/&#62;</span>
<span class="xml&#45;tag">&#60;/div&#62;</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://static.springsource.org/spring/docs/3.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&#45;tag">&#60;input type=<span class="xml&#45;quote">"text"</span> name=<span class="xml&#45;quote">"login"</span> value=<span class="xml&#45;quote">"$&#123;fieldValue(bean:user,field:'login')&#125;"</span>/&#62;</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="7.4 Validation and Internationalization"><!-- Legacy link --></a>
<h2 id="validationAndInternationalization">7.4 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://static.springsource.org/spring/docs/3.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&#45;keyword">package</span> com.mycompany.myapp<p class="paragraph"/>class User &#123;
...<p class="paragraph"/> <span class="java&#45;keyword">static</span> constraints = &#123;
login size: 5..15, blank: <span class="java&#45;keyword">false</span>, unique: <span class="java&#45;keyword">true</span>
password size: 5..15, blank: <span class="java&#45;keyword">false</span>
email email: <span class="java&#45;keyword">true</span>, blank: <span class="java&#45;keyword">false</span>
age min: 18
&#125;
&#125;</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>&#91;<span class="java&#45;object">Class</span> Name&#93;.&#91;Property Name&#93;.&#91;Constraint Code&#93;</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&#45;tag">&#60;g:hasErrors bean=<span class="xml&#45;quote">"$&#123;user&#125;"</span>&#62;</span>
<span class="xml&#45;tag">&#60;ul&#62;</span>
<span class="xml&#45;tag">&#60;g:eachError var=<span class="xml&#45;quote">"err"</span> bean=<span class="xml&#45;quote">"$&#123;user&#125;"</span>&#62;</span>
<span class="xml&#45;tag">&#60;li&#62;</span><span class="xml&#45;tag">&#60;g:message error=<span class="xml&#45;quote">"$&#123;err&#125;"</span> /&#62;</span><span class="xml&#45;tag">&#60;/li&#62;</span>
<span class="xml&#45;tag">&#60;/g:eachError&#62;</span>
<span class="xml&#45;tag">&#60;/ul&#62;</span>
<span class="xml&#45;tag">&#60;/g:hasErrors&#62;</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="7.5 Validation Non Domain and Command Object Classes"><!-- Legacy link --></a>
<h2 id="validationNonDomainAndCommandObjectClasses">7.5 Validation Non Domain and Command Object 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 Annotation</h4><p class="paragraph"/>Classes which define the static <code>constraints</code> property and are annotated with @Validateable can be made validateable by the framework. Consider this example:<p class="paragraph"/><div class="code"><pre>// src/groovy/com/mycompany/myapp/User.groovy
<span class="java&#45;keyword">package</span> com.mycompany.myapp<p class="paragraph"/><span class="java&#45;keyword">import</span> grails.validation.Validateable<p class="paragraph"/>@Validateable
class User &#123;
...<p class="paragraph"/> <span class="java&#45;keyword">static</span> constraints = &#123;
login size: 5..15, blank: <span class="java&#45;keyword">false</span>, unique: <span class="java&#45;keyword">true</span>
password size: 5..15, blank: <span class="java&#45;keyword">false</span>
email email: <span class="java&#45;keyword">true</span>, blank: <span class="java&#45;keyword">false</span>
age min: 18
&#125;
&#125;</pre></div><p class="paragraph"/><h4>Registering Validateable Classes</h4><p class="paragraph"/>If a class is not marked with <code>Validateable, it may still be made validateable by the framework. The steps required to do this are to define the static </code>constraints<code> property in the class (as described above) and then telling the framework about the class by assigning a value to the </code>grails.validateable.classes<code> property in </code>Config.groovy@:<p class="paragraph"/><div class="code"><pre>grails.validateable.classes = &#91;com.mycompany.myapp.User, com.mycompany.dto.Account&#93;</pre></div>
<a name="8. The Service Layer"><!-- Legacy link --></a>
<h1 id="services">8 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&#45;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&#45;keyword">package</span> helloworld<p class="paragraph"/>class SimpleService &#123;
&#125;</pre></div>
<a name="8.1 Declarative Transactions"><!-- Legacy link --></a>
<h2 id="declarativeTransactions">8.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 &#123;
<span class="java&#45;keyword">static</span> transactional = <span class="java&#45;keyword">false</span>
&#125;</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 fully supports Spring's <code>Transactional</code> annotation for cases where you need more fine-grained control over transactions at a per-method level or need specify an alternative propagation level.<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&#45;keyword">import</span> org.springframework.transaction.annotation.Transactional<p class="paragraph"/>class BookService &#123;<p class="paragraph"/> @Transactional(readOnly = <span class="java&#45;keyword">true</span>)
def listBooks() &#123;
Book.list()
&#125;<p class="paragraph"/> @Transactional
def updateBook() &#123;
// …
&#125;<p class="paragraph"/> def deleteBook() &#123;
// …
&#125;
&#125;</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&#45;keyword">import</span> org.springframework.transaction.annotation.Transactional<p class="paragraph"/>@Transactional
class BookService &#123;<p class="paragraph"/> def listBooks() &#123;
Book.list()
&#125;<p class="paragraph"/> def updateBook() &#123;
// …
&#125;<p class="paragraph"/> def deleteBook() &#123;
// …
&#125;
&#125;</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&#45;keyword">import</span> org.springframework.transaction.annotation.Transactional<p class="paragraph"/>@Transactional
class BookService &#123;<p class="paragraph"/> @Transactional(readOnly = <span class="java&#45;keyword">true</span>)
def listBooks() &#123;
Book.list()
&#125;<p class="paragraph"/> def updateBook() &#123;
// …
&#125;<p class="paragraph"/> def deleteBook() &#123;
// …
&#125;
&#125;</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="8.1.1 Transactions Rollback and the Session"><!-- Legacy link --></a>
<h2 id="transactionsRollbackAndTheSession">8.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 &#123;
<span class="java&#45;object">String</span> name
<span class="java&#45;object">Integer</span> age<p class="paragraph"/> <span class="java&#45;keyword">static</span> hasMany = &#91;books: Book&#93;
&#125;</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 &#123; status &#45;&#62;
<span class="java&#45;keyword">new</span> Author(name: <span class="java&#45;quote">"Stephen King"</span>, age: 40).save()
status.setRollbackOnly()
&#125;<p class="paragraph"/>Author.withTransaction &#123; status &#45;&#62;
<span class="java&#45;keyword">new</span> Author(name: <span class="java&#45;quote">"Stephen King"</span>, age: 40).save()
&#125;</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 &#123;<p class="paragraph"/> void updateAge(id, <span class="java&#45;object">int</span> age) &#123;
def author = Author.get(id)
author.age = age
<span class="java&#45;keyword">if</span> (author.isTooOld()) &#123;
<span class="java&#45;keyword">throw</span> <span class="java&#45;keyword">new</span> AuthorException(<span class="java&#45;quote">"too old"</span>, author)
&#125;
&#125;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class AuthorController &#123;<p class="paragraph"/> def authorService<p class="paragraph"/> def updateAge() &#123;
<span class="java&#45;keyword">try</span> &#123;
authorService.updateAge(params.id, params.<span class="java&#45;object">int</span>(<span class="java&#45;quote">"age"</span>))
&#125;
<span class="java&#45;keyword">catch</span>(e) &#123;
render <span class="java&#45;quote">"Author books $&#123;e.author.books&#125;"</span>
&#125;
&#125;
&#125;</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 &#123;
&#8230;
void updateAge(id, <span class="java&#45;object">int</span> age) &#123;
def author = Author.findById(id, &#91;fetch:&#91;books:<span class="java&#45;quote">"eager"</span>&#93;&#93;)
...</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 &#123;<p class="paragraph"/> AuthorService authorService<p class="paragraph"/> def updateAge() &#123;
<span class="java&#45;keyword">try</span> &#123;
authorService.updateAge(params.id, params.<span class="java&#45;object">int</span>(<span class="java&#45;quote">"age"</span>))
&#125;
<span class="java&#45;keyword">catch</span>(e) &#123;
flash.message <span class="java&#45;quote">"Can't update age"</span>
redirect action:<span class="java&#45;quote">"show"</span>, id:params.id
&#125;
&#125;
&#125;</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 &#123;<p class="paragraph"/> def authorService<p class="paragraph"/> def updateAge() &#123;
<span class="java&#45;keyword">try</span> &#123;
authorService.updateAge(params.id, params.<span class="java&#45;object">int</span>(<span class="java&#45;quote">"age"</span>))
&#125;
<span class="java&#45;keyword">catch</span>(e) &#123;
def author = Author.read(params.id)
render <span class="java&#45;quote">"Author books $&#123;author.books&#125;"</span>
&#125;
&#125;
&#125;</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&#45;keyword">import</span> grails.validation.ValidationException<p class="paragraph"/>class AuthorService &#123;<p class="paragraph"/> void updateAge(id, <span class="java&#45;object">int</span> age) &#123;
def author = Author.get(id)
author.age = age
<span class="java&#45;keyword">if</span> (!author.validate()) &#123;
<span class="java&#45;keyword">throw</span> <span class="java&#45;keyword">new</span> ValidationException(<span class="java&#45;quote">"Author is not valid"</span>, author.errors)
&#125;
&#125;
&#125;</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&#45;keyword">import</span> grails.validation.ValidationException<p class="paragraph"/>class AuthorController &#123;<p class="paragraph"/> def authorService<p class="paragraph"/> def updateAge() &#123;
<span class="java&#45;keyword">try</span> &#123;
authorService.updateAge(params.id, params.<span class="java&#45;object">int</span>(<span class="java&#45;quote">"age"</span>))
&#125;
<span class="java&#45;keyword">catch</span> (ValidationException e) &#123;
def author = Author.read(params.id)
author.errors = e.errors
render view: <span class="java&#45;quote">"edit"</span>, model: &#91;author:author&#93;
&#125;
&#125;
&#125;</pre></div>
<a name="8.2 Scoped Services"><!-- Legacy link --></a>
<h2 id="scopedServices">8.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 <a href="../guide/single.html#webflow" class="guide">Web Flow</a>
</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&#45;keyword">static</span> scope = <span class="java&#45;quote">"flow"</span></pre></div>
<a name="8.3 Dependency Injection and Services"><!-- Legacy link --></a>
<h2 id="dependencyInjectionServices">8.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 &#123;
def bookService
&#8230;
&#125;</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 &#123;
BookService bookService
&#125;</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 &#123;
def bookService
&#125;</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 &#123;
&#8230;
def bookService<p class="paragraph"/> def buyBook() &#123;
bookService.buyBook(<span class="java&#45;keyword">this</span>)
&#125;
&#125;</pre></div>
<a name="8.4 Using Services from Java"><!-- Legacy link --></a>
<h2 id="usingServicesFromJava">8.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 &#123;
void buyBook(Book book) &#123;
// logic
&#125;
&#125;</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&#45;keyword">package</span> bookstore<p class="paragraph"/>class BookService &#123;
void buyBook(Book book) &#123;
// logic
&#125;
&#125;</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&#45;keyword">package</span> bookstore<p class="paragraph"/><span class="java&#45;keyword">interface</span> BookStore &#123;
void buyBook(Book book)
&#125;</pre></div><p class="paragraph"/>And then the service:<p class="paragraph"/><div class="code"><pre>class BookService <span class="java&#45;keyword">implements</span> bookstore.BookStore &#123;
void buyBook(Book b) &#123;
// logic
&#125;
&#125;</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&#45;keyword">package</span> bookstore;<p class="paragraph"/><span class="java&#45;keyword">public</span> class BookConsumer &#123;<p class="paragraph"/> <span class="java&#45;keyword">private</span> BookStore store;<p class="paragraph"/> <span class="java&#45;keyword">public</span> void setBookStore(BookStore storeInstance) &#123;
<span class="java&#45;keyword">this</span>.store = storeInstance;
&#125;
&#8230;
&#125;</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&#45;tag">&#60;bean id=<span class="xml&#45;quote">"bookConsumer"</span> class=<span class="xml&#45;quote">"bookstore.BookConsumer"</span>&#62;</span>
<span class="xml&#45;tag">&#60;property name=<span class="xml&#45;quote">"bookStore"</span> ref=<span class="xml&#45;quote">"bookService"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;/bean&#62;</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&#45;keyword">import</span> bookstore.BookConsumer<p class="paragraph"/>beans = &#123;
bookConsumer(BookConsumer) &#123;
bookStore = ref(<span class="java&#45;quote">"bookService"</span>)
&#125;
&#125;</pre></div>
<a name="9. Testing"><!-- Legacy link --></a>
<h1 id="testing">9 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-&#42;</code> and <code>generate-&#42;</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&#45;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&#45;app</pre></div><p class="paragraph"/>The command will produce output such as:<p class="paragraph"/><div class="code"><pre>&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;
Running Unit Tests&#8230;
Running test FooTests...FAILURE
Unit Tests Completed in 464ms &#8230;
&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;<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&#45;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&#45;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&#45;app &#42;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&#45;app some.org.&#42;Controller</pre></div><p class="paragraph"/>or to run all tests in a package...<p class="paragraph"/><div class="code"><pre>grails test&#45;app some.org.&#42;</pre></div><p class="paragraph"/>or to run all tests in a package including subpackages...<p class="paragraph"/><div class="code"><pre>grails test&#45;app some.org.&#42;&#42;.&#42;</pre></div><p class="paragraph"/>You can also target particular test methods...<p class="paragraph"/><div class="code"><pre>grails test&#45;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&#45;app some.org.&#42; 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&#45;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&#45;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&#45;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&#45;app functional:spock</pre></div><p class="paragraph"/>More than one pattern can be specified...<p class="paragraph"/><div class="code"><pre>grails test&#45;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&#45;app integration: unit: some.org.&#42;&#42;.&#42;</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="9.1 Unit Testing"><!-- Legacy link --></a>
<h2 id="unitTesting">9.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="https://grails.apache.org/docs/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.TestMixin</code></li>
<li><code>grails.test.mixin.Mock</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.webflow/WebFlowUnitTestMixin</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 a test a controller and associated domains you would define the following:<p class="paragraph"/><div class="code"><pre>@TestFor(BookController)
<code>Mock(&#91;Book, Author, BookService&#93;)</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@ annotation creates mock version of any collaborators. There is an in-memory implementation of GORM that will simulate most interactions with the GORM API. For those interactions that are not automatically mocked you can use the built in support for defining mocks and stubs programmatically. For example:<p class="paragraph"/>
<div class="code"><pre>void testSearch() &#123;
def control = mockFor(SearchService)
control.demand.searchWeb &#123; <span class="java&#45;object">String</span> q &#45;&#62; &#91;'mock results'&#93; &#125;
control.demand.<span class="java&#45;keyword">static</span>.logResults &#123; List results &#45;&#62; &#125;
controller.searchService = control.createMock()
controller.search()<p class="paragraph"/> assert controller.response.text.contains <span class="java&#45;quote">"Found 1 results"</span>
&#125;</pre></div>
<a name="9.1.1 Unit Testing Controllers"><!-- Legacy link --></a>
<h2 id="unitTestingControllers">9.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&#45;keyword">import</span> grails.test.mixin.TestFor<p class="paragraph"/>@TestFor(SimpleController)
class SimpleControllerTests &#123;
void testSomething() &#123;<p class="paragraph"/> &#125;
&#125;</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 &#123;
def hello() &#123;
render <span class="java&#45;quote">"hello"</span>
&#125;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>void testHello() &#123;
controller.hello()<p class="paragraph"/> assert response.text == 'hello'
&#125;</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>// Test class
class SimpleController &#123;
def index() &#123;
redirect action: 'hello'
&#125;
&#8230;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>void testIndex() &#123;
controller.index()<p class="paragraph"/> assert response.redirectedUrl == '/simple/hello'
&#125;</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>void testList() &#123;
params.sort = <span class="java&#45;quote">"name"</span>
params.max = 20
params.offset = 0<p class="paragraph"/> controller.list()
&#8230;
&#125;</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>void testSave() &#123;
request.method = <span class="java&#45;quote">"POST"</span>
controller.save()
&#8230;
&#125;</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>void testGetPage() &#123;
request.method = <span class="java&#45;quote">"POST"</span>
request.makeAjaxRequest()
controller.getPage()
&#8230;
&#125;</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>// Test class
class SimpleController &#123;
def home() &#123;
render view: <span class="java&#45;quote">"homePage"</span>, model: &#91;title: <span class="java&#45;quote">"Hello World"</span>&#93;
&#125;
&#8230;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>void testIndex() &#123;
controller.home()<p class="paragraph"/> assert view == <span class="java&#45;quote">"/simple/homePage"</span>
assert model.title == <span class="java&#45;quote">"Hello World"</span>
&#125;</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 &#123;
def display() &#123;
render template:<span class="java&#45;quote">"snippet"</span>
&#125;
&#125;</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>void testDisplay() &#123;
controller.display()
assert response.text == 'contents of template'
&#125;</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>void testDisplay() &#123;
views&#91;'/simple/_snippet.gsp'&#93; = 'mock contents'
controller.display()
assert response.text == 'mock contents'
&#125;</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 &#123;
def showBookDetails() &#123;
&#91;title: 'The Nature Of Necessity', author: 'Alvin Plantinga'&#93;
&#125;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> grails.test.mixin.&#42;<p class="paragraph"/>@TestFor(SimpleController)
class SimpleControllerTests &#123;<p class="paragraph"/> void testShowBookDetails() &#123;
def model = controller.showBookDetails()<p class="paragraph"/> assert model.author == 'Alvin Plantinga'
&#125;
&#125;</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() &#123;
render(contentType:<span class="java&#45;quote">"text/xml"</span>) &#123;
book(title:<span class="java&#45;quote">"Great"</span>)
&#125;
&#125;</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>void testRenderXml() &#123;
controller.renderXml()
assert <span class="java&#45;quote">"&#60;book title='Great'/&#62;"</span> == response.text
assert <span class="java&#45;quote">"Great"</span> == response.xml.@title.text()
&#125;</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() &#123;
render(contentType:<span class="java&#45;quote">"text/json"</span>) &#123;
book = <span class="java&#45;quote">"Great"</span>
&#125;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>// test
void testRenderJson() &#123;<p class="paragraph"/> controller.renderJson()<p class="paragraph"/> assert '&#123;<span class="java&#45;quote">"book"</span>:<span class="java&#45;quote">"Great"</span>&#125;' == response.text
assert <span class="java&#45;quote">"Great"</span> == response.json.book
&#125;</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() &#123;
def b = <span class="java&#45;keyword">new</span> Book(params&#91;'book'&#93;)<p class="paragraph"/> render b.title
&#125;</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>void testConsumeBookXml() &#123;
request.xml = '&#60;book&#62;&#60;title&#62;The Shining&#60;/title&#62;&#60;/book&#62;'
controller.consumeBook()<p class="paragraph"/> assert response.text == 'The Shining'
&#125;</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>void testConsumeBookXml() &#123;
request.xml = <span class="java&#45;keyword">new</span> Book(title:<span class="java&#45;quote">"The Shining"</span>)
controller.consumeBook()<p class="paragraph"/> assert response.text == 'The Shining'
&#125;</pre></div><p class="paragraph"/>The same can be done for JSON requests:<p class="paragraph"/><div class="code"><pre>void testConsumeBookJson() &#123;
request.json = <span class="java&#45;keyword">new</span> Book(title:<span class="java&#45;quote">"The Shining"</span>)
controller.consumeBook()<p class="paragraph"/> assert response.text == 'The Shining'
&#125;</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() &#123;
request.withFormat &#123;
xml &#123;
render request.XML.@title
&#125;
json &#123;
render request.JSON.title
&#125;
&#125;
&#125;</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>void testConsumeXml() &#123;
request.xml = '&#60;book title=<span class="java&#45;quote">"The Stand"</span> /&#62;'<p class="paragraph"/> controller.consume()<p class="paragraph"/> assert response.text == 'The Stand'
&#125;</pre></div><p class="paragraph"/>And, of course, the same can be done for JSON:<p class="paragraph"/><div class="code"><pre>void testConsumeJson() &#123;
request.json = '&#123;title:<span class="java&#45;quote">"The Stand"</span>&#125;'
controller.consume()<p class="paragraph"/> assert response.text == 'The Stand'
&#125;</pre></div><p class="paragraph"/><h4>Testing Spring Beans</h4><p class="paragraph"/>When using <code>TestFor</code> only a subset of the Spring beans available to a running Grails application are available. If you wish to make additional beans available you can do so with the <code>defineBeans</code> method of <code>GrailsUnitTestMixin</code>:<p class="paragraph"/><div class="code"><pre>class SimpleController &#123;
SimpleService simpleService
def hello() &#123;
render simpleService.sayHello()
&#125;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>void testBeanWiring() &#123;
defineBeans &#123;
simpleService(SimpleService)
&#125;<p class="paragraph"/> controller.hello()<p class="paragraph"/> assert response.text == <span class="java&#45;quote">"Hello World"</span>
&#125;</pre></div><p class="paragraph"/>The controller is auto-wired by Spring just like in a running Grails application. Autowiring even occurs if you instantiate subsequent instances of the controller:<p class="paragraph"/><div class="code"><pre>void testAutowiringViaNew() &#123;
defineBeans &#123;
simpleService(SimpleService)
&#125;<p class="paragraph"/> def controller1 = <span class="java&#45;keyword">new</span> SimpleController()
def controller2 = <span class="java&#45;keyword">new</span> SimpleController()<p class="paragraph"/> assert controller1.simpleService != <span class="java&#45;keyword">null</span>
assert controller2.simpleService != <span class="java&#45;keyword">null</span>
&#125;</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 response's <code>format</code> attribute:<p class="paragraph"/><div class="code"><pre>// controller action
def sayHello() &#123;
def data = &#91;Hello:<span class="java&#45;quote">"World"</span>&#93;
withFormat &#123;
xml &#123; render data as XML &#125;
html data
&#125;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>// test
void testSayHello() &#123;
response.format = 'xml'
controller.sayHello()<p class="paragraph"/> <span class="java&#45;object">String</span> expected = '&#60;?xml version=<span class="java&#45;quote">"1.0"</span> encoding=<span class="java&#45;quote">"UTF&#45;8"</span>?&#62;' +
'&#60;map&#62;&#60;entry key=<span class="java&#45;quote">"Hello"</span>&#62;World&#60;/entry&#62;&#60;/map&#62;'<p class="paragraph"/> assert expected == response.text
&#125;</pre></div><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() &#123;
withForm &#123;
render <span class="java&#45;quote">"Good"</span>
&#125;.invalidToken &#123;
render <span class="java&#45;quote">"Bad"</span>
&#125;
&#125;</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>void testDuplicateFormSubmission() &#123;
controller.handleForm()
assert <span class="java&#45;quote">"Bad"</span> == response.text
&#125;</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&#45;keyword">import</span> org.codehaus.groovy.grails.web.servlet.mvc.SynchronizerToken
...<p class="paragraph"/>void testValidFormSubmission() &#123;
def token = SynchronizerToken.store(session)
params&#91;SynchronizerToken.KEY&#93; = token.currentToken.toString()<p class="paragraph"/> controller.handleForm()
assert <span class="java&#45;quote">"Good"</span> == response.text
&#125;</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>controller.handleForm() // first execution
&#8230;
response.reset()
&#8230;
controller.handleForm() // second execution</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() &#123;
MultipartFile file = request.getFile(<span class="java&#45;quote">"myFile"</span>)
file.transferTo(<span class="java&#45;keyword">new</span> File(<span class="java&#45;quote">"/local/disk/myFile"</span>))
&#125;</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>void testFileUpload() &#123;
<span class="java&#45;keyword">final</span> file = <span class="java&#45;keyword">new</span> GrailsMockMultipartFile(<span class="java&#45;quote">"myFile"</span>, <span class="java&#45;quote">"foo"</span>.bytes)
request.addFile(file)
controller.uploadFile()<p class="paragraph"/> assert file.targetFileLocation.path == <span class="java&#45;quote">"/local/disk/myFile"</span>
&#125;</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>def handleCommand(SimpleCommand simple) &#123;
<span class="java&#45;keyword">if</span> (simple.hasErrors()) &#123;
render <span class="java&#45;quote">"Bad"</span>
&#125;
<span class="java&#45;keyword">else</span> &#123;
render <span class="java&#45;quote">"Good"</span>
&#125;
&#125;</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>void testInvalidCommand() &#123;
def cmd = mockCommandObject(SimpleCommand)
cmd.name = '' // doesn't allow blank names<p class="paragraph"/> cmd.validate()
controller.handleCommand(cmd)<p class="paragraph"/> assert response.text == 'Bad'
&#125;</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() &#123;
render g.message(code: <span class="java&#45;quote">"foo.bar"</span>)
&#125;</pre></div><p class="paragraph"/>This can be tested as follows:<p class="paragraph"/><div class="code"><pre>void testRenderBasicTemplateWithTags() &#123;
messageSource.addMessage(<span class="java&#45;quote">"foo.bar"</span>, request.locale, <span class="java&#45;quote">"Hello World"</span>)<p class="paragraph"/> controller.showMessage()<p class="paragraph"/> assert response.text == <span class="java&#45;quote">"Hello World"</span>
&#125;</pre></div>
<a name="9.1.2 Unit Testing Tag Libraries"><!-- Legacy link --></a>
<h2 id="unitTestingTagLibraries">9.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>@TestFor(SimpleTagLib)
class SimpleTagLibTests &#123;<p class="paragraph"/>&#125;</pre></div><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>@TestFor(SimpleController)
@Mock(SimpleTagLib)
class GroovyPageUnitTestMixinTests &#123;<p class="paragraph"/>&#125;</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 &#123;<p class="paragraph"/> <span class="java&#45;keyword">static</span> namespace = 's'<p class="paragraph"/> def hello = &#123; attrs, body &#45;&#62;
out &#60;&#60; <span class="java&#45;quote">"Hello $&#123;attrs.name ?: 'World'&#125;"</span>
&#125;
&#125;</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>@TestFor(SimpleTagLib)
class SimpleTagLibTests &#123;
void testHelloTag() &#123;
assert applyTemplate('&#60;s:hello /&#62;') == 'Hello World'
assert applyTemplate('&#60;s:hello name=<span class="java&#45;quote">"Fred"</span> /&#62;') == 'Hello Fred'
&#125;
&#125;</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>@grails.test.mixin.TestMixin(GroovyPageUnitTestMixin)
class MultipleTagLibraryTests &#123;<p class="paragraph"/> @Test
void testMuliple() &#123;
mockTagLib(FirstTagLib)
mockTagLib(SecondTagLib)<p class="paragraph"/> &#8230;
&#125;
&#125;</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>@grails.test.mixin.TestMixin(GroovyPageUnitTestMixin)
class MultipleTagLibraryTests &#123;<p class="paragraph"/> @Test
void testMuliple() &#123;
mockTagLib(FirstTagLib)
mockTagLib(SecondTagLib)
assertOutputEquals ('Hello World', '&#60;s:hello /&#62;')
assertOutputMatches (/.&#42;Fred.&#42;/, '&#60;s:hello name=<span class="java&#45;quote">"Fred"</span> /&#62;')
&#125;
&#125;</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>def result = render(template: <span class="java&#45;quote">"/simple/hello"</span>)
assert result == <span class="java&#45;quote">"Hello World"</span></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.
<a name="9.1.3 Unit Testing Domains"><!-- Legacy link --></a>
<h2 id="unitTestingDomains">9.1.3 Unit Testing Domains</h2>
<h4>Overview</h4><p class="paragraph"/><blockquote class="note">
The mocking support described here is best used when testing non-domain artifacts that use domain classes, to let you focus on testing the artifact without needing a database. But when testing persistence it's best to use integration tests which configure Hibernate and use a database.
</blockquote><p class="paragraph"/>Domain class interaction can be tested without involving a database connection using <code>DomainClassUnitTestMixin</code>. This implementation mimics the behavior of GORM against an in-memory <code>ConcurrentHashMap</code> implementation. Note that this has limitations compared to a real GORM implementation. The following features of GORM for Hibernate can only be tested within an integration test:
<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"/>However 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"/>If something isn't supported then <code>GrailsUnitTestMixin</code>'s <code>mockFor</code> method can come in handy to mock the missing pieces. Alternatively you can write an integration test which bootstraps the complete Grails environment at a cost of test execution time.<p class="paragraph"/><h4>The 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&#45;keyword">import</span> grails.test.mixin.&#42;<p class="paragraph"/>@TestFor(SimpleController)
@Mock(Simple)
class SimpleControllerTests &#123;<p class="paragraph"/>&#125;</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 &#123;
def save() &#123;
def book = <span class="java&#45;keyword">new</span> Book(params)
<span class="java&#45;keyword">if</span> (book.save(flush: <span class="java&#45;keyword">true</span>)) &#123;
flash.message = message(
code: '<span class="java&#45;keyword">default</span>.created.message',
args: &#91;message(code: 'book.label',
<span class="java&#45;keyword">default</span>: 'Book'), book.id&#93;)&#125;<span class="java&#45;quote">"
redirect(action: "</span>show<span class="java&#45;quote">", id: book.id)
&#125;
<span class="java&#45;keyword">else</span> &#123;
render(view: "</span>create", model: &#91;bookInstance: book&#93;)
&#125;
&#125;
&#125;</pre></div><p class="paragraph"/>Tests for this action can be written as follows:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> grails.test.mixin.&#42;<p class="paragraph"/>@TestFor(BookController)
@Mock(Book)
class BookControllerTests &#123;<p class="paragraph"/> void testSaveInvalidBook() &#123;
controller.save()<p class="paragraph"/> assert model.bookInstance != <span class="java&#45;keyword">null</span>
assert view == '/book/create'
&#125;<p class="paragraph"/> void testSaveValidBook() &#123;
params.title = <span class="java&#45;quote">"The Stand"</span>
params.pages = <span class="java&#45;quote">"500"</span><p class="paragraph"/> controller.save()<p class="paragraph"/> assert response.redirectedUrl == '/book/show/1'
assert flash.message != <span class="java&#45;keyword">null</span>
assert Book.count() == 1
&#125;
&#125;</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>@TestFor(BookController)
@Mock(&#91;Book, Author&#93;)
class BookControllerTests &#123;
&#8230;
&#125;</pre></div><p class="paragraph"/>Alternatively you can also use the <code>DomainClassUnitTestMixin</code> directly with the <code>TestMixin</code> annotation:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> grails.test.mixin.domain.DomainClassUnitTestMixin<p class="paragraph"/>@TestFor(BookController)
@TestMixin(DomainClassUnitTestMixin)
class BookControllerTests &#123;
&#8230;
&#125;</pre></div><p class="paragraph"/>And then call the <code>mockDomain</code> method to mock domains during your test:<p class="paragraph"/><div class="code"><pre>void testSave() &#123;
mockDomain(Author)
mockDomain(Book)
&#125;</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>void testSave() &#123;
mockDomain(Book, &#91;
&#91;title: <span class="java&#45;quote">"The Stand"</span>, pages: 1000&#93;,
&#91;title: <span class="java&#45;quote">"The Shining"</span>, pages: 400&#93;,
&#91;title: <span class="java&#45;quote">"Along Came a Spider"</span>, pages: 300&#93; &#93;)
&#125;</pre></div><p class="paragraph"/><h4>Testing Constraints</h4><p class="paragraph"/>Your constraints contain logic and that logic is highly susceptible to bugs - the kind of bugs that can be tricky to track down (particularly as by default <code>save()</code> doesn't throw an exception when it fails). If your answer is that it's too hard or fiddly, that is no longer an excuse. Enter the <code>mockForConstraintsTests()</code> method.<p class="paragraph"/>This method is like a much reduced version of the <code>mockDomain()</code> method that simply adds a <code>validate()</code> method to a given domain class. All you have to do is mock the class, create an instance with populated data, and then call <code>validate()</code>. You can then access the <code>errors</code> property to determine if validation failed. So if all we are doing is mocking the <code>validate()</code> method, why the optional list of test instances? That is so that we can test the <code>unique</code> constraint as you will soon see.<p class="paragraph"/>So, suppose we have a simple domain class:<p class="paragraph"/><div class="code"><pre>class Book &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> title
<span class="java&#45;object">String</span> author<p class="paragraph"/> <span class="java&#45;keyword">static</span> constraints = &#123;
title blank: <span class="java&#45;keyword">false</span>, unique: <span class="java&#45;keyword">true</span>
author blank: <span class="java&#45;keyword">false</span>, minSize: 5
&#125;
&#125;</pre></div><p class="paragraph"/>Don't worry about whether the constraints are sensible (they're not!), they are for demonstration only. To test these constraints we can do the following:<p class="paragraph"/><div class="code"><pre>@TestFor(Book)
class BookTests &#123;
void testConstraints() &#123;<p class="paragraph"/> def existingBook = <span class="java&#45;keyword">new</span> Book(
title: <span class="java&#45;quote">"Misery"</span>,
author: <span class="java&#45;quote">"Stephen King"</span>)<p class="paragraph"/> mockForConstraintsTests(Book, &#91;existingBook&#93;)<p class="paragraph"/> // validation should fail <span class="java&#45;keyword">if</span> both properties are <span class="java&#45;keyword">null</span>
def book = <span class="java&#45;keyword">new</span> Book()<p class="paragraph"/> assert !book.validate()
assert <span class="java&#45;quote">"nullable"</span> == book.errors&#91;<span class="java&#45;quote">"title"</span>&#93;
assert <span class="java&#45;quote">"nullable"</span> == book.errors&#91;<span class="java&#45;quote">"author"</span>&#93;<p class="paragraph"/> // So let's demonstrate the unique and minSize constraints<p class="paragraph"/> book = <span class="java&#45;keyword">new</span> Book(title: <span class="java&#45;quote">"Misery"</span>, author: <span class="java&#45;quote">"JK"</span>)
assert !book.validate()
assert <span class="java&#45;quote">"unique"</span> == book.errors&#91;<span class="java&#45;quote">"title"</span>&#93;
assert <span class="java&#45;quote">"minSize"</span> == book.errors&#91;<span class="java&#45;quote">"author"</span>&#93;<p class="paragraph"/> // Validation should pass!
book = <span class="java&#45;keyword">new</span> Book(title: <span class="java&#45;quote">"The Shining"</span>, author: <span class="java&#45;quote">"Stephen King"</span>)
assert book.validate()
&#125;
&#125;</pre></div><p class="paragraph"/>You can probably look at that code and work out what's happening without any further explanation. The one thing we will explain is the way the <code>errors</code> property is used. First, is a real Spring <code>Errors</code> instance, so you can access all the properties and methods you would normally expect. Second, this particular <code>Errors</code> object also has map/property access as shown. Simply specify the name of the field you are interested in and the map/property access will return the name of the constraint that was violated. Note that it is the constraint name, not the message code (as you might expect).<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! It is currently one of the hardest bugs to track down normally, and yet a unit test for your constraints will highlight the problem straight away.
<a name="9.1.4 Unit Testing Filters"><!-- Legacy link --></a>
<h2 id="unitTestingFilters">9.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 &#123;
def filters = &#123;
all(controller:<span class="java&#45;quote">"simple"</span>, action:<span class="java&#45;quote">"list"</span>) &#123;
before = &#123;
redirect(controller:<span class="java&#45;quote">"book"</span>)
<span class="java&#45;keyword">return</span> <span class="java&#45;keyword">false</span>
&#125;
&#125;
&#125;
&#125;</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>@TestFor(SimpleController)
@Mock(CancellingFilters)
class SimpleControllerTests &#123;<p class="paragraph"/>&#125;</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>void testInvocationOfListActionIsFiltered() &#123;
withFilters(action:<span class="java&#45;quote">"list"</span>) &#123;
controller.list()
&#125;
assert response.redirectedUrl == '/book'
&#125;</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 a another controller you are testing then you can specify it:<p class="paragraph"/><div class="code"><pre>withFilters(controller:<span class="java&#45;quote">"book"</span>,action:<span class="java&#45;quote">"list"</span>) &#123;
controller.list()
&#125;</pre></div>
<a name="9.1.5 Unit Testing URL Mappings"><!-- Legacy link --></a>
<h2 id="unitTestingURLMappings">9.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>@TestFor(UrlMappings)
class UrlMappingsTests &#123;<p class="paragraph"/>&#125;</pre></div><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&#45;keyword">static</span> mappings = &#123;
<span class="java&#45;quote">"/action1"</span>(controller: <span class="java&#45;quote">"simple"</span>, action: <span class="java&#45;quote">"action1"</span>)
<span class="java&#45;quote">"/action2"</span>(controller: <span class="java&#45;quote">"simple"</span>, action: <span class="java&#45;quote">"action2"</span>)
&#125;</pre></div><p class="paragraph"/>The following test can be written to assert these URL mappings:<p class="paragraph"/><div class="code"><pre>void testUrlMappings() &#123;<p class="paragraph"/> assertForwardUrlMapping(<span class="java&#45;quote">"/action1"</span>, controller: 'simple',
action: <span class="java&#45;quote">"action1"</span>)<p class="paragraph"/> assertForwardUrlMapping(<span class="java&#45;quote">"/action2"</span>, controller: 'simple',
action: <span class="java&#45;quote">"action2"</span>)<p class="paragraph"/> shouldFail &#123;
assertForwardUrlMapping(<span class="java&#45;quote">"/action2"</span>, controller: 'simple',
action: <span class="java&#45;quote">"action1"</span>)
&#125;
&#125;</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>.<p class="paragraph"/><h4>Simulating Controller Mapping</h4><p class="paragraph"/>In addition to the assertions to check the validity of URL mappings you can also simulate mapping to a controller by using your <code>UrlMappings</code> as a mock collaborator and the <code>mapURI</code> method. For example:<p class="paragraph"/><div class="code"><pre>@TestFor(SimpleController)
@Mock(UrlMappings)
class SimpleControllerTests &#123;<p class="paragraph"/> void testControllerMapping() &#123;<p class="paragraph"/> SimpleController controller = mapURI('/simple/list')
assert controller != <span class="java&#45;keyword">null</span><p class="paragraph"/> def model = controller.list()
assert model != <span class="java&#45;keyword">null</span>
&#125;
&#125;</pre></div>
<a name="9.1.6 Mocking Collaborators"><!-- Legacy link --></a>
<h2 id="mockingCollaborators">9.1.6 Mocking Collaborators</h2>
Beyond the specific targeted mocking APIs there is also an all-purpose <code>mockFor()</code> method that is available when using the <code>TestFor</code> annotation. The signature of <code>mockFor</code> is:<p class="paragraph"/><div class="code"><pre>mockFor(class, loose = <span class="java&#45;keyword">false</span>)</pre></div><p class="paragraph"/>This is general-purpose mocking that lets you set up either strict or loose demands on a class.<p class="paragraph"/>This method is surprisingly intuitive to use. By default it will create a strict mock control object (one for which the order in which methods are called is important) that you can use to specify demands:<p class="paragraph"/><div class="code"><pre>def strictControl = mockFor(MyService)
strictControl.demand.someMethod(0..2) &#123; <span class="java&#45;object">String</span> arg1, <span class="java&#45;object">int</span> arg2 &#45;&#62; &#8230; &#125;
strictControl.demand.<span class="java&#45;keyword">static</span>.aStaticMethod &#123;&#45;&#62; &#8230; &#125;</pre></div><p class="paragraph"/>Notice that you can mock static as well as instance methods by using the "static" property. You then specify the name of the method to mock, with an optional range argument. This range determines how many times you expect the method to be called, and if the number of invocations falls outside of that range (either too few or too many) then an assertion error will be thrown. If no range is specified, a default of "1..1" is assumed, i.e. that the method must be called exactly once.<p class="paragraph"/>The last part of a demand is a closure representing the implementation of the mock method. The closure arguments must match the number and types of the mocked method, but otherwise you are free to add whatever you want in the body.<p class="paragraph"/>Call <code>mockControl.createMock()</code> to get an actual mock instance of the class that you are mocking. You can call this multiple times to create as many mock instances as you need. And once you have executed the test method, call <code>mockControl.verify()</code> to check that the expected methods were called.<p class="paragraph"/>Lastly, the call:<p class="paragraph"/><div class="code"><pre>def looseControl = mockFor(MyService, <span class="java&#45;keyword">true</span>)</pre></div><p class="paragraph"/>will create a mock control object that has only loose expectations, i.e. the order that methods are invoked does not matter.
<a name="9.2 Integration Testing"><!-- Legacy link --></a>
<h2 id="integrationTesting">9.2 Integration Testing</h2>
Integration tests differ from unit tests in that you have full access to the Grails environment within the test. Grails uses an in-memory H2 database for integration tests and clears out all the data from the database between tests.<p class="paragraph"/>One thing to bear in mind is that logging is enabled for your application classes, but it is different from logging in tests. So if you have something like this:<p class="paragraph"/><div class="code"><pre>class MyServiceTests <span class="java&#45;keyword">extends</span> GroovyTestCase &#123;
void testSomething() &#123;
log.info <span class="java&#45;quote">"Starting tests"</span>
&#8230;
&#125;
&#125;</pre></div><p class="paragraph"/>the "starting tests" message is logged using a different system than the one used by the application. The <code>log</code> property in the example above is an instance of <code>java.util.logging.Logger</code> (inherited from the base class, not injected by Grails), which doesn't have the same methods as the <code>log</code> property injected into your application artifacts. For example, it doesn't have <code>debug()</code> or <code>trace()</code> methods, and the equivalent of <code>warn()</code> is in fact <code>warning()</code>.<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. Add a <code>transactional</code> property to your test class to check transactional behaviour:<p class="paragraph"/><div class="code"><pre>class MyServiceTests <span class="java&#45;keyword">extends</span> GroovyTestCase &#123;
<span class="java&#45;keyword">static</span> transactional = <span class="java&#45;keyword">false</span><p class="paragraph"/> void testMyTransactionalServiceMethod() &#123;
&#8230;
&#125;
&#125;</pre></div><p class="paragraph"/>Be sure to remove any persisted data from a non-transactional test, for example in the <code>tearDown</code> method, so these tests don't interfere with standard transactional tests that expect a clean database.<p class="paragraph"/><h4>Testing Controllers</h4><p class="paragraph"/>To test controllers you first have to understand the Spring Mock Library.<p class="paragraph"/>Grails automatically configures each test with a <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/mock/web/MockHttpServletRequest.html" class="api">MockHttpServletRequest</a>, <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/mock/web/MockHttpServletResponse.html" class="api">MockHttpServletResponse</a>, and <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/mock/web/MockHttpSession.html" class="api">MockHttpSession</a> that you can use in your tests. For example consider the following controller:<p class="paragraph"/><div class="code"><pre>class FooController &#123;<p class="paragraph"/> def text() &#123;
render <span class="java&#45;quote">"bar"</span>
&#125;<p class="paragraph"/> def someRedirect() &#123;
redirect(action:<span class="java&#45;quote">"bar"</span>)
&#125;
&#125;</pre></div><p class="paragraph"/>The tests for this would be:<p class="paragraph"/><div class="code"><pre>class FooControllerTests <span class="java&#45;keyword">extends</span> GroovyTestCase &#123;<p class="paragraph"/> void testText() &#123;
def fc = <span class="java&#45;keyword">new</span> FooController()
fc.text()
assertEquals <span class="java&#45;quote">"bar"</span>, fc.response.contentAsString
&#125;<p class="paragraph"/> void testSomeRedirect() &#123;
def fc = <span class="java&#45;keyword">new</span> FooController()
fc.someRedirect()
assertEquals <span class="java&#45;quote">"/foo/bar"</span>, fc.response.redirectedUrl
&#125;
&#125;</pre></div><p class="paragraph"/>In the above case <code>response</code> is an instance of <code>MockHttpServletResponse</code> which we can use to obtain the generated content with <code>contentAsString</code> (when writing to the response) or the redirected URL. These mocked versions of the Servlet API are completely mutable (unlike the real versions) and hence you can set properties on the request such as the <code>contextPath</code> and so on.<p class="paragraph"/>Grails <strong class="bold">does not</strong> invoke <a href="../guide/single.html#interceptors" class="guide">interceptors</a> or servlet filters when calling actions during integration testing. You should test interceptors and filters in isolation, using <a href="../guide/single.html#functionalTesting" class="guide">functional testing</a> if necessary.<p class="paragraph"/><h4>Testing Controllers with Services</h4><p class="paragraph"/>If your controller references a service (or other Spring beans), you have to explicitly initialise the service from your test.<p class="paragraph"/>Given a controller using a service:<p class="paragraph"/><div class="code"><pre>class FilmStarsController &#123;
def popularityService<p class="paragraph"/> def update() &#123;
// <span class="java&#45;keyword">do</span> something with popularityService
&#125;
&#125;</pre></div><p class="paragraph"/>The test for this would be:<p class="paragraph"/><div class="code"><pre>class FilmStarsTests <span class="java&#45;keyword">extends</span> GroovyTestCase &#123;
def popularityService<p class="paragraph"/> void testInjectedServiceInController () &#123;
def fsc = <span class="java&#45;keyword">new</span> FilmStarsController()
fsc.popularityService = popularityService
fsc.update()
&#125;
&#125;</pre></div><p class="paragraph"/><h4>Testing Controller Command Objects</h4><p class="paragraph"/>With command objects you just supply parameters to the request and it will automatically do the command object work for you when you call your action with no parameters:<p class="paragraph"/>Given a controller using a command object:<p class="paragraph"/><div class="code"><pre>class AuthenticationController &#123;
def signup(SignupForm form) &#123;
&#8230;
&#125;
&#125;</pre></div><p class="paragraph"/>You can then test it like this:<p class="paragraph"/><div class="code"><pre>def controller = <span class="java&#45;keyword">new</span> AuthenticationController()
controller.params.login = <span class="java&#45;quote">"marcpalmer"</span>
controller.params.password = <span class="java&#45;quote">"secret"</span>
controller.params.passwordConfirm = <span class="java&#45;quote">"secret"</span>
controller.signup()</pre></div><p class="paragraph"/>Grails auto-magically sees your call to <code>signup()</code> as a call to the action and populates the command object from the mocked request parameters. During controller testing, the <code>params</code> are mutable with a mocked request supplied by Grails.<p class="paragraph"/><h4>Testing Controllers and the render Method</h4><p class="paragraph"/>The <a href="../ref/Controllers/render.html" class="controllers">render</a> method lets you render a custom view at any point within the body of an action. For instance, consider the example below:<p class="paragraph"/><div class="code"><pre>def save() &#123;
def book = Book(params)
<span class="java&#45;keyword">if</span> (book.save()) &#123;
// handle
&#125;
<span class="java&#45;keyword">else</span> &#123;
render(view:<span class="java&#45;quote">"create"</span>, model:&#91;book:book&#93;)
&#125;
&#125;</pre></div><p class="paragraph"/>In the above example the result of the model of the action is not available as the return value, but instead is stored within the <code>modelAndView</code> property of the controller. The <code>modelAndView</code> property is an instance of Spring MVC's <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/ModelAndView.html" target="blank">ModelAndView</a> class and you can use it to the test the result of an action:<p class="paragraph"/><div class="code"><pre>def bookController = <span class="java&#45;keyword">new</span> BookController()
bookController.save()
def model = bookController.modelAndView.model.book</pre></div><p class="paragraph"/><h4>Simulating Request Data</h4><p class="paragraph"/>You can use the Spring <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/mock/web/MockHttpServletRequest.html" class="api">MockHttpServletRequest</a> to test an action that requires request data, for example a REST web service. For example consider this action which performs data binding from an incoming request:<p class="paragraph"/><div class="code"><pre>def create() &#123;
&#91;book: <span class="java&#45;keyword">new</span> Book(params.book)&#93;
&#125;</pre></div><p class="paragraph"/>To simulate the 'book' parameter as an XML request you could do something like the following:<p class="paragraph"/><div class="code"><pre>void testCreateWithXML() &#123;<p class="paragraph"/> def controller = <span class="java&#45;keyword">new</span> BookController()<p class="paragraph"/> controller.request.contentType = 'text/xml'
controller.request.content = '''&#92;&#10; &#60;?xml version=<span class="java&#45;quote">"1.0"</span> encoding=<span class="java&#45;quote">"ISO&#45;8859&#45;1"</span>?&#62;
&#60;book&#62;
&#60;title&#62;The Stand&#60;/title&#62;
&#8230;
&#60;/book&#62;
'''.stripIndent().getBytes() // note we need the bytes<p class="paragraph"/> def model = controller.create()
assert model.book
assertEquals <span class="java&#45;quote">"The Stand"</span>, model.book.title
&#125;</pre></div><p class="paragraph"/>The same can be achieved with a JSON request:<p class="paragraph"/><div class="code"><pre>void testCreateWithJSON() &#123;<p class="paragraph"/> def controller = <span class="java&#45;keyword">new</span> BookController()<p class="paragraph"/> controller.request.contentType = <span class="java&#45;quote">"text/json"</span>
controller.request.content =
'&#123;<span class="java&#45;quote">"id"</span>:1,<span class="java&#45;quote">"class"</span>:<span class="java&#45;quote">"Book"</span>,<span class="java&#45;quote">"title"</span>:<span class="java&#45;quote">"The Stand"</span>&#125;'.getBytes()<p class="paragraph"/> def model = controller.create()
assert model.book
assertEquals <span class="java&#45;quote">"The Stand"</span>, model.book.title
&#125;</pre></div><p class="paragraph"/><blockquote class="note">
With JSON don't forget the <code>class</code> property to specify the name the target type to bind to. In XML this is implicit within the name of the <code>&#60;book&#62;</code> node, but this property is required as part of the JSON packet.
</blockquote><p class="paragraph"/>For more information on the subject of REST web services see the section on <a href="../guide/single.html#REST" class="guide">REST</a>.<p class="paragraph"/><h4>Testing Web Flows</h4><p class="paragraph"/>Testing <a href="../guide/single.html#webflow" class="guide">Web Flows</a> requires a special test harness called <code>grails.test.WebFlowTestCase</code> which subclasses Spring Web Flow's <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/webflow/test/execution/AbstractFlowExecutionTests.html" class="api">AbstractFlowExecutionTests</a> class.<p class="paragraph"/><blockquote class="note">
Subclasses of <code>WebFlowTestCase</code> <strong class="bold">must</strong> be integration tests
</blockquote><p class="paragraph"/>For example given this simple flow:<p class="paragraph"/><div class="code"><pre>class ExampleController &#123;<p class="paragraph"/> def exampleFlow() &#123;
start &#123;
on(<span class="java&#45;quote">"go"</span>) &#123;
flow.hello = <span class="java&#45;quote">"world"</span>
&#125;.to <span class="java&#45;quote">"next"</span>
&#125;
next &#123;
on(<span class="java&#45;quote">"back"</span>).to <span class="java&#45;quote">"start"</span>
on(<span class="java&#45;quote">"go"</span>).to <span class="java&#45;quote">"subber"</span>
&#125;
subber &#123;
subflow(action: <span class="java&#45;quote">"sub"</span>)
on(<span class="java&#45;quote">"end"</span>).to(<span class="java&#45;quote">"end"</span>)
&#125;
end()
&#125;<p class="paragraph"/> def subFlow() &#123;
subSubflowState &#123;
subflow(controller: <span class="java&#45;quote">"other"</span>, action: <span class="java&#45;quote">"otherSub"</span>)
on(<span class="java&#45;quote">"next"</span>).to(<span class="java&#45;quote">"next"</span>)
&#125;
&#8230;
&#125;
&#125;</pre></div><p class="paragraph"/>You need to tell the test harness what to use for the "flow definition". This is done via overriding the abstract <code>getFlow</code>
method:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> grails.test.WebFlowTestCase<p class="paragraph"/>class ExampleFlowTests <span class="java&#45;keyword">extends</span> WebFlowTestCase &#123;
def getFlow() &#123; <span class="java&#45;keyword">new</span> ExampleController().exampleFlow &#125;
&#8230;
&#125;</pre></div><p class="paragraph"/>You can specify the flow id by overriding the <code>getFlowId</code> method, otherwise the default is <code>test</code>:
<div class="code"><pre><span class="java&#45;keyword">import</span> grails.test.WebFlowTestCase<p class="paragraph"/>class ExampleFlowTests <span class="java&#45;keyword">extends</span> WebFlowTestCase &#123;
<span class="java&#45;object">String</span> getFlowId() &#123; <span class="java&#45;quote">"example"</span> &#125;
&#8230;
&#125;</pre></div><p class="paragraph"/>If the flow under test calls any subflows, these (or mocks) must be registered before the calling the flow:
<div class="code"><pre><span class="java&#45;keyword">protected</span> void setUp() &#123;
<span class="java&#45;keyword">super</span>.setUp()<p class="paragraph"/> registerFlow(<span class="java&#45;quote">"other/otherSub"</span>) &#123; // register a simplified mock
start &#123;
on(<span class="java&#45;quote">"next"</span>).to(<span class="java&#45;quote">"end"</span>)
&#125;
end()
&#125;<p class="paragraph"/> // register the original subflow
registerFlow(<span class="java&#45;quote">"example/sub"</span>, <span class="java&#45;keyword">new</span> ExampleController().subFlow)
&#125;</pre></div><p class="paragraph"/>Then you kick off the flow with the <code>startFlow</code> method:<p class="paragraph"/><div class="code"><pre>void testExampleFlow() &#123;
def viewSelection = startFlow()
&#8230;
&#125;</pre></div><p class="paragraph"/>Use the <code>signalEvent</code> method to trigger an event:<p class="paragraph"/><div class="code"><pre>void testExampleFlow() &#123;
&#8230;
signalEvent(<span class="java&#45;quote">"go"</span>)
assert <span class="java&#45;quote">"next"</span> == flowExecution.activeSession.state.id
assert <span class="java&#45;quote">"world"</span> == flowScope.hello
&#125;</pre></div><p class="paragraph"/>Here we have signaled to the flow to execute the event "go" which causes a transition to the "next" state. In the example a transition action placed a <code>hello</code> variable into the flow scope.<p class="paragraph"/><h4>Testing Tag Libraries</h4><p class="paragraph"/>Testing tag libraries is simple because when a tag is invoked as a method it returns its result as a string (technically a <code>StreamCharBuffer</code> but this class implements all of the methods of <code>String</code>). So for example if you have a tag library like this:<p class="paragraph"/><div class="code"><pre>class FooTagLib &#123;<p class="paragraph"/> def bar = &#123; attrs, body &#45;&#62;
out &#60;&#60; <span class="java&#45;quote">"&#60;p&#62;Hello World!&#60;/p&#62;"</span>
&#125;<p class="paragraph"/> def bodyTag = &#123; attrs, body &#45;&#62;
out &#60;&#60; <span class="java&#45;quote">"&#60;&#36;&#123;attrs.name&#125;&#62;"</span>
out &#60;&#60; body()
out &#60;&#60; <span class="java&#45;quote">"&#60;/&#36;&#123;attrs.name&#125;&#62;"</span>
&#125;
&#125;</pre></div><p class="paragraph"/>The tests would look like:<p class="paragraph"/><div class="code"><pre>class FooTagLibTests <span class="java&#45;keyword">extends</span> GroovyTestCase &#123;<p class="paragraph"/> void testBarTag() &#123;
assertEquals <span class="java&#45;quote">"&#60;p&#62;Hello World!&#60;/p&#62;"</span>,
<span class="java&#45;keyword">new</span> FooTagLib().bar(<span class="java&#45;keyword">null</span>, <span class="java&#45;keyword">null</span>).toString()
&#125;<p class="paragraph"/> void testBodyTag() &#123;
assertEquals <span class="java&#45;quote">"&#60;p&#62;Hello World!&#60;/p&#62;"</span>,
<span class="java&#45;keyword">new</span> FooTagLib().bodyTag(name: <span class="java&#45;quote">"p"</span>) &#123;
<span class="java&#45;quote">"Hello World!"</span>
&#125;.toString()
&#125;
&#125;</pre></div><p class="paragraph"/>Notice that for the second example, <code>testBodyTag</code>, we pass a block that returns the body of the tag. This is convenient to representing the body as a String.<p class="paragraph"/><h4>Testing Tag Libraries with GroovyPagesTestCase</h4><p class="paragraph"/>In addition to doing simple testing of tag libraries like in the above examples, you can also use the <code>grails.test.GroovyPagesTestCase</code> class to test tag libraries with integration tests.<p class="paragraph"/>The <code>GroovyPagesTestCase</code> class is a subclass of the standard <code>GroovyTestCase</code> class and adds utility methods for testing the output of GSP rendering.<p class="paragraph"/><blockquote class="note">
<code>GroovyPagesTestCase</code> can only be used in an integration test.
</blockquote><p class="paragraph"/>For example, consider this date formatting tag library:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> java.text.SimpleDateFormat<p class="paragraph"/>class FormatTagLib &#123;
def dateFormat = &#123; attrs, body &#45;&#62;
out &#60;&#60; <span class="java&#45;keyword">new</span> SimpleDateFormat(attrs.format) &#60;&#60; attrs.date
&#125;
&#125;</pre></div><p class="paragraph"/>This can be easily tested as follows:<p class="paragraph"/><div class="code"><pre>class FormatTagLibTests <span class="java&#45;keyword">extends</span> GroovyPagesTestCase &#123;
void testDateFormat() &#123;
def template =
'&#60;g:dateFormat format=<span class="java&#45;quote">"dd&#45;MM&#45;yyyy"</span> date=<span class="java&#45;quote">"&#36;&#123;myDate&#125;"</span> /&#62;'<p class="paragraph"/> def testDate = &#8230; // create the date
assertOutputEquals('01&#45;01&#45;2008', template, &#91;myDate:testDate&#93;)
&#125;
&#125;</pre></div><p class="paragraph"/>You can also obtain the result of a GSP using the <code>applyTemplate</code> method of the <code>GroovyPagesTestCase</code> class:<p class="paragraph"/><div class="code"><pre>class FormatTagLibTests <span class="java&#45;keyword">extends</span> GroovyPagesTestCase &#123;
void testDateFormat() &#123;
def template =
'&#60;g:dateFormat format=<span class="java&#45;quote">"dd&#45;MM&#45;yyyy"</span> date=<span class="java&#45;quote">"&#36;&#123;myDate&#125;"</span> /&#62;'<p class="paragraph"/> def testDate = &#8230; // create the date
def result = applyTemplate(template, &#91;myDate:testDate&#93;)<p class="paragraph"/> assertEquals '01&#45;01&#45;2008', result
&#125;
&#125;</pre></div><p class="paragraph"/><h4>Testing Domain Classes</h4><p class="paragraph"/>Testing domain classes is typically a simple matter of using the <a href="../guide/single.html#GORM" class="guide">GORM API</a>, but there are a few things to be aware of. Firstly, when testing queries you often need to "flush" to ensure the correct state has been persisted to the database. For example take the following example:<p class="paragraph"/><div class="code"><pre>void testQuery() &#123;
def books = &#91;
<span class="java&#45;keyword">new</span> Book(title: <span class="java&#45;quote">"The Stand"</span>),
<span class="java&#45;keyword">new</span> Book(title: <span class="java&#45;quote">"The Shining"</span>)&#93;
books&#42;.save()<p class="paragraph"/> assertEquals 2, Book.list().size()
&#125;</pre></div><p class="paragraph"/>This test will fail because calling <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> does not actually persist the <code>Book</code> instances when called. Calling <code>save</code> only indicates to Hibernate that at some point in the future these instances should be persisted. To commit changes immediately you "flush" them:<p class="paragraph"/><div class="code"><pre>void testQuery() &#123;
def books = &#91;
<span class="java&#45;keyword">new</span> Book(title: <span class="java&#45;quote">"The Stand"</span>),
<span class="java&#45;keyword">new</span> Book(title: <span class="java&#45;quote">"The Shining"</span>)&#93;
books&#42;.save(flush: <span class="java&#45;keyword">true</span>)<p class="paragraph"/> assertEquals 2, Book.list().size()
&#125;</pre></div><p class="paragraph"/>In this case since we're passing the argument <code>flush</code> with a value of <code>true</code> the updates will be persisted immediately and hence will be available to the query later on.
<a name="9.3 Functional Testing"><!-- Legacy link --></a>
<h2 id="functionalTesting">9.3 Functional Testing</h2>
Functional tests involve making HTTP requests against the running application and verifying the resultant behaviour. Grails does not ship with any support for writing functional tests directly, but there are several plugins available for this.
<ul class="star">
<li><code>Canoo Webtest</code> - <a href="http://grails.org/plugin/webtest" target="blank">http://grails.org/plugin/webtest</a></li>
<li><code>G-Func</code> - <a href="http://grails.org/plugin/functional-test" target="blank">http://grails.org/plugin/functional-test</a></li>
<li><code>Geb</code> - <a href="http://grails.org/plugin/geb" target="blank">http://grails.org/plugin/geb</a></li>
<li><code>Selenium-RC</code> - <a href="http://grails.org/plugin/selenium-rc" target="blank">http://grails.org/plugin/selenium-rc</a></li>
<li><code>WebDriver</code> - <a href="http://grails.org/plugin/webdriver" target="blank">http://grails.org/plugin/webdriver</a></li>
</ul><p class="paragraph"/>Consult the documentation for each plugin for its capabilities.<p class="paragraph"/><h4>Common Options</h4><p class="paragraph"/>There are options that are common to all plugins that control how the Grails application is launched, if at all.<p class="paragraph"/><h5>inline</h5><p class="paragraph"/>The <code>-inline</code> option specifies that the grails application should be started inline (i.e. like <code>run-app</code>).<p class="paragraph"/><strong class="bold">This option is implicitly set unless the <code>baseUrl</code> or <code>war</code> options are set</strong><p class="paragraph"/><h5>war</h5><p class="paragraph"/>The <code>-war</code> option specifies that the grails application should be packaged as a war and started. This is useful as it tests your application in a production-like state, but it has a longer startup time than the <code>-inline</code> option. It also runs the war in a forked JVM, meaning that you cannot access any internal application objects.<p class="paragraph"/><div class="code"><pre>grails test&#45;app functional: &#45;war</pre></div><p class="paragraph"/>Note that the same build/config options for the <a href="../ref/Command Line/run-war.html" class="commandLine">run-war</a> command apply to functional testing against the WAR.<p class="paragraph"/><h5>https</h5><p class="paragraph"/>The <code>-https</code> option results in the application being able to receive https requests as well as http requests. It is compatible with both the <code>-inline</code> and <code>-war</code> options.<p class="paragraph"/><div class="code"><pre>grails test&#45;app functional: &#45;https</pre></div><p class="paragraph"/>Note that this does not change the test <em class="italic">base url</em> to be https, it will still be http unless the <code>-httpsBaseUrl</code> option is also given.<p class="paragraph"/><h5>httpsBaseUrl</h5><p class="paragraph"/>The <code>-httpsBaseUrl</code> causes the implicit base url to be used for tests to be a https url.<p class="paragraph"/><div class="code"><pre>grails test&#45;app functional: &#45;httpsBaseUrl</pre></div><p class="paragraph"/>This option is ignored if the <code>-baseUrl</code> option is specified.<p class="paragraph"/><h5>baseUrl</h5><p class="paragraph"/>The <code>baseUrl</code> option allows the base url for tests to be specified.<p class="paragraph"/><div class="code"><pre>grails test&#45;app functional: &#45;baseUrl=http://mycompany.com/grailsapp</pre></div><p class="paragraph"/>This option will prevent the local grails application being started unless <code>-inline</code> or <code>-war</code> are given as well. To use a custom base url but still test against the local Grails application you <strong class="bold">must</strong> specify one of either the <code>-inline</code> or <code>-war</code> options.
<a name="10. Internationalization"><!-- Legacy link --></a>
<h1 id="i18n">10 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://download.oracle.com/javase/1.5.0/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/englangn.html" target="blank">language code</a> and a <a href="http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html" target="blank">country code</a>. For example "en_US" is the code for US english, whilst "en_GB" is the for British English.
<a name="10.1 Understanding Message Bundles"><!-- Legacy link --></a>
<h2 id="understandingMessageBundles">10.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="10.2 Changing Locales"><!-- Legacy link --></a>
<h2 id="changingLocales">10.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="10.3 Reading Messages"><!-- Legacy link --></a>
<h2 id="readingMessages">10.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&#45;tag">&#60;g:message code=<span class="xml&#45;quote">"my.localized.content"</span> /&#62;</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&#45;tag">&#60;g:message code=<span class="xml&#45;quote">"my.localized.content"</span> args=<span class="xml&#45;quote">"$&#123; &#91;'Juan', 'lunes'&#93; &#125;"</span> /&#62;</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 &#123;0&#125;. Hoy es &#123;1&#125;.</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() &#123;
def msg = message(code: <span class="java&#45;quote">"my.localized.content"</span>, args: &#91;'Juan', 'lunes'&#93;)
&#125;</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 = &#123; attrs, body &#45;&#62;
def msg = g.message(code: <span class="java&#45;quote">"my.localized.content"</span>, args: &#91;'Juan', 'lunes'&#93;)
&#125;</pre></div>
<a name="10.4 Scaffolding and i18n"><!-- Legacy link --></a>
<h2 id="scaffoldingAndI18n">10.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.
<a name="11. Security"><!-- Legacy link --></a>
<h1 id="security">11 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="11.1 Securing Against Attacks"><!-- Legacy link --></a>
<h2 id="securingAgainstAttacks">11.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() &#123;
def books = Book.find(<span class="java&#45;quote">"from Book as b where b.title ='"</span> + params.title + <span class="java&#45;quote">"'"</span>)
&#125;</pre></div><p class="paragraph"/>or the analagous call using a GString:<p class="paragraph"/><div class="code"><pre>def vulnerable() &#123;
def books = Book.find(<span class="java&#45;quote">"from Book as b where b.title ='$&#123;params.title&#125;'"</span>)
&#125;</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() &#123;
def books = Book.find(<span class="java&#45;quote">"from Book as b where b.title = ?"</span>,
&#91;params.title&#93;)
&#125;</pre></div><p class="paragraph"/>or<p class="paragraph"/><div class="code"><pre>def safe() &#123;
def books = Book.find(<span class="java&#45;quote">"from Book as b where b.title = :title"</span>,
&#91;title: params.title&#93;)
&#125;</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. Ticketing and page flow systems can help this and Grails' support for <a href="http://www.springsource.org/webflow" target="blank">Spring Web Flow</a> includes security like this by default.<p class="paragraph"/>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 call <a href="../guide/single.html#codecs" class="guide">encodeAsHTML</a> on every object to ensure that people cannot maliciously inject JavaScript or other HTML into data or tags viewed by others. Grails supplies several <a href="../guide/single.html#codecs" class="guide">Dynamic Encoding Methods</a> for this purpose and if your output escaping format is not supported you can easily write your own codec.<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>def safeMax = <span class="java&#45;object">Math</span>.max(params.max?.toInteger(), 100) // limit to 100 results
<span class="java&#45;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="11.2 Encoding and Decoding Objects"><!-- Legacy link --></a>
<h2 id="codecs">11.2 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>$&#123;report.description.encodeAsHTML()&#125;</pre></div><p class="paragraph"/>Decoding is performed using <code>value.decodeHTML()</code> syntax.<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 &#62; 1?" you wouldn't be able to show this safely within an HTML page because the &#62; 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>&#60;input name=<span class="java&#45;quote">"comment.message"</span> value=<span class="java&#45;quote">"$&#123;comment.message.encodeAsHTML()&#125;"</span>/&#62;</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"/><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 &#38; 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>&#60;a href=<span class="java&#45;quote">"/mycontroller/find?searchKey=$&#123;lastSearch.encodeAsURL()&#125;"</span>&#62;
Repeat last search
&#60;/a&#62;</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: $&#123;user.registrationCode.encodeAsBase64()&#125;</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('$&#123;elementId&#125;',
'$&#123;render(template: <span class="java&#45;quote">"/common/message"</span>).encodeAsJavaScript()&#125;')</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: &#35;$&#123;&#91;255,127,255&#93;.encodeAsHex()&#125;</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: $&#123;user.uniqueID.encodeAsMD5()&#125;</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&#45;object">byte</span>&#91;&#93; 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: $&#123;user.uniqueID.encodeAsSHA1()&#125;</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&#45;object">byte</span>&#91;&#93; 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: $&#123;user.uniqueID.encodeAsSHA256()&#125;</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&#45;object">byte</span>&#91;&#93; 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 &#123;
<span class="java&#45;keyword">static</span> encode = &#123; str &#45;&#62;
// convert the string to pig latin and <span class="java&#45;keyword">return</span> the result
&#125;
&#125;</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>$&#123;lastName.encodeAsPigLatin()&#125;</pre></div>
<a name="11.3 Authentication"><!-- Legacy link --></a>
<h2 id="authentication">11.3 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 either <a href="../guide/single.html#interceptors" class="guide">interceptors</a> or <a href="../guide/single.html#filters" class="guide">filters</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"/>Filters 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/conf/SecurityFilters.groovy</code> by running:<p class="paragraph"/><div class="code"><pre>grails create&#45;filters security</pre></div><p class="paragraph"/>and implement your interception logic there:<p class="paragraph"/><div class="code"><pre>class SecurityFilters &#123;
def filters = &#123;
loginCheck(controller: '&#42;', action: '&#42;') &#123;
before = &#123;
<span class="java&#45;keyword">if</span> (!session.user &#38;&#38; actionName != <span class="java&#45;quote">"login"</span>) &#123;
redirect(controller: <span class="java&#45;quote">"user"</span>, action: <span class="java&#45;quote">"login"</span>)
<span class="java&#45;keyword">return</span> <span class="java&#45;keyword">false</span>
&#125;
&#125;
&#125;
&#125;
&#125;</pre></div><p class="paragraph"/>Here the <code>loginCheck</code> filter 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() &#123;
<span class="java&#45;keyword">if</span> (request.get) &#123;
<span class="java&#45;keyword">return</span> // render the login view
&#125;<p class="paragraph"/> def u = User.findByLogin(params.login)
<span class="java&#45;keyword">if</span> (u) &#123;
<span class="java&#45;keyword">if</span> (u.password == params.password) &#123;
session.user = u
redirect(action: <span class="java&#45;quote">"home"</span>)
&#125;
<span class="java&#45;keyword">else</span> &#123;
render(view: <span class="java&#45;quote">"login"</span>, model: &#91;message: <span class="java&#45;quote">"Password incorrect"</span>&#93;)
&#125;
&#125;
<span class="java&#45;keyword">else</span> &#123;
render(view: <span class="java&#45;quote">"login"</span>, model: &#91;message: <span class="java&#45;quote">"User not found"</span>&#93;)
&#125;
&#125;</pre></div>
<a name="11.4 Security Plug-ins"><!-- Legacy link --></a>
<h2 id="securityPlugins">11.4 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="11.4.1 Spring Security"><!-- Legacy link --></a>
<h2 id="springSecurity">11.4.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="11.4.2 Shiro"><!-- Legacy link --></a>
<h2 id="shiro">11.4.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 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&#45;keyword">extends</span> JsecAuthBase &#123;
<span class="java&#45;keyword">static</span> accessControl = &#123;
// 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: &#91; 'create', 'edit', 'save', 'update' &#93;)
&#125;
&#8230;
&#125;</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="12. Plug-ins"><!-- Legacy link --></a>
<h1 id="plugins">12 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="12.1 Creating and Installing Plug-ins"><!-- Legacy link --></a>
<h2 id="creatingAndInstallingPlugins">12.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&#45;plugin &#91;PLUGIN NAME&#93;</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"/>The structure of a Grails plugin is very nearly the same as a Grails application project's except that in the root of the plugin directory you will find a plugin Groovy file called the "plugin descriptor".<p class="paragraph"/>Being a regular Grails project has a number of benefits in that you can immediately test your plugin by running:<p class="paragraph"/><div class="code"><pre>grails run&#45;app</pre></div><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 &#123;
def version = <span class="java&#45;quote">"0.1"</span><p class="paragraph"/> &#8230;
&#125;</pre></div><p class="paragraph"/>All plugins must have this class in the root of their directory structure. The plugin class defines the version of the plugin and other metadata, 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>version</code> - The version of your plugin. Valid values include example "0.1", "0.2-SNAPSHOT", "1.1.4" etc.</li>
<li><code>grailsVersion</code> - The version of version range of Grails that the plugin supports. eg. "1.2 &#62; *" (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 &#123;
def version = <span class="java&#45;quote">"0.1"</span>
def grailsVersion = <span class="java&#45;quote">"1.1 &#62; &#42;"</span>
def author = <span class="java&#45;quote">"Sergey Nebolsin"</span>
def authorEmail = <span class="java&#45;quote">"nebolsin@gmail.com"</span>
def title = <span class="java&#45;quote">"Quartz Plugin"</span>
def description = '''&#92;
The Quartz plugin allows your Grails application to schedule jobs&#92;
to be executed using a specified interval or cron expression. The&#92;
underlying system uses the Quartz Enterprise Job Scheduler configured&#92;
via Spring, but is made simpler by the coding by convention paradigm.&#92;
'''
def documentation = <span class="java&#45;quote">"http://grails.org/plugin/quartz"</span><p class="paragraph"/> &#8230;
&#125;</pre></div><p class="paragraph"/><h4>Installing and Distributing Plugins</h4><p class="paragraph"/>To distribute a plugin you navigate to its root directory in a console and run:<p class="paragraph"/><div class="code"><pre>grails <span class="java&#45;keyword">package</span>&#45;plugin</pre></div><p class="paragraph"/>This will create a zip file of the plugin starting with <code>grails-</code> then the plugin name and version. For example with the example plugin created earlier this would be <code>grails-example-0.1.zip</code>. The <code>package-plugin</code> command will also generate a <code>plugin.xml</code> file which contains machine-readable information about plugin's name, version, author, and so on.<p class="paragraph"/>Once you have a plugin distribution file you can navigate to a Grails project and run:<p class="paragraph"/><div class="code"><pre>grails install&#45;plugin /path/to/grails&#45;example&#45;0.1.zip</pre></div><p class="paragraph"/>If the plugin is hosted on an HTTP server you can install it with:<p class="paragraph"/><div class="code"><pre>grails install&#45;plugin http://myserver.com/plugins/grails&#45;example&#45;0.1.zip</pre></div><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/conf/BootStrap.groovy</code></li>
<li><code>grails-app/conf/BuildConfig.groovy</code> (although it is used to generate <code>dependencies.groovy</code>)</li>
<li><code>grails-app/conf/Config.groovy</code></li>
<li><code>grails-app/conf/DataSource.groovy</code> (and any other <code>*DataSource.groovy</code>)</li>
<li><code>grails-app/conf/UrlMappings.groovy</code></li>
<li><code>grails-app/conf/spring/resources.groovy</code></li>
<li>Everything within <code>/web-app/WEB-INF</code></li>
<li>Everything within <code>/web-app/plugins/&#42;&#42;</code></li>
<li>Everything within <code>/test/&#42;&#42;</code></li>
<li>SCM management files within <code>&#42;&#42;/.svn/&#42;&#42;</code> and <code>&#42;&#42;/CVS/&#42;&#42;</code></li>
</ul><p class="paragraph"/>If you need artefacts within <code>WEB-INF</code> it is recommended you use the <code>_Install.groovy</code> script (covered later), which is executed when a plugin is installed, to provide such artefacts. In addition, although <code>UrlMappings.groovy</code> is excluded you are allowed to include a <code>UrlMappings</code> definition with a different name, such as <code>MyPluginUrlMappings.groovy</code>.<p class="paragraph"/><h4>Specifying Plugin Locations</h4><p class="paragraph"/>An application can load plugins from anywhere on the file system, even if they have not been installed. Specify the location of the (unpacked) plugin in the application's <code>grails-app/conf/BuildConfig.groovy</code> file:<p class="paragraph"/><div class="code"><pre>// Useful to test plugins you are developing.
grails.plugin.location.shiro =
<span class="java&#45;quote">"/home/dilbert/dev/plugins/grails&#45;shiro"</span><p class="paragraph"/>// Useful <span class="java&#45;keyword">for</span> modular applications where all plugins and
// applications are in the same directory.
grails.plugin.location.'grails&#45;ui' = <span class="java&#45;quote">"../grails&#45;grails&#45;ui"</span></pre></div><p class="paragraph"/>This is particularly useful in two cases:
<ul class="star">
<li>You are developing a plugin and want to test it in a real application without packaging and installing it first.</li>
<li>You have split an application into a set of plugins and an application, all in the same "super-project" directory.</li>
</ul><p class="paragraph"/><h4>Global plugins</h4><p class="paragraph"/>Plugins can also be installed globally for all applications for a particular version of Grails using the <code>&#45;global</code> flag, for example:<p class="paragraph"/><div class="code"><pre>grails install&#45;plugin webtest &#45;global</pre></div><p class="paragraph"/>The default location is &#36;USER_HOME/.grails/&#60;grailsVersion&#62;/global-plugins but this can be customized with the <code>grails.global.plugins.dir</code> setting in <code>BuildConfig.groovy</code>.
<a name="12.2 Plugin Repositories"><!-- Legacy link --></a>
<h2 id="repositories">12.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&#45;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&#45;info &#91;plugin&#45;name&#93;</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 <a href="http://grails.org/Creating+Plugins" target="blank">this wiki page</a>.
</blockquote><p class="paragraph"/>When you have access to the Grails Plugin repository, install the <a href="http://grails-plugins.github.com/grails-release/docs/index.html" target="blank">Release Plugin</a> and execute the <code>publish-plugin</code> command to release your plugin:<p class="paragraph"/><div class="code"><pre>grails install&#45;plugin release
grails publish&#45;plugin</pre></div><p class="paragraph"/>This will automatically commit any remaining source code changes to your SCM provider and then publish the plugin to the central repository. If the command is successful, it will immediately be available on the plugin portal at http://grails.org/plugin/&#60;pluginName&#62;. You can find out more about the Release plugin and its other features in <a href="http://grails-plugins.github.com/grails-release/docs/index.html" target="blank">its user guide</a>.<p class="paragraph"/><h4>Configuring Additional Repositories</h4><p class="paragraph"/>The process for configuring repositories in Grails differs between versions. For version of Grails 1.2 and earlier please refer to the <a href="https://grails.apache.org/docs/1.2.x/guide/12.%20Plug-ins.html#12.2%20Plugin%20Repositories" target="blank">Grails 1.2 documentation</a> on the subject. The following sections cover Grails 1.3 and above.<p class="paragraph"/>Grails 1.3 and above use Ivy under the hood to resolve plugin dependencies. The mechanism for defining additional plugin repositories is largely the same as <a href="../guide/single.html#ivy" class="guide">defining repositories for JAR dependencies</a>. For example you can define a remote Maven repository that contains Grails plugins using the following syntax in <code>grails-app/conf/BuildConfig.groovy</code>:<p class="paragraph"/><div class="code"><pre>repositories &#123;
mavenRepo <span class="java&#45;quote">"http://repository.codehaus.org"</span><p class="paragraph"/> // ...or with a name
mavenRepo name: <span class="java&#45;quote">"myRepo"</span>,
root: <span class="java&#45;quote">"http://myserver:8081/artifactory/plugins&#45;snapshots&#45;local"</span>
&#125;</pre></div><p class="paragraph"/>You can also define a SVN-based Grails repository (such as the one hosted at <a href="https://grails.apache.org/plugins.html/" target="blank">https://grails.apache.org/plugins.html</a>) using the <code>grailsRepo</code> method:<p class="paragraph"/><div class="code"><pre>repositories &#123;
grailsRepo <span class="java&#45;quote">"http://myserver/mygrailsrepo"</span><p class="paragraph"/> // ...or with a name
grailsRepo <span class="java&#45;quote">"http://myserver/svn/grails&#45;plugins"</span>, <span class="java&#45;quote">"mySvnRepo"</span>
&#125;</pre></div><p class="paragraph"/>There is a shortcut to setup the Grails central repository:<p class="paragraph"/><div class="code"><pre>repositories &#123;
grailsCentral()
&#125;</pre></div><p class="paragraph"/>The order in which plugins are resolved is based on the ordering of the repositories. So in this case the Grails central repository will be searched last:<p class="paragraph"/><div class="code"><pre>repositories &#123;
grailsRepo <span class="java&#45;quote">"http://myserver/mygrailsrepo"</span>
grailsCentral()
&#125;</pre></div><p class="paragraph"/>All of the above examples use HTTP; however you can specify any <a href="http://ant.apache.org/ivy/history/latest-milestone/settings/resolvers.html" target="blank">Ivy resolver</a> to resolve plugins with. Below is an example that uses an SSH resolver:<p class="paragraph"/><div class="code"><pre>def sshResolver = <span class="java&#45;keyword">new</span> SshResolver(user:<span class="java&#45;quote">"myuser"</span>, host:<span class="java&#45;quote">"myhost.com"</span>)
sshResolver.addArtifactPattern(
<span class="java&#45;quote">"/path/to/repo/grails&#45;&#91;artifact&#93;/tags/"</span> +
<span class="java&#45;quote">"LATEST_RELEASE/grails&#45;&#91;artifact&#93;&#45;&#91;revision&#93;.&#91;ext&#93;"</span>)
sshResolver.latestStrategy =
<span class="java&#45;keyword">new</span> org.apache.ivy.plugins.latest.LatestTimeStrategy()<p class="paragraph"/>sshResolver.changingPattern = <span class="java&#45;quote">".&#42;SNAPSHOT"</span>
sshResolver.setCheckmodified(<span class="java&#45;keyword">true</span>)</pre></div><p class="paragraph"/>The above example defines an artifact pattern which tells Ivy how to resolve a plugin zip file. For a more detailed explanation on Ivy patterns see the <a href="http://ant.apache.org/ivy/history/2.1.0/concept.html#patterns" target="blank">relevant section</a> in the Ivy user guide.<p class="paragraph"/><h4>Publishing to Maven Compatible Repositories</h4><p class="paragraph"/>In general it is recommended for Grails 1.3 and above to use standard Maven-style repositories to self host plugins. The benefits of doing so include the ability for existing tooling and repository managers to interpret the structure of a Maven repository. In addition Maven compatible repositories are not tied to SVN as Grails repositories are.<p class="paragraph"/>You use the Maven publisher plugin to publish a plugin to a Maven repository. Please refer to the section of the <a href="../guide/single.html#mavendeploy" class="guide">Maven deployment</a> user guide on the subject.<p class="paragraph"/><h4>Publishing to Grails Compatible Repositories</h4><p class="paragraph"/>Specify the <code>grails.plugin.repos.distribution.myRepository</code> setting within the grails-app/conf/BuildConfig.groovy file to publish a Grails plugin to a Grails-compatible repository:<p class="paragraph"/><div class="code"><pre>grails.plugin.repos.distribution.myRepository =
<span class="java&#45;quote">"https://svn.codehaus.org/grails/trunk/grails&#45;test&#45;plugin&#45;repo"</span></pre></div><p class="paragraph"/>You can also provide this settings in the &#36;USER_HOME/.grails/settings.groovy file if you prefer to share the same settings across multiple projects.<p class="paragraph"/>Once this is done use the <code>repository</code> argument of the <code>release-plugin</code> command to specify the repository to release the plugin into:<p class="paragraph"/><div class="code"><pre>grails release&#45;plugin &#45;repository = myRepository</pre></div>
<a name="12.3 Understanding a Plug-ins Structure"><!-- Legacy link --></a>
<h2 id="understandingPluginStructure">12.3 Understanding a Plugin's Structure</h2>
As as mentioned previously, a plugin is basically a regular Grails application with a plugin descriptor. However when installed, the structure of a plugin differs slightly. For example, take a look at this plugin directory structure:<p class="paragraph"/><div class="code"><pre>+ grails&#45;app
+ controllers
+ domain
+ taglib
etc.
+ lib
+ src
+ java
+ groovy
+ web&#45;app
+ js
+ css</pre></div><p class="paragraph"/>When a plugin is installed the contents of the <code>grails-app</code> directory will go into a directory such as <code>plugins/example-1.0/grails-app</code>. They <strong class="bold">will not</strong> be copied into the main source tree. A plugin never interferes with a project's primary source tree.<p class="paragraph"/>Dealing with static resources is slightly different. When developing a plugin, just like an application, all static resources go in the <code>web-app</code> directory. You can then link to static resources just like in an application. This example links to a JavaScript source:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;g:resource dir=<span class="xml&#45;quote">"js"</span> file=<span class="xml&#45;quote">"mycode.js"</span> /&#62;</span></pre></div><p class="paragraph"/>When you run the plugin in development mode the link to the resource will resolve to something like <code>/js/mycode.js</code>. However, when the plugin is installed into an application the path will automatically change to something like <code>/plugin/example-0.1/js/mycode.js</code> and Grails will deal with making sure the resources are in the right place.<p class="paragraph"/>There is a special <code>pluginContextPath</code> variable that can be used whilst both developing the plugin and when in the plugin is installed into the application to find out what the correct path to the plugin is.<p class="paragraph"/>At runtime the <code>pluginContextPath</code> variable will either evaluate to an empty string or <code>/plugins/example</code> depending on whether the plugin is running standalone or has been installed in an application<p class="paragraph"/>Java and Groovy code that the plugin provides within the lib and <code>src/java</code> and <code>src/groovy</code> directories will be compiled into the main project's <code>web-app/WEB-INF/classes</code> directory so that they are made available at runtime.
<a name="12.4 Providing Basic Artefacts"><!-- Legacy link --></a>
<h2 id="providingBasicArtefacts">12.4 Providing Basic Artefacts</h2>
<h4>Adding a new Script</h4><p class="paragraph"/>A plugin can add a new script simply by providing the relevant Gant script in its scripts directory:<p class="paragraph"/><div class="code"><pre>+ MyPlugin.groovy
+ scripts &#60;&#45;&#45; additional scripts here
+ grails&#45;app
+ controllers
+ services
+ etc.
+ lib</pre></div><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. Note that the plugin is loaded from where it is installed and not copied into the main application tree.<p class="paragraph"/><div class="code"><pre>+ ExamplePlugin.groovy
+ scripts
+ grails&#45;app
+ controllers &#60;&#45;&#45; additional controllers here
+ services &#60;&#45;&#45; additional services here
+ etc. &#60;&#45;&#45; additional XXX here
+ lib</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>&#60;g:render template=<span class="java&#45;quote">"fooTemplate"</span> plugin=<span class="java&#45;quote">"amazon"</span>/&#62;</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/BootStrap.groovy</code></li>
<li><code>grails-app/conf/BuildConfig.groovy</code> (although it is used to generate <code>dependencies.groovy</code>)</li>
<li><code>grails-app/conf/Config.groovy</code></li>
<li><code>grails-app/conf/DataSource.groovy</code> (and any other <code>*DataSource.groovy</code>)</li>
<li><code>grails-app/conf/UrlMappings.groovy</code></li>
<li><code>grails-app/conf/spring/resources.groovy</code></li>
<li>Everything within <code>/web-app/WEB-INF</code></li>
<li>Everything within <code>/web-app/plugins/&#42;&#42;</code></li>
<li>Everything within <code>/test/&#42;&#42;</code></li>
<li>SCM management files within <code>&#42;&#42;/.svn/&#42;&#42;</code> and <code>&#42;&#42;/CVS/&#42;&#42;</code></li>
</ul><p class="paragraph"/>If your plugin requires files under the <code>web-app/WEB-INF</code> directory it is recommended that you modify the plugin's <code>scripts/_Install.groovy</code> Gant script to install these artefacts into the target project's directory tree.<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 = &#91;
<span class="java&#45;quote">"grails&#45;app/views/error.gsp"</span>
&#93;</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="12.5 Evaluating Conventions"><!-- Legacy link --></a>
<h2 id="evaluatingConventions">12.5 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="../api/org/codehaus/groovy/grails/commons/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="../api/org/codehaus/groovy/grails/commons/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&#45;keyword">for</span> (grailsClass in application.allClasses) &#123;
println grailsClass.name
&#125;</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&#45;keyword">for</span> (controllerClass in application.controllerClasses) &#123;
println controllerClass.name
&#125;</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 (eg. '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="../api/org/codehaus/groovy/grails/commons/GrailsClass.html" class="api">javadoc API</a>.
<a name="12.6 Hooking into Build Events"><!-- Legacy link --></a>
<h2 id="hookingIntoBuildEvents">12.6 Hooking into Build Events</h2>
<h4>Post-Install Configuration and Participating in Upgrades</h4><p class="paragraph"/>Grails plugins can do post-install configuration and participate in application upgrade process (the <a href="../ref/Command Line/upgrade.html" class="commandLine">upgrade</a> command). This is achieved using two specially named scripts under the <code>scripts</code> directory of the plugin - <code>_Install.groovy</code> and <code>_Upgrade.groovy</code>.<p class="paragraph"/><code>_Install.groovy</code> is executed after the plugin has been installed and <code>_Upgrade.groovy</code> is executed each time the user upgrades the application (but not the plugin) with <a href="../ref/Command Line/upgrade.html" class="commandLine">upgrade</a> command.<p class="paragraph"/>These scripts are <a href="../guide/single.html#commandLine" class="guide">Gant</a> scripts, so you can use the full power of Gant. An addition to the standard Gant variables there is also a <code>pluginBasedir</code> variable which points at the plugin installation basedir.<p class="paragraph"/>As an example this <code>_Install.groovy</code> script will create a new directory type under the <code>grails-app</code> directory and install a configuration template:<p class="paragraph"/><div class="code"><pre>ant.mkdir(dir: <span class="java&#45;quote">"$&#123;basedir&#125;/grails&#45;app/jobs"</span>)<p class="paragraph"/>ant.copy(file: <span class="java&#45;quote">"$&#123;pluginBasedir&#125;/src/samples/SamplePluginConfig.groovy"</span>,
todir: <span class="java&#45;quote">"$&#123;basedir&#125;/grails&#45;app/conf"</span>)</pre></div><p class="paragraph"/><h4>Scripting events</h4><p class="paragraph"/>It is also possible to hook into command line scripting events. These are events triggered during execution of Grails target and plugin scripts.<p class="paragraph"/>For example, you can hook into status update output (i.e. "Tests passed", "Server running") and the creation of files or artefacts.<p class="paragraph"/>A plugin just has to provide an <code>_Events.groovy</code> script to listen to the required events. Refer the documentation on <a href="../guide/single.html#events" class="guide">Hooking into Events</a> for further information.
<a name="12.7 Hooking into Runtime Configuration"><!-- Legacy link --></a>
<h2 id="hookingIntoRuntimeConfiguration">12.7 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 by providing a property called <code>doWithSpring</code> which is assigned a block of code. 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&#45;keyword">import</span> org.springframework.web.servlet.i18n.CookieLocaleResolver
<span class="java&#45;keyword">import</span> org.springframework.web.servlet.i18n.LocaleChangeInterceptor
<span class="java&#45;keyword">import</span> org.springframework.context.support.ReloadableResourceBundleMessageSource<p class="paragraph"/>class I18nGrailsPlugin &#123;<p class="paragraph"/> def version = <span class="java&#45;quote">"0.1"</span><p class="paragraph"/> def doWithSpring = &#123;
messageSource(ReloadableResourceBundleMessageSource) &#123;
basename = <span class="java&#45;quote">"WEB&#45;INF/grails&#45;app/i18n/messages"</span>
&#125;
localeChangeInterceptor(LocaleChangeInterceptor) &#123;
paramName = <span class="java&#45;quote">"lang"</span>
&#125;
localeResolver(CookieLocaleResolver)
&#125;
&#125;</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>Participating in web.xml Generation</h4><p class="paragraph"/>Grails generates the <code>WEB-INF/web.xml</code> file at load time, and although plugins cannot change this file directly, they can participate in the generation of the file. A plugin can provide a <code>doWithWebDescriptor</code> property that is assigned a block of code that gets passed the <code>web.xml</code> as an <code>XmlSlurper</code> <code>GPathResult</code>.<p class="paragraph"/><h5>Add <code>servlet</code> and <code>servlet-mapping</code></h5><p class="paragraph"/>Consider this example from the <code>ControllersPlugin</code>:<p class="paragraph"/><div class="code"><pre>def doWithWebDescriptor = &#123; webXml &#45;&#62;<p class="paragraph"/> def mappingElement = webXml.'servlet&#45;mapping'<p class="paragraph"/> def lastMapping = mappingElement&#91;mappingElement.size() &#45; 1&#93;
lastMapping + &#123;
'servlet&#45;mapping' &#123;
'servlet&#45;name'(<span class="java&#45;quote">"grails"</span>)
'url&#45;pattern'(<span class="java&#45;quote">"&#42;.dispatch"</span>)
&#125;
&#125;
&#125;</pre></div><p class="paragraph"/>Here the plugin gets a reference to the last <code>&#60;servlet-mapping&#62;</code> element and appends Grails' servlet after it using XmlSlurper's ability to programmatically modify XML using closures and blocks.<p class="paragraph"/><h5>Add <code>filter</code> and <code>filter-mapping</code></h5><p class="paragraph"/>Adding a filter with its mapping works a little differently. The location of the <code>&#60;filter&#62;</code> element doesn't matter since order is not important, so it's simplest to insert your custom filter definition immediately after the last <code>&#60;context-param&#62;</code> element. Order <em class="italic">is</em> important for mappings, but the usual approach is to add it immediately after the last <code>&#60;filter&#62;</code> element like so:<p class="paragraph"/><div class="code"><pre>def doWithWebDescriptor = &#123; webXml &#45;&#62;<p class="paragraph"/> def contextParam = webXml.'context&#45;param'<p class="paragraph"/> contextParam&#91;contextParam.size() &#45; 1&#93; + &#123;
'filter' &#123;
'filter&#45;name'('springSecurityFilterChain')
'filter&#45;class'(DelegatingFilterProxy.name)
&#125;
&#125;<p class="paragraph"/> def filter = webXml.'filter'
filter&#91;filter.size() &#45; 1&#93; + &#123;
'filter&#45;mapping'&#123;
'filter&#45;name'('springSecurityFilterChain')
'url&#45;pattern'('/&#42;')
&#125;
&#125;
&#125;</pre></div><p class="paragraph"/>In some cases you need to ensure that your filter comes after one of the standard Grails filters, such as the Spring character encoding filter or the SiteMesh filter. Fortunately you can insert filter mappings immediately after the standard ones (more accurately, any that are in the template web.xml file) like so:<p class="paragraph"/><div class="code"><pre>def doWithWebDescriptor = &#123; webXml &#45;&#62;
...<p class="paragraph"/> // Insert the Spring Security filter after the Spring
// character encoding filter.
def filter = webXml.'filter&#45;mapping'.find &#123;
it.'filter&#45;name'.text() == <span class="java&#45;quote">"charEncodingFilter"</span>
&#125;<p class="paragraph"/> filter + &#123;
'filter&#45;mapping'&#123;
'filter&#45;name'('springSecurityFilterChain')
'url&#45;pattern'('/&#42;')
&#125;
&#125;
&#125;</pre></div><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://static.springsource.org/spring/docs/3.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 &#123;<p class="paragraph"/> def name = <span class="java&#45;quote">"simple"</span>
def version = <span class="java&#45;quote">"1.1"</span><p class="paragraph"/> def doWithApplicationContext = &#123; appCtx &#45;&#62;
def sessionFactory = appCtx.sessionFactory
// <span class="java&#45;keyword">do</span> something here with session factory
&#125;
&#125;</pre></div>
<a name="12.8 Adding Dynamic Methods at Runtime"><!-- Legacy link --></a>
<h2 id="addingDynamicMethodsAtRuntime">12.8 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> closure.<p class="paragraph"/>For Grails-managed classes like controllers, tag libraries and so forth you can add methods, constructors etc. using the <a href="http://groovy.codehaus.org/ExpandoMetaClass" target="blank">ExpandoMetaClass</a> mechanism by accessing each controller's <a href="api:http://groovy.codehaus.org/api/groovy/lang/MetaObjectProtocol.html" target="blank">MetaClass</a>:<p class="paragraph"/><div class="code"><pre>class ExamplePlugin &#123;
def doWithDynamicMethods = &#123; applicationContext &#45;&#62;
<span class="java&#45;keyword">for</span> (controllerClass in application.controllerClasses) &#123;
controllerClass.metaClass.myNewMethod = &#123;&#45;&#62; println <span class="java&#45;quote">"hello world"</span> &#125;
&#125;
&#125;
&#125;</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 &#123;<p class="paragraph"/> def doWithDynamicMethods = &#123; applicationContext &#45;&#62;
<span class="java&#45;object">String</span>.metaClass.swapCase = &#123;&#45;&#62;
def sb = <span class="java&#45;keyword">new</span> StringBuilder()
delegate.each &#123;
sb &#60;&#60; (<span class="java&#45;object">Character</span>.isUpperCase(it as <span class="java&#45;object">char</span>) ?
<span class="java&#45;object">Character</span>.toLowerCase(it as <span class="java&#45;object">char</span>) :
<span class="java&#45;object">Character</span>.toUpperCase(it as <span class="java&#45;object">char</span>))
&#125;
sb.toString()
&#125;<p class="paragraph"/> assert <span class="java&#45;quote">"UpAndDown"</span> == <span class="java&#45;quote">"uPaNDdOWN"</span>.swapCase()
&#125;
&#125;</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&#45;keyword">import</span> org.springframework.orm.hibernate3.HibernateTemplate<p class="paragraph"/>class ExampleHibernatePlugin &#123;<p class="paragraph"/> def doWithDynamicMethods = &#123; applicationContext &#45;&#62;<p class="paragraph"/> <span class="java&#45;keyword">for</span> (domainClass in application.domainClasses) &#123;<p class="paragraph"/> domainClass.metaClass.<span class="java&#45;keyword">static</span>.load = &#123; <span class="java&#45;object">Long</span> id&#45;&#62;
def sf = applicationContext.sessionFactory
def template = <span class="java&#45;keyword">new</span> HibernateTemplate(sf)
template.load(delegate, id)
&#125;
&#125;
&#125;
&#125;</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 &#123;<p class="paragraph"/> def doWithDynamicMethods = &#123; applicationContext &#45;&#62;
<span class="java&#45;keyword">for</span> (domainClass in application.domainClasses) &#123;
domainClass.metaClass.constructor = &#123;&#45;&#62;
<span class="java&#45;keyword">return</span> applicationContext.getBean(domainClass.name)
&#125;
&#125;
&#125;
&#125;</pre></div><p class="paragraph"/>Here we actually replace the default constructor with one that looks up prototyped Spring beans instead!
<a name="12.9 Participating in Auto Reload Events"><!-- Legacy link --></a>
<h2 id="participatingInAutoReloadEvents">12.9 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 &#123;
&#8230;
def watchedResources = <span class="java&#45;quote">"file:./grails&#45;app/services/&#42;Service.groovy"</span><p class="paragraph"/> &#8230;
def onChange = &#123; event &#45;&#62;
<span class="java&#45;keyword">if</span> (event.source) &#123;
def serviceClass = application.addServiceClass(event.source)
def serviceName = <span class="java&#45;quote">"&#36;&#123;serviceClass.propertyName&#125;"</span>
def beans = beans &#123;
<span class="java&#45;quote">"$serviceName"</span>(serviceClass.getClazz()) &#123; bean &#45;&#62;
bean.autowire = <span class="java&#45;keyword">true</span>
&#125;
&#125;
<span class="java&#45;keyword">if</span> (event.ctx) &#123;
event.ctx.registerBeanDefinition(
serviceName,
beans.getBeanDefinition(serviceName))
&#125;
&#125;
&#125;
&#125;</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 = &#91;'controllers'&#93;</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 = &#91;<span class="java&#45;quote">"controllers"</span>&#93;</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 = &#91;<span class="java&#45;quote">"&#42;"</span>&#93;</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="12.10 Understanding Plug-in Load Order"><!-- Legacy link --></a>
<h2 id="understandingPluginLoadOrder">12.10 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 &#123;<p class="paragraph"/> def version = <span class="java&#45;quote">"1.0"</span><p class="paragraph"/> def dependsOn = &#91;dataSource: <span class="java&#45;quote">"1.0"</span>,
domainClass: <span class="java&#45;quote">"1.0"</span>,
i18n: <span class="java&#45;quote">"1.0"</span>,
core: <span class="java&#45;quote">"1.0"</span>&#93;
&#125;</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 = &#91;foo: <span class="java&#45;quote">"&#42; &#62; 1.0"</span>&#93;
def dependsOn = &#91;foo: <span class="java&#45;quote">"1.0 &#62; 1.1"</span>&#93;
def dependsOn = &#91;foo: <span class="java&#45;quote">"1.0 &#62; &#42;"</span>&#93;</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 &#62; 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 = &#91;'controllers'&#93;</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&#45;keyword">if</span> (manager?.hasGrailsPlugin(<span class="java&#45;quote">"controllers"</span>)) &#123;
openSessionInViewInterceptor(OpenSessionInViewInterceptor) &#123;
flushMode = HibernateAccessor.FLUSH_MANUAL
sessionFactory = sessionFactory
&#125;
grailsUrlHandlerMapping.interceptors &#60;&#60; openSessionInViewInterceptor
&#125;</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="../api/org/codehaus/groovy/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 = &#91;'rabbitmq'&#93;</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 = &#91;'development', 'test', 'myCustomEnv'&#93;
def scopes = &#91;excludes:'war'&#93;</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="../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&#45;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 = &#91;<span class="java&#45;quote">"development"</span>, <span class="java&#45;quote">"test"</span>&#93;</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 = &#91;includes: &#91;<span class="java&#45;quote">"development"</span>, <span class="java&#45;quote">"test"</span>&#93;&#93;</pre></div><p class="paragraph"/>will do the same thing.
<h2 id="artefactApi">12.11 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">12.11.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="../api/org/codehaus/groovy/grails/commons/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&#45;keyword">for</span> (cls in grailsApplication.&#60;artefactType&#62;Classes) &#123;
&#8230;
&#125;</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&#45;keyword">for</span> (cls in grailsApplication.domainClasses) &#123;
&#8230;
&#125;</pre></div><p class="paragraph"/>and for URL mappings:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">for</span> (cls in grailsApplication.urlMappingsClasses) &#123;
&#8230;
&#125;</pre></div><p class="paragraph"/>You need to be aware that the objects returned by these properties are not instances of <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html" class="api">Class</a>. Instead, they are instances of <a href="../api/org/codehaus/groovy/grails/commons/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&#60;type&#62;Class(String name)</li>
<li>is&#60;type&#62;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">12.11.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 &#123;
def artefacts = &#91; org.somewhere.MyArtefactHandler &#93;
&#8230;
&#125;</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="../api/org/codehaus/groovy/grails/commons/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="../api/org/codehaus/groovy/grails/commons/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="../api/org/codehaus/groovy/grails/commons/GrailsClass.html" class="api">GrailsClass</a>. Again, skeleton implementations are available such as <a href="../api/org/codehaus/groovy/grails/commons/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="12.11 Binary Plugins"><!-- Legacy link --></a>
<h2 id="binaryPlugins">12.12 Binary Plugins</h2>
Regular Grails plugins are packaged as zip files containing the full source of the plugin. This has some advantages in terms of being an open distribution system (anyone can see the source), in addition to avoiding problems with the source compatibility level used for compilation.<p class="paragraph"/>As of Grails 2.0 you can pre-compile Grails plugins into regular JAR files known as "binary plugins". This has several advantages (and some disadvantages as discussed in the advantages of source plugins above) including:
<ul class="star">
<li>Binary plugins can be published as standard JAR files to a Maven repository</li>
<li>Binary plugins can be declared like any other JAR dependency</li>
<li>Commercial plugins are more viable since the source isn't published</li>
<li>IDEs have a better understanding since binary plugins are regular JAR files containing classes</li>
</ul><p class="paragraph"/><h4>Packaging</h4><p class="paragraph"/>To package a plugin in binary form you can use the package-plugin command and the <code>--binary</code> flag:<p class="paragraph"/><div class="code"><pre>grails <span class="java&#45;keyword">package</span>&#45;plugin &#45;&#45;binary</pre></div><p class="paragraph"/>Supported artefacts include:
<ul class="star">
<li>Grails artifact classes such as controllers, domain classes and so on</li>
<li>I18n Message bundles</li>
<li>GSP Views, layouts and templates</li>
</ul><p class="paragraph"/>You can also specify the packaging in the plugin descriptor:<p class="paragraph"/><div class="code"><pre>def packaging = <span class="java&#45;quote">"binary"</span></pre></div><p class="paragraph"/>in which case the packaging will default to binary.<p class="paragraph"/><h4>Using Binary Plugins</h4><p class="paragraph"/>The packaging process creates a JAR file in the <code>target</code> directory of the plugin, for example <code>target/foo-plugin-0.1.jar</code>. There are two ways to incorporate a binary plugin into an application.<p class="paragraph"/>One is simply placing the plugin JAR file in your application's <code>lib</code> directory. The other is to publish the plugin JAR to a compatible Maven repository and declare it as a dependency in <code>grails-app/conf/BuildConfig.groovy</code>:<p class="paragraph"/><div class="code"><pre>dependencies &#123;
compile <span class="java&#45;quote">"mycompany:myplugin:0.1"</span>
&#125;</pre></div><p class="paragraph"/><blockquote class="note">
Since binary plugins are packaged as JAR files, they are declared as dependencies in the <code>dependencies</code> block, <em class="italic">not</em> in the <code>plugins</code> block as you may be naturally inclined to do. The <code>plugins</code> block is used for declaring traditional source plugins packaged as zip files
</blockquote>
<a name="13. Web Services"><!-- Legacy link --></a>
<h1 id="webServices">13 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="13.1 REST"><!-- Legacy link --></a>
<h2 id="REST">13.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, PUT for creating data, POST for updating and so on. In this sense REST fits quite well with <a href="../guide/single.html#scaffolding" class="guide">CRUD</a>.<p class="paragraph"/><h4>URL patterns</h4><p class="paragraph"/>The first step to implementing REST with Grails is to provide RESTful <a href="../guide/single.html#urlmappings" class="guide">URL mappings</a>:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">static</span> mappings = &#123;
<span class="java&#45;quote">"/product/$id?"</span>(resource:<span class="java&#45;quote">"product"</span>)
&#125;</pre></div><p class="paragraph"/>This maps the URI <code>/product</code> onto a <code>ProductController</code>. Each HTTP method such as GET, PUT, POST and DELETE map to unique actions within the controller as outlined by the table below:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Method</th><th>Action</th></tr><tr class="table-odd"><td><code>GET</code></td><td><code>show</code></td></tr><tr class="table-even"><td><code>PUT</code></td><td><code>update</code></td></tr><tr class="table-odd"><td><code>POST</code></td><td><code>save</code></td></tr><tr class="table-even"><td><code>DELETE</code></td><td><code>delete</code></td></tr></table><p class="paragraph"/>In addition, Grails provides automatic XML or JSON marshalling for you.<p class="paragraph"/>You can alter how HTTP methods are handled by using URL Mappings to <a href="../guide/single.html#mappingHTTP" class="guide">map to HTTP methods</a>:<p class="paragraph"/><div class="code"><pre><span class="java&#45;quote">"/product/$id"</span>(controller: <span class="java&#45;quote">"product"</span>) &#123;
action = &#91;GET: <span class="java&#45;quote">"show"</span>, PUT: <span class="java&#45;quote">"update"</span>, DELETE: <span class="java&#45;quote">"delete"</span>, POST: <span class="java&#45;quote">"save"</span>&#93;
&#125;</pre></div><p class="paragraph"/>However, unlike the <code>resource</code> argument used previously, in this case Grails will not provide automatic XML or JSON marshalling unless you specify the <code>parseRequest</code> argument:<p class="paragraph"/><div class="code"><pre><span class="java&#45;quote">"/product/$id"</span>(controller: <span class="java&#45;quote">"product"</span>, parseRequest: <span class="java&#45;keyword">true</span>) &#123;
action = &#91;GET: <span class="java&#45;quote">"show"</span>, PUT: <span class="java&#45;quote">"update"</span>, DELETE: <span class="java&#45;quote">"delete"</span>, POST: <span class="java&#45;quote">"save"</span>&#93;
&#125;</pre></div><p class="paragraph"/><h4>HTTP Methods</h4><p class="paragraph"/>In the previous section you saw how you can easily define URL mappings that map specific HTTP methods onto specific controller actions. Writing a REST client that then sends a specific HTTP method is then easy (example in Groovy's HTTPBuilder module):<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> groovyx.net.http.&#42;
<span class="java&#45;keyword">import</span> <span class="java&#45;keyword">static</span> groovyx.net.http.ContentType.JSON<p class="paragraph"/>def http = <span class="java&#45;keyword">new</span> HTTPBuilder(<span class="java&#45;quote">"http://localhost:8080/amazon"</span>)<p class="paragraph"/> http.request(Method.GET, JSON) &#123;
url.path = '/book/list'
response.success = &#123; resp, json &#45;&#62;
<span class="java&#45;keyword">for</span> (book in json.books) &#123;
println book.title
&#125;
&#125;
&#125;</pre></div><p class="paragraph"/>Issuing a request with a method other than <code>GET</code> or <code>POST</code> from a regular browser is not possible without some help from Grails. When defining a <a href="../ref/Tags/form.html" class="tags">form</a> you can specify an alternative method such as <code>DELETE</code>:<p class="paragraph"/><div class="code"><pre>&#60;g:form controller=<span class="java&#45;quote">"book"</span> method=<span class="java&#45;quote">"DELETE"</span>&#62;
..
&#60;/g:form&#62;</pre></div><p class="paragraph"/>Grails will send a hidden parameter called <code>_method</code>, which will be used as the request's HTTP method. Another alternative for changing the method for non-browser clients is to use the <code>X-HTTP-Method-Override</code> to specify the alternative method name.<p class="paragraph"/><h4>XML Marshalling - Reading</h4><p class="paragraph"/>The controller can use Grails' <a href="../guide/single.html#xmlAndJSON" class="guide">XML marshalling</a> support to implement the GET method:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> grails.converters.XML<p class="paragraph"/>class ProductController &#123;
def show() &#123;
<span class="java&#45;keyword">if</span> (params.id &#38;&#38; Product.exists(params.id)) &#123;
def p = Product.findByName(params.id)
render p as XML
&#125;
<span class="java&#45;keyword">else</span> &#123;
def all = Product.list()
render all as XML
&#125;
&#125;
..
&#125;</pre></div><p class="paragraph"/>If there is an <code>id</code> we search for the <code>Product</code> by name and return it, otherwise we return all Products. This way if we go to <code>/products</code> we get all products, otherwise if we go to <code>/product/MacBook</code> we only get a MacBook.<p class="paragraph"/><h4>XML Marshalling - Updating</h4><p class="paragraph"/>To support updates such as <code>PUT</code> and <code>POST</code> you can use the <a href="../ref/Controllers/params.html" class="controllers">params</a> object which Grails enhances with the ability to read an incoming XML packet. Given an incoming XML packet of:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;?xml version=<span class="xml&#45;quote">"1.0"</span> encoding=<span class="xml&#45;quote">"ISO&#45;8859&#45;1"</span>?&#62;</span>
<span class="xml&#45;tag">&#60;product&#62;</span>
<span class="xml&#45;tag">&#60;name&#62;</span>MacBook<span class="xml&#45;tag">&#60;/name&#62;</span>
<span class="xml&#45;tag">&#60;vendor id=<span class="xml&#45;quote">"12"</span>&#62;</span>
<span class="xml&#45;tag">&#60;name&#62;</span>Apple<span class="xml&#45;tag">&#60;/name&#62;</span>
<span class="xml&#45;tag">&#60;/vender&#62;</span>
<span class="xml&#45;tag">&#60;/product&#62;</span></pre></div><p class="paragraph"/>you can read this XML packet using the same techniques described in the <a href="../guide/single.html#dataBinding" class="guide">Data Binding</a> section, using the <a href="../ref/Controllers/params.html" class="controllers">params</a> object:<p class="paragraph"/><div class="code"><pre>def save() &#123;
def p = <span class="java&#45;keyword">new</span> Product(params.product)<p class="paragraph"/> <span class="java&#45;keyword">if</span> (p.save()) &#123;
render p as XML
&#125;
<span class="java&#45;keyword">else</span> &#123;
render p.errors
&#125;
&#125;</pre></div><p class="paragraph"/>In this example by indexing into the <code>params</code> object using the <code>product</code> key we can automatically create and bind the XML using the <code>Product</code> constructor. An interesting aspect of the line:<p class="paragraph"/><div class="code"><pre>def p = <span class="java&#45;keyword">new</span> Product(params.product)</pre></div><p class="paragraph"/>is that it requires no code changes to deal with a form submission that submits form data, or an XML request, or a JSON request.<p class="paragraph"/><blockquote class="note">
If you require different responses to different clients (REST, HTML etc.) you can use <a href="../guide/single.html#contentNegotiation" class="guide">content negotation</a>
</blockquote><p class="paragraph"/>The <code>Product</code> object is then saved and rendered as XML, otherwise an error message is produced using Grails' <a href="../guide/single.html#validation" class="guide">validation</a> capabilities in the form:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;error&#62;</span>
<span class="xml&#45;tag">&#60;message&#62;</span>The property 'title' of class 'Person' must be specified<span class="xml&#45;tag">&#60;/message&#62;</span>
<span class="xml&#45;tag">&#60;/error&#62;</span></pre></div><p class="paragraph"/><h4>REST with JAX-RS</h4><p class="paragraph"/>There also is a <a href="http://grails.org/plugin/jaxrs" target="blank">JAX-RS Plugin</a> which can be used to build web services based on the Java API for RESTful Web Services (<a href="http://jcp.org/en/jsr/summary?id=311" target="blank">JSR 311: JAX-RS</a>).
<a name="13.2 SOAP"><!-- Legacy link --></a>
<h2 id="SOAP">13.2 SOAP</h2>
There are several plugins that add SOAP support to Grails depending on your preferred approach. For Contract First SOAP services there is a <a href="http://grails.org/plugin/springws" target="blank">Spring WS</a> plugin, whilst if you want to generate a SOAP API from Grails services there are several plugins that do this including:
<ul class="star">
<li><a href="http://grails.org/plugin/cxf/" target="blank">CXF</a> plugin which uses the <a href="http://cxf.apache.org/" target="blank">CXF</a> SOAP stack</li>
<li><a href="http://grails.org/plugin/axis2" target="blank">Axis2</a> plugin which uses <a href="http://ws.apache.org/axis2/" target="blank">Axis2</a></li>
<li><a href="https://jax-ws-commons.dev.java.net/grails/" target="blank">Metro</a> plugin which uses the <a href="https://jax-ws-commons.dev.java.net/grails/" target="blank">Metro</a> framework (and can also be used for <a href="http://docs.codehaus.org/pages/viewpage.action?pageId=88342530" target="blank">Contract First</a>)</li>
</ul><p class="paragraph"/>Most of the SOAP integrations integrate with Grails <a href="../guide/single.html#services" class="guide">services</a> via the <code>exposes</code> static property. This example is taken from the CXF plugin:<p class="paragraph"/><div class="code"><pre>class BookService &#123;<p class="paragraph"/> <span class="java&#45;keyword">static</span> expose = &#91;'cxf'&#93;<p class="paragraph"/> Book&#91;&#93; getBooks() &#123;
Book.list() as Book&#91;&#93;
&#125;
&#125;</pre></div><p class="paragraph"/>The WSDL can then be accessed at the location: <code>http://127.0.0.1:8080/your_grails_app/services/book?wsdl</code><p class="paragraph"/>For more information on the CXF plugin refer to <a href="http://grails.org/plugin/cxf" target="blank">the documentation</a> on the wiki.
<a name="13.3 RSS and Atom"><!-- Legacy link --></a>
<h2 id="RSSAndAtom">13.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() &#123;
render(feedType: <span class="java&#45;quote">"rss"</span>, feedVersion: <span class="java&#45;quote">"2.0"</span>) &#123;
title = <span class="java&#45;quote">"My test feed"</span>
link = <span class="java&#45;quote">"http://your.test.server/yourController/feed"</span><p class="paragraph"/> <span class="java&#45;keyword">for</span> (article in Article.list()) &#123;
entry(article.title) &#123;
link = <span class="java&#45;quote">"http://your.test.server/article/&#36;&#123;article.id&#125;"</span>
article.content // <span class="java&#45;keyword">return</span> the content
&#125;
&#125;
&#125;
&#125;</pre></div>
<a name="14. Grails and Spring"><!-- Legacy link --></a>
<h1 id="spring">14 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="14.1 The Underpinnings of Grails"><!-- Legacy link --></a>
<h2 id="theUnderpinningsOfGrails">14.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://static.springsource.org/spring/docs/3.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://static.springsource.org/spring/docs/3.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="../api/org/codehaus/groovy/grails/commons/GrailsApplication.html" class="api">GrailsApplication</a> instance and the <a href="../api/org/codehaus/groovy/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="14.2 Configuring Additional Beans"><!-- Legacy link --></a>
<h2 id="springdslAdditional">14.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 = &#123;
// beans here
&#125;</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&#45;keyword">import</span> my.company.MyBeanImpl<p class="paragraph"/>beans = &#123;
myBean(MyBeanImpl) &#123;
someProperty = 42
otherProperty = <span class="java&#45;quote">"blue"</span>
&#125;
&#125;</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 &#123;<p class="paragraph"/> def myBean
&#8230;
&#125;</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&#45;keyword">import</span> grails.util.Environment
<span class="java&#45;keyword">import</span> my.company.mock.MockImpl
<span class="java&#45;keyword">import</span> my.company.MyBeanImpl<p class="paragraph"/>beans = &#123;
<span class="java&#45;keyword">switch</span>(Environment.current) &#123;
<span class="java&#45;keyword">case</span> Environment.PRODUCTION:
myBean(MyBeanImpl) &#123;
someProperty = 42
otherProperty = <span class="java&#45;quote">"blue"</span>
&#125;
<span class="java&#45;keyword">break</span><p class="paragraph"/> <span class="java&#45;keyword">case</span> Environment.DEVELOPMENT:
myBean(MockImpl) &#123;
someProperty = 42
otherProperty = <span class="java&#45;quote">"blue"</span>
&#125;
<span class="java&#45;keyword">break</span>
&#125;
&#125;</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&#45;keyword">import</span> grails.util.Environment
<span class="java&#45;keyword">import</span> my.company.mock.MockImpl
<span class="java&#45;keyword">import</span> my.company.MyBeanImpl<p class="paragraph"/>beans = &#123;
<span class="java&#45;keyword">if</span> (application.config.my.company.mockService) &#123;
myBean(MockImpl) &#123;
someProperty = 42
otherProperty = <span class="java&#45;quote">"blue"</span>
&#125;
&#125; <span class="java&#45;keyword">else</span> &#123;
myBean(MyBeanImpl) &#123;
someProperty = 42
otherProperty = <span class="java&#45;quote">"blue"</span>
&#125;
&#125;
&#125;</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&#45;tag">&#60;bean id=<span class="xml&#45;quote">"myBean"</span> class=<span class="xml&#45;quote">"my.company.MyBeanImpl"</span>&#62;</span>
<span class="xml&#45;tag">&#60;property name=<span class="xml&#45;quote">"someProperty"</span> value=<span class="xml&#45;quote">"42"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;property name=<span class="xml&#45;quote">"otherProperty"</span> value=<span class="xml&#45;quote">"blue"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;/bean&#62;</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 &#123;<p class="paragraph"/> def myBean
&#125;</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 = &#123;
myBean(MyBeanImpl) &#123;
someProperty = 42
otherProperty = <span class="java&#45;quote">"blue"</span>
bookService = ref(<span class="java&#45;quote">"bookService"</span>)
&#125;
&#125;</pre></div><p class="paragraph"/>or like this in XML:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;bean id=<span class="xml&#45;quote">"myBean"</span> class=<span class="xml&#45;quote">"my.company.MyBeanImpl"</span>&#62;</span>
<span class="xml&#45;tag">&#60;property name=<span class="xml&#45;quote">"someProperty"</span> value=<span class="xml&#45;quote">"42"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;property name=<span class="xml&#45;quote">"otherProperty"</span> value=<span class="xml&#45;quote">"blue"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;property name=<span class="xml&#45;quote">"bookService"</span> ref=<span class="xml&#45;quote">"bookService"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;/bean&#62;</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&#45;keyword">package</span> my.company<p class="paragraph"/>class MyBeanImpl &#123;
<span class="java&#45;object">Integer</span> someProperty
<span class="java&#45;object">String</span> otherProperty
BookService bookService // or just <span class="java&#45;quote">"def bookService"</span>
&#125;</pre></div><p class="paragraph"/>or in Java like this:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">package</span> my.company;<p class="paragraph"/>class MyBeanImpl &#123;<p class="paragraph"/> <span class="java&#45;keyword">private</span> BookService bookService;
<span class="java&#45;keyword">private</span> <span class="java&#45;object">Integer</span> someProperty;
<span class="java&#45;keyword">private</span> <span class="java&#45;object">String</span> otherProperty;<p class="paragraph"/> <span class="java&#45;keyword">public</span> void setBookService(BookService theBookService) &#123;
<span class="java&#45;keyword">this</span>.bookService = theBookService;
&#125;<p class="paragraph"/> <span class="java&#45;keyword">public</span> void setSomeProperty(<span class="java&#45;object">Integer</span> someProperty) &#123;
<span class="java&#45;keyword">this</span>.someProperty = someProperty;
&#125;<p class="paragraph"/> <span class="java&#45;keyword">public</span> void setOtherProperty(<span class="java&#45;object">String</span> otherProperty) &#123;
<span class="java&#45;keyword">this</span>.otherProperty = otherProperty;
&#125;
&#125;</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="14.3 Runtime Spring with the Beans DSL"><!-- Legacy link --></a>
<h2 id="springdsl">14.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="../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="../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&#45;keyword">import</span> org.apache.commons.dbcp.BasicDataSource
<span class="java&#45;keyword">import</span> org.codehaus.groovy.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean
<span class="java&#45;keyword">import</span> org.springframework.context.ApplicationContext
<span class="java&#45;keyword">import</span> grails.spring.BeanBuilder<p class="paragraph"/>def bb = <span class="java&#45;keyword">new</span> BeanBuilder()<p class="paragraph"/>bb.beans &#123;<p class="paragraph"/> dataSource(BasicDataSource) &#123;
driverClassName = <span class="java&#45;quote">"org.h2.Driver"</span>
url = <span class="java&#45;quote">"jdbc:h2:mem:grailsDB"</span>
username = <span class="java&#45;quote">"sa"</span>
password = <span class="java&#45;quote">""</span>
&#125;<p class="paragraph"/> sessionFactory(ConfigurableLocalSessionFactoryBean) &#123;
dataSource = ref('dataSource')
hibernateProperties = &#91;<span class="java&#45;quote">"hibernate.hbm2ddl.auto"</span>: <span class="java&#45;quote">"create&#45;drop"</span>,
<span class="java&#45;quote">"hibernate.show_sql"</span>: <span class="java&#45;quote">"<span class="java&#45;keyword">true</span>"</span>&#93;
&#125;
&#125;<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) &#123; bean &#45;&#62;
// Autowiring behaviour. The other option is 'byType'. &#91;autowire&#93;
bean.autowire = 'byName'
// Sets the initialisation method to 'init'. &#91;init&#45;method&#93;
bean.initMethod = 'init'
// Sets the destruction method to 'destroy'. &#91;destroy&#45;method&#93;
bean.destroyMethod = 'destroy'
// Sets the scope of the bean. &#91;scope&#93;
bean.scope = 'request'
dataSource = ref('dataSource')
hibernateProperties = &#91;<span class="java&#45;quote">"hibernate.hbm2ddl.auto"</span>: <span class="java&#45;quote">"create&#45;drop"</span>,
<span class="java&#45;quote">"hibernate.show_sql"</span>: <span class="java&#45;quote">"<span class="java&#45;keyword">true</span>"</span>&#93;
&#125;</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-&#60;version&#62;.jar</code> file in your classpath to use BeanBuilder in a regular Spring MVC application. Then add the following <code>&#60;context-param&#62;</code> values to your <code>/WEB-INF/web.xml</code> file:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;context&#45;param&#62;</span>
<span class="xml&#45;tag">&#60;param&#45;name&#62;</span>contextConfigLocation<span class="xml&#45;tag">&#60;/param&#45;name&#62;</span>
<span class="xml&#45;tag">&#60;param&#45;value&#62;</span>/WEB&#45;INF/applicationContext.groovy<span class="xml&#45;tag">&#60;/param&#45;value&#62;</span>
<span class="xml&#45;tag">&#60;/context&#45;param&#62;</span><p class="paragraph"/><span class="xml&#45;tag">&#60;context&#45;param&#62;</span>
<span class="xml&#45;tag">&#60;param&#45;name&#62;</span>contextClass<span class="xml&#45;tag">&#60;/param&#45;name&#62;</span>
<span class="xml&#45;tag">&#60;param&#45;value&#62;</span>
org.codehaus.groovy.grails.commons.spring.GrailsWebApplicationContext
<span class="xml&#45;tag">&#60;/param&#45;value&#62;</span>
<span class="xml&#45;tag">&#60;/context&#45;param&#62;</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&#45;keyword">import</span> org.apache.commons.dbcp.BasicDataSource<p class="paragraph"/>beans &#123;
dataSource(BasicDataSource) &#123;
driverClassName = <span class="java&#45;quote">"org.h2.Driver"</span>
url = <span class="java&#45;quote">"jdbc:h2:mem:grailsDB"</span>
username = <span class="java&#45;quote">"sa"</span>
password = <span class="java&#45;quote">""</span>
&#125;
&#125;</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&#45;keyword">new</span> BeanBuilder()
bb.loadBeans(<span class="java&#45;quote">"classpath:&#42;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&#45;keyword">import</span> org.apache.commons.dbcp.BasicDataSource
<span class="java&#45;keyword">import</span> org.codehaus.groovy.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean<p class="paragraph"/>beans &#123;<p class="paragraph"/> dataSource(BasicDataSource) &#123;
driverClassName = <span class="java&#45;quote">"org.h2.Driver"</span>
url = <span class="java&#45;quote">"jdbc:h2:mem:grailsDB"</span>
username = <span class="java&#45;quote">"sa"</span>
password = <span class="java&#45;quote">""</span>
&#125;<p class="paragraph"/> sessionFactory(ConfigurableLocalSessionFactoryBean) &#123;
dataSource = dataSource
hibernateProperties = &#91;<span class="java&#45;quote">"hibernate.hbm2ddl.auto"</span>: <span class="java&#45;quote">"create&#45;drop"</span>,
<span class="java&#45;quote">"hibernate.show_sql"</span>: <span class="java&#45;quote">"<span class="java&#45;keyword">true</span>"</span>&#93;
&#125;
&#125;</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&#45;keyword">new</span> Binding()
binding.maxSize = 10000
binding.productGroup = 'finance'<p class="paragraph"/>def bb = <span class="java&#45;keyword">new</span> BeanBuilder()
bb.binding = binding
bb.loadBeans(<span class="java&#45;quote">"classpath:&#42;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="14.4 The BeanBuilder DSL Explained"><!-- Legacy link --></a>
<h2 id="theBeanBuilderDSLExplained">14.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 &#123;
exampleBean(MyExampleBean, <span class="java&#45;quote">"firstArgument"</span>, 2) &#123;
someProperty = &#91;1, 2, 3&#93;
&#125;
&#125;</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&#45;object">String</span> foo, <span class="java&#45;object">int</span> bar) &#123;
&#8230;
&#125;</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://static.springsource.org/spring/docs/3.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 &#123;
exampleBean(MyExampleBean) &#123; bean &#45;&#62;
bean.factoryMethod = <span class="java&#45;quote">"getInstance"</span>
bean.singleton = <span class="java&#45;keyword">false</span>
someProperty = &#91;1, 2, 3&#93;
&#125;
&#125;</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 &#123;
def example = exampleBean(MyExampleBean) &#123;
someProperty = &#91;1, 2, 3&#93;
&#125;
example.factoryMethod = <span class="java&#45;quote">"getInstance"</span>
&#125;</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 &#123;<p class="paragraph"/> myFactory(ExampleFactoryBean) &#123;
someProperty = &#91;1, 2, 3&#93;
&#125;<p class="paragraph"/> myBean(myFactory) &#123;
name = <span class="java&#45;quote">"blah"</span>
&#125;
&#125;</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 &#123;<p class="paragraph"/> myFactory(ExampleFactoryBean) &#123;
someProperty = &#91;1, 2, 3&#93;
&#125;<p class="paragraph"/> myBean(myFactory: <span class="java&#45;quote">"getInstance"</span>) &#123;
name = <span class="java&#45;quote">"blah"</span>
&#125;
&#125;</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&#45;quote">"example"</span>
bb.beans &#123;
<span class="java&#45;quote">"$&#123;beanName&#125;Bean"</span>(MyExampleBean) &#123;
someProperty = &#91;1, 2, 3&#93;
&#125;
&#125;</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&#45;quote">"example"</span>
bb.beans &#123;<p class="paragraph"/> <span class="java&#45;quote">"$&#123;beanName&#125;Bean"</span>(MyExampleBean) &#123;
someProperty = &#91;1, 2, 3&#93;
&#125;<p class="paragraph"/> anotherBean(AnotherBean) &#123;
example = ref(<span class="java&#45;quote">"$&#123;beanName&#125;Bean"</span>)
&#125;
&#125;</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 = ...//
der bb = <span class="java&#45;keyword">new</span> BeanBuilder(parent)
bb.beans &#123;
anotherBean(AnotherBean) &#123;
example = ref(<span class="java&#45;quote">"$&#123;beanName&#125;Bean"</span>, <span class="java&#45;keyword">true</span>)
&#125;
&#125;</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 &#123;<p class="paragraph"/> marge(Person) &#123;
name = <span class="java&#45;quote">"Marge"</span>
husband = &#123; Person p &#45;&#62;
name = <span class="java&#45;quote">"Homer"</span>
age = 45
props = &#91;overweight: <span class="java&#45;keyword">true</span>, height: <span class="java&#45;quote">"1.8m"</span>&#93;
&#125;
children = &#91;bart, lisa&#93;
&#125;<p class="paragraph"/> bart(Person) &#123;
name = <span class="java&#45;quote">"Bart"</span>
age = 11
&#125;<p class="paragraph"/> lisa(Person) &#123;
name = <span class="java&#45;quote">"Lisa"</span>
age = 9
&#125;
&#125;</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 &#123;<p class="paragraph"/> personFactory(PersonFactory)<p class="paragraph"/> marge(Person) &#123;
name = <span class="java&#45;quote">"Marge"</span>
husband = &#123; bean &#45;&#62;
bean.factoryBean = <span class="java&#45;quote">"personFactory"</span>
bean.factoryMethod = <span class="java&#45;quote">"newInstance"</span>
name = <span class="java&#45;quote">"Homer"</span>
age = 45
props = &#91;overweight: <span class="java&#45;keyword">true</span>, height: <span class="java&#45;quote">"1.8m"</span>&#93;
&#125;
children = &#91;bart, lisa&#93;
&#125;
&#125;</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 &#123;
def start() &#123; println <span class="java&#45;quote">"lets begin"</span> &#125;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class KnightOfTheRoundTable &#123;<p class="paragraph"/> <span class="java&#45;object">String</span> name
<span class="java&#45;object">String</span> leader
HolyGrailQuest quest<p class="paragraph"/> KnightOfTheRoundTable(<span class="java&#45;object">String</span> name) &#123;
<span class="java&#45;keyword">this</span>.name = name
&#125;<p class="paragraph"/> def embarkOnQuest() &#123;
quest.start()
&#125;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> grails.spring.BeanBuilder<p class="paragraph"/>def bb = <span class="java&#45;keyword">new</span> BeanBuilder()
bb.beans &#123;
abstractBean &#123;
leader = <span class="java&#45;quote">"Lancelot"</span>
&#125;
&#8230;
&#125;</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 &#123;
&#8230;
quest(HolyGrailQuest)<p class="paragraph"/> knights(KnightOfTheRoundTable, <span class="java&#45;quote">"Camelot"</span>) &#123; bean &#45;&#62;
bean.parent = abstractBean
quest = ref('quest')
&#125;
&#125;</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&#45;keyword">import</span> grails.spring.BeanBuilder<p class="paragraph"/>def bb = <span class="java&#45;keyword">new</span> BeanBuilder()
bb.beans &#123;<p class="paragraph"/> abstractBean(KnightOfTheRoundTable) &#123; bean &#45;&#62;
bean.'<span class="java&#45;keyword">abstract</span>' = <span class="java&#45;keyword">true</span>
leader = <span class="java&#45;quote">"Lancelot"</span>
&#125;<p class="paragraph"/> quest(HolyGrailQuest)<p class="paragraph"/> knights(<span class="java&#45;quote">"Camelot"</span>) &#123; bean &#45;&#62;
bean.parent = abstractBean
quest = quest
&#125;
&#125;</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&#45;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&#45;scan'('base&#45;<span class="java&#45;keyword">package</span>': <span class="java&#45;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&#45;quote">"http://www.springframework.org/schema/jee"</span><p class="paragraph"/>jee.'jndi&#45;lookup'(id: <span class="java&#45;quote">"dataSource"</span>, 'jndi&#45;name': <span class="java&#45;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 &#123;<p class="paragraph"/> <span class="java&#45;object">int</span> age
<span class="java&#45;object">String</span> name<p class="paragraph"/> void birthday() &#123;
++age;
&#125;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class BirthdayCardSender &#123;<p class="paragraph"/> List peopleSentCards = &#91;&#93;<p class="paragraph"/> void onBirthday(Person person) &#123;
peopleSentCards &#60;&#60; person
&#125;
&#125;</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&#45;quote">"http://www.springframework.org/schema/aop"</span><p class="paragraph"/>fred(Person) &#123;
name = <span class="java&#45;quote">"Fred"</span>
age = 45
&#125;<p class="paragraph"/>birthdayCardSenderAspect(BirthdayCardSender)<p class="paragraph"/>aop &#123;
config(<span class="java&#45;quote">"proxy&#45;target&#45;class"</span>: <span class="java&#45;keyword">true</span>) &#123;
aspect(id: <span class="java&#45;quote">"sendBirthdayCard"</span>, ref: <span class="java&#45;quote">"birthdayCardSenderAspect"</span>) &#123;
after method: <span class="java&#45;quote">"onBirthday"</span>,
pointcut: <span class="java&#45;quote">"execution(void ..Person.birthday()) and <span class="java&#45;keyword">this</span>(person)"</span>
&#125;
&#125;
&#125;</pre></div>
<a name="14.5 Property Placeholder Configuration"><!-- Legacy link --></a>
<h2 id="propertyPlaceholderConfiguration">14.5 Property Placeholder Configuration</h2>
Grails supports the notion of property placeholder configuration through an extended version of Spring's <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html" class="api">PropertyPlaceholderConfigurer</a>, which is typically useful in combination with <a href="../guide/single.html#configExternalized" class="guide">externalized configuration</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>. 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&#45;quote">"com.mysql.jdbc.Driver"</span>
database.dbname=<span class="java&#45;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&#45;tag">&#60;bean id=<span class="xml&#45;quote">"dataSource"</span>
class=<span class="xml&#45;quote">"org.springframework.jdbc.datasource.DriverManagerDataSource"</span>&#62;</span>
<span class="xml&#45;tag">&#60;property name=<span class="xml&#45;quote">"driverClassName"</span>&#62;</span>
<span class="xml&#45;tag">&#60;value&#62;</span>$&#123;database.driver&#125;<span class="xml&#45;tag">&#60;/value&#62;</span>
<span class="xml&#45;tag">&#60;/property&#62;</span>
<span class="xml&#45;tag">&#60;property name=<span class="xml&#45;quote">"url"</span>&#62;</span>
<span class="xml&#45;tag">&#60;value&#62;</span>jdbc:$&#123;database.dbname&#125;<span class="xml&#45;tag">&#60;/value&#62;</span>
<span class="xml&#45;tag">&#60;/property&#62;</span>
<span class="xml&#45;tag">&#60;/bean&#62;</span></pre></div>
<a name="14.6 Property Override Configuration"><!-- Legacy link --></a>
<h2 id="propertyOverrideConfiguration">14.6 Property Override Configuration</h2>
Grails supports setting of bean properties via <a href="../guide/single.html#conf" class="guide">configuration</a>. This is often useful when used in combination with <a href="../guide/single.html#configExternalized" class="guide">externalized 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 &#123;
bookService &#123;
webServiceURL = <span class="java&#45;quote">"http://www.amazon.com"</span>
&#125;
&#125;</pre></div><p class="paragraph"/>The general format is:<p class="paragraph"/><div class="code"><pre>&#91;bean name&#93;.&#91;property name&#93; = &#91;value&#93;</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="15. Grails and Hibernate"><!-- Legacy link --></a>
<h1 id="hibernate">15 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="15.1 Using Hibernate XML Mapping Files"><!-- Legacy link --></a>
<h2 id="usingHibernateXMLMappingFiles">15.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 <a href="../ref/Command Line/create-hibernate-cfg-xml.html" class="commandLine">create-hibernate-cfg-xml</a> command, that contains the following:<p class="paragraph"/><div class="code"><pre><span class="xml&#45;tag">&#60;?xml version='1.0' encoding='UTF&#45;8'?&#62;</span>
&#60;!DOCTYPE hibernate&#45;configuration PUBLIC
<span class="xml&#45;quote">"&#45;//Hibernate/Hibernate Configuration DTD 3.0//EN"</span>
<span class="xml&#45;quote">"http://hibernate.sourceforge.net/hibernate&#45;configuration&#45;3.0.dtd"</span>&#62;
<span class="xml&#45;tag">&#60;hibernate&#45;configuration&#62;</span>
<span class="xml&#45;tag">&#60;session&#45;factory&#62;</span>
<span class="xml&#45;comment">&#60;!&#45;&#45; Example mapping file inclusion &#45;&#45;&#62;</span>
<span class="xml&#45;tag">&#60;mapping resource=<span class="xml&#45;quote">"org.example.Book.hbm.xml"</span>/&#62;</span>
&#8230;
<span class="xml&#45;tag">&#60;/session&#45;factory&#62;</span>
<span class="xml&#45;tag">&#60;/hibernate&#45;configuration&#62;</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 &#123;
config.location = <span class="java&#45;quote">"file:/path/to/my/hibernate.cfg.xml"</span>
&#125;</pre></div><p class="paragraph"/>or even a list of locations:<p class="paragraph"/><div class="code"><pre>hibernate &#123;
config.location = &#91;<span class="java&#45;quote">"file:/path/to/one/hibernate.cfg.xml"</span>,
<span class="java&#45;quote">"file:/path/to/two/hibernate.cfg.xml"</span>&#93;
&#125;</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="15.2 Mapping with Hibernate Annotations"><!-- Legacy link --></a>
<h2 id="mappingWithHibernateAnnotations">15.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&#45;keyword">package</span> com.books;<p class="paragraph"/><span class="java&#45;keyword">import</span> javax.persistence.Entity;
<span class="java&#45;keyword">import</span> javax.persistence.GeneratedValue;
<span class="java&#45;keyword">import</span> javax.persistence.Id;<p class="paragraph"/>@Entity
<span class="java&#45;keyword">public</span> class Book &#123;
<span class="java&#45;keyword">private</span> <span class="java&#45;object">Long</span> id;
<span class="java&#45;keyword">private</span> <span class="java&#45;object">String</span> title;
<span class="java&#45;keyword">private</span> <span class="java&#45;object">String</span> description;
<span class="java&#45;keyword">private</span> Date date;<p class="paragraph"/> @Id
@GeneratedValue
<span class="java&#45;keyword">public</span> <span class="java&#45;object">Long</span> getId() &#123;
<span class="java&#45;keyword">return</span> id;
&#125;<p class="paragraph"/> <span class="java&#45;keyword">public</span> void setId(<span class="java&#45;object">Long</span> id) &#123;
<span class="java&#45;keyword">this</span>.id = id;
&#125;<p class="paragraph"/> <span class="java&#45;keyword">public</span> <span class="java&#45;object">String</span> getTitle() &#123;
<span class="java&#45;keyword">return</span> title;
&#125;<p class="paragraph"/> <span class="java&#45;keyword">public</span> void setTitle(<span class="java&#45;object">String</span> title) &#123;
<span class="java&#45;keyword">this</span>.title = title;
&#125;<p class="paragraph"/> <span class="java&#45;keyword">public</span> <span class="java&#45;object">String</span> getDescription() &#123;
<span class="java&#45;keyword">return</span> description;
&#125;<p class="paragraph"/> <span class="java&#45;keyword">public</span> void setDescription(<span class="java&#45;object">String</span> description) &#123;
<span class="java&#45;keyword">this</span>.description = description;
&#125;
&#125;</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>&#60;!DOCTYPE hibernate&#45;configuration SYSTEM
<span class="xml&#45;quote">"http://hibernate.sourceforge.net/hibernate&#45;configuration&#45;3.0.dtd"</span>&#62;
<span class="xml&#45;tag">&#60;hibernate&#45;configuration&#62;</span>
<span class="xml&#45;tag">&#60;session&#45;factory&#62;</span>
<span class="xml&#45;tag">&#60;mapping package=<span class="xml&#45;quote">"com.books"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;mapping class=<span class="xml&#45;quote">"com.books.Book"</span> /&#62;</span>
<span class="xml&#45;tag">&#60;/session&#45;factory&#62;</span>
<span class="xml&#45;tag">&#60;/hibernate&#45;configuration&#62;</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="15.3 Adding Constraints"><!-- Legacy link --></a>
<h2 id="addingConstraints">15.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>&#46;<p class="paragraph"/>Add a standard GORM <code>constraints</code> block to the script:
<div class="code"><pre>constraints = &#123;
title blank: <span class="java&#45;keyword">false</span>
author blank: <span class="java&#45;keyword">false</span>
&#125;</pre></div><p class="paragraph"/>Once this is in place you can validate instances of your domain class!
<a name="16. Scaffolding"><!-- Legacy link --></a>
<h1 id="scaffolding">16 Scaffolding</h1>
Scaffolding lets you auto-generate a whole application for a given 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"/><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 &#123;
<span class="java&#45;keyword">static</span> scaffold = <span class="java&#45;keyword">true</span>
&#125;</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 &#123;
<span class="java&#45;keyword">static</span> scaffold = Author
&#125;</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>list</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 &#123;<p class="paragraph"/> <span class="java&#45;keyword">static</span> scaffold = Book<p class="paragraph"/> def changeAuthor() &#123;
def b = Book.get(params.id)
b.author = Author.get(params&#91;<span class="java&#45;quote">"author.id"</span>&#93;)
b.save()<p class="paragraph"/> // redirect to a scaffolded action
redirect(action:show)
&#125;
&#125;</pre></div><p class="paragraph"/>You can also override the scaffolded actions:<p class="paragraph"/><div class="code"><pre>class BookController &#123;<p class="paragraph"/> <span class="java&#45;keyword">static</span> scaffold = Book<p class="paragraph"/> // overrides scaffolded action to <span class="java&#45;keyword">return</span> both authors and books
def list() &#123;
&#91;bookInstanceList: Book.list(),
bookInstanceTotal: Book.count(),
authorInstanceList: Author.list()&#93;
&#125;<p class="paragraph"/> def show() &#123;
def book = Book.get(params.id)
log.error(book)
&#91;bookInstance : book&#93;
&#125;
&#125;</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>&#60;propertyName&#62;InstanceList</code> for collections and <code>&#60;propertyName&#62;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 = &#123;
title()
releaseDate()
&#125;</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 = &#123;
title()
category(inList: &#91;<span class="java&#45;quote">"Fiction"</span>, <span class="java&#45;quote">"Non&#45;fiction"</span>, <span class="java&#45;quote">"Biography"</span>&#93;)
releaseDate()
&#125;</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 = &#123;
age(range:18..65)
&#125;</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 = &#123;
name(size:0..30)
&#125;</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&#45;controller Book</pre></div><p class="paragraph"/>or to generate the views:<p class="paragraph"/><div class="code"><pre>grails generate&#45;views Book</pre></div><p class="paragraph"/>or to generate everything:<p class="paragraph"/><div class="code"><pre>grails generate&#45;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&#45;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 <a href="../ref/Command Line/install-templates.html" class="commandLine">install-templates</a> command.
<a name="17. Deployment"><!-- Legacy link --></a>
<h1 id="deployment">17 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&#45;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&#45;quote">"foobar&#45;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 = &#91;
<span class="java&#45;quote">"hibernate3.jar"</span>,
<span class="java&#45;quote">"groovy&#45;all&#45;&#42;.jar"</span>,
<span class="java&#45;quote">"standard&#45;&#36;&#123;servletVersion&#125;.jar"</span>,
<span class="java&#45;quote">"jstl&#45;&#36;&#123;servletVersion&#125;.jar"</span>,
<span class="java&#45;quote">"oscache&#45;&#42;.jar"</span>,
<span class="java&#45;quote">"commons&#45;logging&#45;&#42;.jar"</span>,
<span class="java&#45;quote">"sitemesh&#45;&#42;.jar"</span>,
<span class="java&#45;quote">"spring&#45;&#42;.jar"</span>,
<span class="java&#45;quote">"log4j&#45;&#42;.jar"</span>,
<span class="java&#45;quote">"ognl&#45;&#42;.jar"</span>,
<span class="java&#45;quote">"commons&#45;&#42;.jar"</span>,
<span class="java&#45;quote">"xstream&#45;1.2.1.jar"</span>,
<span class="java&#45;quote">"xpp3_min&#45;1.1.3.4.O.jar"</span> &#93;<p class="paragraph"/>grails.war.dependencies = &#123;
fileset(dir: <span class="java&#45;quote">"libs"</span>) &#123;
<span class="java&#45;keyword">for</span> (pattern in deps) &#123;
include(name: pattern)
&#125;
&#125;
&#125;</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 = &#123; args &#45;&#62;
fileset(dir:<span class="java&#45;quote">"web&#45;app"</span>) &#123;
include(name: <span class="java&#45;quote">"js/&#42;&#42;"</span>)
include(name: <span class="java&#45;quote">"css/&#42;&#42;"</span>)
include(name: <span class="java&#45;quote">"WEB&#45;INF/&#42;&#42;"</span>)
&#125;
&#125;<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 = &#123; stagingDir, args &#45;&#62;
copy(file: <span class="java&#45;quote">"grails&#45;app/conf/custom&#45;web.xml"</span>,
tofile: <span class="java&#45;quote">"&#36;&#123;stagingDir&#125;/WEB&#45;INF/web.xml"</span>)
&#125;</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 an up-to-date 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">18 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">18.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&amp;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">18.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">&#34;grails&#34; GitHub user</a>. This is a simple case of cloning the repository you're interested in. For example, to getthe core framework run:<p class="paragraph"/><div class="code"><pre>git clone http://github.com/grails/grails&#45;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 case <code>MappingDslTests</code> simply execute the following command:
<div class="code"><pre>./gradlew &#45;Dtest.single=MappingDslTest :grails&#45;test&#45;suite&#45;persistence:test</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 "&#60;classpathentry kind="src" path="../scripts"/&#62;".</li>
</ul><p class="paragraph"/>Use "Import-&#62;General-&#62;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/com.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 "&#60;classpathentry kind="src" path="../scripts"/&#62;"). 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 -&#62; Team -&#62; 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-&#62;Preferences-&#62;Java-&#62;Code Style-&#62;Formatter-&#62;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&#45;debug &#60;command&#62;</pre></div><p class="paragraph"/>and then connect to the JVM remotely via the IDE ("remote debugging") using the port 5005. Of course, if you have modified the <code>grails-debug</code> script to use a different port number, connect using that one.<p class="paragraph"/>If you need to debug stuff that happens during application startup, then you should modify the "grails-debug" script and change the "suspend" option from 'n' to 'y'. You can read more about the JPDA connection settings TODO here: <a href="http://java.sun.com/j2se/1.5.0/docs/guide/jpda/conninv.html#Invocation" target="blank">http://java.sun.com/j2se/1.5.0/docs/guide/jpda/conninv.html#Invocation</a>.<p class="paragraph"/>It's also possible to get Eclipse to wait for incoming debugger connections and instead of using "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005" you could use this "-Xrunjdwp:transport=dt_socket,server=n,address=8000" (which assumes the Eclipse default port for remote java applications) Inside eclipse you create a new "Remote Java Application" launch configuration and change the connection type to "Standard (Socket Listen)" and click debug. This allows you to start a debugger session in eclipse and just leave it running and you're free to debug anything without having to keep remembering to relaunch a "Socket Attach" launch configuration. You might find it handy to have 2 scripts, one called "grails-debug", and another called "grails-debug-attach"
<h2 id="patchesCore">18.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 &#45;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">18.4 Submit Patches to Grails Documentation</h2>
Contributing to the documentation is simpler than 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&#45;quote">"&#45;Xmx512m &#45;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 &#45;Dgrails.home=/home/user/projects/grails&#45;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&#45;core</pre></div>
or
<div class="code"><pre>grails.home=../grails&#45;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 &#45;Ddisable.groovydocs=<span class="java&#45;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="https://grails.apache.org/docs/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/&#60;lang&#62;/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/&#60;lang&#62;/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/&#60;lang&#62;/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>&#123;hidden&#125;</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>&#123;hidden&#125;
When you create a Grails application with the &#91;create&#45;app|commandLine&#93; command,
Grails doesn't automatically create an Ant <code>build.xml</code> file but you can generate
one with the &#91;integrate&#45;with|commandLine&#93; command:
&#123;hidden&#125;<p class="paragraph"/>Quando crias uma aplicação Grails com o comando &#91;create&#45;app|commandLine&#93;, Grails
não cria automaticamente um ficheiro de construção Ant <code>build.xml</code> mas podes gerar
um com o comando &#91;integrate&#45;with|commandLine&#93;:</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>&#123;hidden&#125;</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>&#123;hidden&#125;</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>&#123;code&#125;</code> blocks are ignored, so you <em class="italic">don't</em> need to include them inside <code>&#123;hidden&#125;</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>&#60;lang&#62;</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 '&#60;lang&#62;.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_&#42;</code> and <code>publishPdf_&#42;</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/&#60;lang&#62;/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/add-proxy.html">add-proxy</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/bootstrap.html">bootstrap</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/clear-proxy.html">clear-proxy</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-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-filters.html">create-filters</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/create-hibernate-cfg-xml.html">create-hibernate-cfg-xml</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-plugin.html">create-plugin</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/create-scaffold-controller.html">create-scaffold-controller</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/init.html">init</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/install-dependency.html">install-dependency</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/install-plugin.html">install-plugin</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/install-templates.html">install-templates</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/integrate-with.html">integrate-with</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/interactive.html">interactive</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/list-plugin-updates.html">list-plugin-updates</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/migrate-docs.html">migrate-docs</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/refresh-dependencies.html">refresh-dependencies</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/remove-proxy.html">remove-proxy</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/run-script.html">run-script</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/run-war.html">run-war</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/set-proxy.html">set-proxy</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/set-version.html">set-version</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/uninstall-plugin.html">uninstall-plugin</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/upgrade.html">upgrade</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/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/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/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/response.html">response</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/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/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/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/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/filters.html">filters</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 class="menu-item"><a href="../ref/Plug-ins/web%20flow.html">web flow</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/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/formRemote.html">formRemote</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/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/remoteField.html">remoteField</a>
</div>
<div class="menu-item"><a href="../ref/Tags/remoteFunction.html">remoteFunction</a>
</div>
<div class="menu-item"><a href="../ref/Tags/remoteLink.html">remoteLink</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/setProvider.html">setProvider</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/submitToRemote.html">submitToRemote</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.
Sponsored by <a href="http://springsource.com">SpringSource</a>
</div>
<script type="text/javascript" src="../js/docs.js"></script>
</body>
</html>