blob: be9f8ba6ea58218423e20ebcf0b9e0518b5464bf [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 3.3.7</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">
<div class="navTitle">
The Grails Framework
</div>
<div class="navLinks">
<ul>
<li>
<div id="nav-summary" onmouseover="toggleNavSummary(false)" onmouseout="toggleNavSummary(true)">
<a href="../guide/index.html" class="button">Table of contents</a>
<div id="nav-summary-childs" style="display:none;">
<div class="toc-item" style="margin-left:0"><a href="#introduction"><strong>1</strong><span>Introduction</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#gettingStarted"><strong>2</strong><span>Getting Started</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#upgrading"><strong>3</strong><span>Upgrading from Grails 3.2.x</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#conf"><strong>4</strong><span>Configuration</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#commandLine"><strong>5</strong><span>The Command Line</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#profiles"><strong>6</strong><span>Application Profiles</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#GORM"><strong>7</strong><span>Object Relational Mapping (GORM)</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#theWebLayer"><strong>8</strong><span>The Web Layer</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#traits"><strong>9</strong><span>Traits</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#REST"><strong>10</strong><span>REST</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#async"><strong>11</strong><span>Asynchronous Programming</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#validation"><strong>12</strong><span>Validation</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#services"><strong>13</strong><span>The Service Layer</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#staticTypeCheckingAndCompilation"><strong>14</strong><span>Static Type Checking And Compilation</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#testing"><strong>15</strong><span>Testing</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#i18n"><strong>16</strong><span>Internationalization</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#security"><strong>17</strong><span>Security</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#plugins"><strong>18</strong><span>Plugins</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#spring"><strong>19</strong><span>Grails and Spring</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#scaffolding"><strong>20</strong><span>Scaffolding</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#deployment"><strong>21</strong><span>Deployment</span></a></div>
<div class="toc-item" style="margin-left:0"><a href="#contributing"><strong>22</strong><span>Contributing to Grails</span></a></div>
</div>
</div>
</li>
<li class="separator selected">
<a id="ref-button" onclick="localToggle(); return false;" href="#">Quick Reference</a>
</li>
</ul>
</div>
</div>
<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</h1>
<p><strong>Authors:</strong> The Grails Team</p>
<p><strong>Version:</strong> 3.3.7</p>
</div>
<div id="table-of-content">
<h2>Table of Contents</h2>
<div class="toc-item" style="margin-left:0px"><a href="#introduction"><strong>1</strong><span>Introduction</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#whatsNew"><strong>1.1</strong><span>What's new in Grails 3.3?</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#whatsNewGORM"><strong>1.1.1</strong><span>GORM 6.1</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#whatsNewEventBus"><strong>1.1.2</strong><span>New Events API</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#whatsNewTesting"><strong>1.1.3</strong><span>New Testing Framework</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#whatsNewJSONViews"><strong>1.1.4</strong><span>JSON Views 1.2</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#dependencyUpgrades"><strong>1.1.5</strong><span>Updated Dependencies</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#otherNovelties"><strong>1.1.6</strong><span>Other Novelties</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#gettingStarted"><strong>2</strong><span>Getting Started</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#requirements"><strong>2.1</strong><span>Installation Requirements</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#downloadingAndInstalling"><strong>2.2</strong><span>Downloading and Installing</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#creatingAnApplication"><strong>2.3</strong><span>Creating an Application</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#aHelloWorldExample"><strong>2.4</strong><span>A Hello World Example</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#usingInteractiveMode"><strong>2.5</strong><span>Using Interactive Mode</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#ide"><strong>2.6</strong><span>Getting Set Up in an IDE</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#conventionOverConfiguration"><strong>2.7</strong><span>Convention over Configuration</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#runningAndDebuggingAnApplication"><strong>2.8</strong><span>Running and Debugging an Application</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#testingAnApplication"><strong>2.9</strong><span>Testing an Application</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#deployingAnApplication"><strong>2.10</strong><span>Deploying an Application</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#supportedJavaEEContainers"><strong>2.11</strong><span>Supported Java EE Containers</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#creatingArtefacts"><strong>2.12</strong><span>Creating Artefacts</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#generatingAnApplication"><strong>2.13</strong><span>Generating an Application</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#upgrading"><strong>3</strong><span>Upgrading from Grails 3.2.x</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#conf"><strong>4</strong><span>Configuration</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#config"><strong>4.1</strong><span>Basic Configuration</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#ymlOptions"><strong>4.1.1</strong><span>Options for the YML format Config</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#builtInOptions"><strong>4.1.2</strong><span>Built in options</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#logging"><strong>4.1.3</strong><span>Logging</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#loggerName"><strong>4.1.3.1</strong><span>Logger Names</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#maskingRequestParametersFromStacktraceLogs"><strong>4.1.3.2</strong><span>Masking Request Parameters From Stacktrace Logs</span></a></div>
<div class="toc-item" style="margin-left:30px"><a href="#externalLoggingConfiguration"><strong>4.1.3.3</strong><span>External Configuration File</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#configGORM"><strong>4.1.4</strong><span>GORM</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#proxyConfig"><strong>4.1.5</strong><span>Configuring an HTTP proxy</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#applicationClass"><strong>4.2</strong><span>The Application Class</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#executing"><strong>4.2.1</strong><span>Executing the Application Class</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#customizing"><strong>4.2.2</strong><span>Customizing the Application Class</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#applicationLifeCycle"><strong>4.2.3</strong><span>The Application LifeCycle</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#environments"><strong>4.3</strong><span>Environments</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#dataSource"><strong>4.4</strong><span>The DataSource</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#dataSourcesAndEnvironments"><strong>4.4.1</strong><span>DataSources and Environments</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#automaticDatabaseMigration"><strong>4.4.2</strong><span>Automatic Database Migration</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#transactionAwareDataSourceProxy"><strong>4.4.3</strong><span>Transaction-aware DataSource Proxy</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#databaseConsole"><strong>4.4.4</strong><span>Database Console</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#multipleDatasources"><strong>4.4.5</strong><span>Multiple Datasources</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#versioning"><strong>4.5</strong><span>Versioning</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#dependencyResolution"><strong>4.6</strong><span>Dependency Resolution</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#commandLine"><strong>5</strong><span>The Command Line</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#interactiveMode"><strong>5.1</strong><span>Interactive Mode</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#creatingCustomScripts"><strong>5.2</strong><span>Creating Custom Scripts</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#creatingCustomCommands"><strong>5.3</strong><span>Creating Custom Commands</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#reusingGrailsScripts"><strong>5.4</strong><span>Re-using Grails scripts</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#gradleBuild"><strong>5.5</strong><span>Building with Gradle</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#gradleDependencies"><strong>5.5.1</strong><span>Defining Dependencies with Gradle</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#gradleTasks"><strong>5.5.2</strong><span>Working with Gradle Tasks</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#gradlePlugins"><strong>5.5.3</strong><span>Grails plugins for Gradle</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#profiles"><strong>6</strong><span>Application Profiles</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#creatingProfiles"><strong>6.1</strong><span>Creating Profiles</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#profileInheritance"><strong>6.2</strong><span>Profile Inheritance</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#publishingProfiles"><strong>6.3</strong><span>Publishing Profiles</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#profileStructure"><strong>6.4</strong><span>Understanding Profiles</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#profileCommands"><strong>6.5</strong><span>Creating Profile Commands</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#profileFeatures"><strong>6.6</strong><span>Creating Profile Features</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#GORM"><strong>7</strong><span>Object Relational Mapping (GORM)</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#quickStartGuide"><strong>7.1</strong><span>Quick Start Guide</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#basicCRUD"><strong>7.1.1</strong><span>Basic CRUD</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#furtherReading"><strong>7.2</strong><span>Further Reading on GORM</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#theWebLayer"><strong>8</strong><span>The Web Layer</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#controllers"><strong>8.1</strong><span>Controllers</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#understandingControllersAndActions"><strong>8.1.1</strong><span>Understanding Controllers and Actions</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#controllersAndScopes"><strong>8.1.2</strong><span>Controllers and Scopes</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#modelsAndViews"><strong>8.1.3</strong><span>Models and Views</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#redirectsAndChaining"><strong>8.1.4</strong><span>Redirects and Chaining</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#dataBinding"><strong>8.1.5</strong><span>Data Binding</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#jsonResponses"><strong>8.1.6</strong><span>Responding with JSON</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#moreOnJSONBuilder"><strong>8.1.7</strong><span>More on JSONBuilder</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#xmlResponses"><strong>8.1.8</strong><span>Responding with XML</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#uploadingFiles"><strong>8.1.9</strong><span>Uploading Files</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#commandObjects"><strong>8.1.10</strong><span>Command Objects</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#formtokens"><strong>8.1.11</strong><span>Handling Duplicate Form Submissions</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#typeConverters"><strong>8.1.12</strong><span>Simple Type Converters</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#controllerExceptionHandling"><strong>8.1.13</strong><span>Declarative Controller Exception Handling</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#gsp"><strong>8.2</strong><span>Groovy Server Pages</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#urlmappings"><strong>8.3</strong><span>URL Mappings</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#mappingToControllersAndActions"><strong>8.3.1</strong><span>Mapping to Controllers and Actions</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#restfulMappings"><strong>8.3.2</strong><span>Mapping to REST resources</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#redirectMappings"><strong>8.3.3</strong><span>Redirects In URL Mappings</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#embeddedVariables"><strong>8.3.4</strong><span>Embedded Variables</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#mappingToViews"><strong>8.3.5</strong><span>Mapping to Views</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#mappingToResponseCodes"><strong>8.3.6</strong><span>Mapping to Response Codes</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#mappingHTTP"><strong>8.3.7</strong><span>Mapping to HTTP methods</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#mappingWildcards"><strong>8.3.8</strong><span>Mapping Wildcards</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#automaticLinkRewriting"><strong>8.3.9</strong><span>Automatic Link Re-Writing</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#applyingConstraints"><strong>8.3.10</strong><span>Applying Constraints</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#namedMappings"><strong>8.3.11</strong><span>Named URL Mappings</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#customizingUrlFormat"><strong>8.3.12</strong><span>Customizing URL Formats</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#namespacedControllers"><strong>8.3.13</strong><span>Namespaced Controllers</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#cors"><strong>8.4</strong><span>CORS</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#interceptors"><strong>8.5</strong><span>Interceptors</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#definingInterceptors"><strong>8.5.1</strong><span>Defining Interceptors</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#interceptorMatching"><strong>8.5.2</strong><span>Matching Requests with Inteceptors</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#interceptorOrdering"><strong>8.5.3</strong><span>Ordering Interceptor Execution</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#contentNegotiation"><strong>8.6</strong><span>Content Negotiation</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#traits"><strong>9</strong><span>Traits</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#traitsprovided"><strong>9.1</strong><span>Traits Provided by Grails</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#example"><strong>9.1.1</strong><span>WebAttributes Trait Example</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#REST"><strong>10</strong><span>REST</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#domainResources"><strong>10.1</strong><span>Domain classes as REST resources</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#urlMappings"><strong>10.2</strong><span>Mapping to REST resources</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#linkingToResources"><strong>10.3</strong><span>Linking to REST resources from GSP pages</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#versioningResources"><strong>10.4</strong><span>Versioning REST resources</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#restfulControllers"><strong>10.5</strong><span>Implementing REST controllers</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#extendingRestfulController"><strong>10.5.1</strong><span>Extending the RestfulController super class</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#restControllersStepByStep"><strong>10.5.2</strong><span>Implementing REST Controllers Step by Step</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#generatingRestControllers"><strong>10.5.3</strong><span>Generating a REST controller using scaffolding</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#restProfile"><strong>10.6</strong><span>The REST Profile</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#angularJsProfile"><strong>10.7</strong><span>The AngularJS Profile</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#angularProfile"><strong>10.8</strong><span>The Angular Profile</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#jsonViews"><strong>10.9</strong><span>JSON Views</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#jsonViewsSetup"><strong>10.9.1</strong><span>Getting Started</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#jsonViewsCreating"><strong>10.9.2</strong><span>Creating JSON Views</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#jsonViewsAndTemplates"><strong>10.9.3</strong><span>JSON View Templates</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#jsonViewsAndDomainClasses"><strong>10.9.4</strong><span>Rendering Domain Classes with JSON Views</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#jsonViewsTemplatesAndConventions"><strong>10.9.5</strong><span>JSON Views by Convention</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#renderers"><strong>10.10</strong><span>Customizing Response Rendering</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#defaultRenderers"><strong>10.10.1</strong><span>Customizing the Default Renderers</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#customRenderers"><strong>10.10.2</strong><span>Implementing a Custom Renderer</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#gspRenderers"><strong>10.10.3</strong><span>Using GSP to Customize Rendering</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#hypermedia"><strong>10.11</strong><span>Hypermedia as the Engine of Application State</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#hal"><strong>10.11.1</strong><span>HAL Support</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#atom"><strong>10.11.2</strong><span>Atom Support</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#vndError"><strong>10.11.3</strong><span>Vnd.Error Support</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#binding"><strong>10.12</strong><span>Customizing Binding of Resources</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#RSSAndAtom"><strong>10.13</strong><span>RSS and Atom</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#async"><strong>11</strong><span>Asynchronous Programming</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#validation"><strong>12</strong><span>Validation</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#constraints"><strong>12.1</strong><span>Declaring Constraints</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#validatingConstraints"><strong>12.2</strong><span>Validating Constraints</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#sharingConstraints"><strong>12.3</strong><span>Sharing Constraints Between Classes</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#validationOnTheClient"><strong>12.4</strong><span>Validation on the Client</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#validationAndInternationalization"><strong>12.5</strong><span>Validation and Internationalization</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#validationNonDomainAndCommandObjectClasses"><strong>12.6</strong><span>Applying Validation to Other Classes</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#services"><strong>13</strong><span>The Service Layer</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#declarativeTransactions"><strong>13.1</strong><span>Declarative Transactions</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#transactionsMultiDataSource"><strong>13.1.1</strong><span>Transactions and Multi-DataSources</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#transactionsRollbackAndTheSession"><strong>13.1.2</strong><span>Transactions Rollback and the Session</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#scopedServices"><strong>13.2</strong><span>Scoped Services</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#dependencyInjectionServices"><strong>13.3</strong><span>Dependency Injection and Services</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#staticTypeCheckingAndCompilation"><strong>14</strong><span>Static Type Checking And Compilation</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#grailsCompileStatic"><strong>14.1</strong><span>The GrailsCompileStatic Annotation</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#grailsTypeChecked"><strong>14.2</strong><span>The GrailsTypeChecked Annotation</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#testing"><strong>15</strong><span>Testing</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#unitTesting"><strong>15.1</strong><span>Unit Testing</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#integrationTesting"><strong>15.2</strong><span>Integration Testing</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#functionalTesting"><strong>15.3</strong><span>Functional Testing</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#i18n"><strong>16</strong><span>Internationalization</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#understandingMessageBundles"><strong>16.1</strong><span>Understanding Message Bundles</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#changingLocales"><strong>16.2</strong><span>Changing Locales</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#readingMessages"><strong>16.3</strong><span>Reading Messages</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#scaffoldingAndI18n"><strong>16.4</strong><span>Scaffolding and i18n</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#security"><strong>17</strong><span>Security</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#securingAgainstAttacks"><strong>17.1</strong><span>Securing Against Attacks</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#xssPrevention"><strong>17.2</strong><span>Cross Site Scripting (XSS) Prevention</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#codecs"><strong>17.3</strong><span>Encoding and Decoding Objects</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#authentication"><strong>17.4</strong><span>Authentication</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#securityPlugins"><strong>17.5</strong><span>Security Plugins</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#springSecurity"><strong>17.5.1</strong><span>Spring Security</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#plugins"><strong>18</strong><span>Plugins</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#creatingAndInstallingPlugins"><strong>18.1</strong><span>Creating and Installing Plugins</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#repositories"><strong>18.2</strong><span>Plugin Repositories</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#providingBasicArtefacts"><strong>18.3</strong><span>Providing Basic Artefacts</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#evaluatingConventions"><strong>18.4</strong><span>Evaluating Conventions</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#hookingIntoRuntimeConfiguration"><strong>18.5</strong><span>Hooking into Runtime Configuration</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#addingMethodsAtCompileTime"><strong>18.6</strong><span>Adding Methods at Compile Time</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#addingDynamicMethodsAtRuntime"><strong>18.7</strong><span>Adding Dynamic Methods at Runtime</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#participatingInAutoReloadEvents"><strong>18.8</strong><span>Participating in Auto Reload Events</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#understandingPluginLoadOrder"><strong>18.9</strong><span>Understanding Plugin Load Order</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#artefactApi"><strong>18.10</strong><span>The Artefact API</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#queryingArtefacts"><strong>18.10.1</strong><span>Asking About Available Artefacts</span></a></div>
<div class="toc-item" style="margin-left:20px"><a href="#customArtefacts"><strong>18.10.2</strong><span>Adding Your Own Artefact Types</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#spring"><strong>19</strong><span>Grails and Spring</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#springdslAdditional"><strong>19.1</strong><span>Configuring Additional Beans</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#springdsl"><strong>19.2</strong><span>Runtime Spring with the Beans DSL</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#theBeanBuilderDSLExplained"><strong>19.3</strong><span>The BeanBuilder DSL Explained</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#propertyPlaceholderConfiguration"><strong>19.4</strong><span>Property Placeholder Configuration</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#propertyOverrideConfiguration"><strong>19.5</strong><span>Property Override Configuration</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#actuators"><strong>19.6</strong><span>Spring Boot Actuators</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#scaffolding"><strong>20</strong><span>Scaffolding</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#deployment"><strong>21</strong><span>Deployment</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#deploymentStandalone"><strong>21.1</strong><span>Standalone</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#deploymentContainer"><strong>21.2</strong><span>Container Deployment (e.g. Tomcat)</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#deploymentTasks"><strong>21.3</strong><span>Deployment Configuration Tasks</span></a></div>
<div class="toc-item" style="margin-left:0px"><a href="#contributing"><strong>22</strong><span>Contributing to Grails</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#issues"><strong>22.1</strong><span>Report Issues in Github's issue tracker</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#build"><strong>22.2</strong><span>Build From Source and Run Tests</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#patchesCore"><strong>22.3</strong><span>Submit Patches to Grails Core</span></a></div>
<div class="toc-item" style="margin-left:10px"><a href="#patchesDoc"><strong>22.4</strong><span>Submit Patches to Grails Documentation</span></a></div>
<div style="clear:both" ></div>
</div>
<a name="1. Introduction"><!-- Legacy link --></a>
<h1 id="introduction">1 Introduction</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/introduction.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Many modern web frameworks in the Java space are more complicated than needed and don&#8217;t embrace the Don&#8217;t Repeat Yourself (DRY) principles.</p>
</div>
<div class="paragraph">
<p>Dynamic frameworks like Rails and Django 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>
</div>
<div class="paragraph">
<p>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:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://grails.apache.org/docs/latest/grails-data/">GORM</a> - An easy to use Object Mapping library with support for <a href="https://grails.apache.org/docs/latest/grails-data/hibernate5/manual/">SQL</a>, <a href="https://grails.apache.org/docs/latest/grails-data/mongodb/manual/">MongoDB</a>, <a href="https://grails.apache.org/docs/latest/grails-data/mongodb/manual/">Neo4j</a> and <a href="https://grails.apache.org/docs/latest/grails-data/">more</a>.</p>
</li>
<li>
<p>View technologies for <a href="https://gsp.grails.org">rendering HTML</a> as well as <a href="http://views.grails.org">JSON</a></p>
</li>
<li>
<p>A controller layer built on <a href="http://www.spring.io">Spring Boot</a></p>
</li>
<li>
<p>A plugin system featuring <a href="http://plugins.grails.org">hundreds of plugins</a>.</p>
</li>
<li>
<p>Flexible profiles to <a href="http://start.grails.org/#/index">create applications with AngularJS, React and more</a>.</p>
</li>
<li>
<p>An interactive command line environment and build system based on <a href="http://gradle.org">Gradle</a></p>
</li>
<li>
<p>An embedded <a href="http://tomcat.apache.org">Tomcat</a> container which is configured for on the fly reloading</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>All of these are made easy to use through the power of the <a href="http://groovy-lang.org">Groovy</a> language and the extensive use of Domain Specific Languages (DSLs)</p>
</div>
<div class="paragraph">
<p>This documentation will take you through getting started with Grails and building web applications with the Grails framework.</p>
</div>
<div class="paragraph">
<p>In addition to this documentation there are <a href="http://guides.grails.org">comprehensive guides</a> that walk you through various aspects of the technology.</p>
</div>
<div class="paragraph">
<p>Finally, Grails is far more than just a web framework and is made up of various sub-projects. The following table summarizes some other key projects in the eco-system with links to documentation.</p>
</div>
<table class="tableblock frame-all grid-all spread">
<caption class="title">Table 1. Grails Ecosystem Projects</caption>
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">Project</th>
<th class="tableblock halign-left valign-top">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/grails-data/hibernate5/manual/">GORM for Hibernate</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">An Object Mapping implementation for SQL databases</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/grails-data/mongodb/manual/">GORM for MongoDB</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">An Object Mapping implementation for the MongoDB Document Database</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs-legacy-gorm/latest/neo4j">GORM for Neo4j</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">An Object Mapping implementation for Neo4j Graph Database</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="http://views.grails.org">JSON Views</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">A View technology for rendering JSON on the server side</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="http://gsp.grails.org">Groovy Server Pages</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">A View technology for rendering HTML and other markup on the server</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/guide/async.html">Async Framework</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Asynchronous programming abstraction with support for RxJava, GPars and more</p></td>
</tr>
</tbody>
</table>
<a name="1.1 What's new in Grails 2.0?"><!-- Legacy link --></a>
<h2 id="whatsNew">1.1 What's new in Grails 3.3?</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/introduction/whatsNew.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>This section covers all the new features introduced in Grails 3.3.</p>
</div>
<h2 id="whatsNewGORM">1.1.1 GORM 6.1</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/introduction/whatsNew/whatsNewGORM.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails 3.3 comes with GORM 6.1, which includes the following new features:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Multi-Tenancy AST Transforms</p>
</li>
<li>
<p>Rewritten <code>@Transactional</code> and <code>@Rollback</code> transformations</p>
</li>
<li>
<p>Common Services like <code>TenantService</code> and <code>TransactionService</code></p>
</li>
<li>
<p>Data Services Concept - Implement interfaces automatically!</p>
</li>
<li>
<p>Bean Validation API Support</p>
</li>
<li>
<p>JPA Annotation Support</p>
</li>
<li>
<p>Package Scanning and Easy Unit Testing</p>
</li>
<li>
<p>Neo4j Bolt 1.2 Driver Support</p>
</li>
<li>
<p>MongoDB 3.4 Driver Support</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>There are so many new features and novelties in GORM that we had to write its own independent <a href="https://grails.apache.org/docs-legacy-gorm/6.1.x/whatsNew/manual/index.html">What&#8217;s New Guide</a>!</p>
</div>
<h2 id="whatsNewEventBus">1.1.2 New Events API</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/introduction/whatsNew/whatsNewEventBus.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>The <a href="https://grails.apache.org/docs/latest/guide/async.html">Grails Async Framework</a> has been extracted from Grails and moved to a separate project.</p>
</div>
<div class="paragraph">
<p>This allows the Async support to evolve independent of the framework itself in a fast moving and evolving area.</p>
</div>
<div class="paragraph">
<p>In order to support multiple different asynchronous and reactive frameworks Grails 3.3 has been decoupled from Reactor 2.x and an abstract <code>EventBus</code> notation added.</p>
</div>
<div class="paragraph">
<p>The <a href="https://grails.apache.org/docs/latest/api/grails/events/bus/EventBus.html">EventBus</a> interface provides the foundation and multiple implementations including GPars and RxJava.</p>
</div>
<div class="paragraph">
<p>A new set of annotations usable in services classes and regular Spring beans can be leveraged to publish and consume events:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://grails.apache.org/docs/latest/api/grails/events/annotation/Publisher.html">Publisher</a> - A transformation that transforms a method ensuring the return value is published as an event</p>
</li>
<li>
<p><a href="https://grails.apache.org/docs/latest/api/grails/events/annotation/Subscriber.html">Subscriber</a> - A transformation that transforms a method to listen for an event.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>For more information see <a href="https://grails.apache.org/docs/latest/guide/async.html#events">the new documentation</a>.</p>
</div>
<h2 id="whatsNewTesting">1.1.3 New Testing Framework</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/introduction/whatsNew/whatsNewTesting.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails 3.3 includes a <a href="https://testing.grails.org">new Trait-based testing framework</a> that replaces the existing <code>@TestMixin</code> based framework with a simpler implementation that is easier to debug, provides better code completion and is easier to extend.</p>
</div>
<div class="paragraph">
<p>An example hello world test can be seen below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">spock.lang.Specification</span>
<span class="keyword">import</span> <span class="include">grails.testing.web.controllers.ControllerUnitTest</span>
<span class="type">class</span> <span class="class">HelloControllerTests</span> <span class="directive">extends</span> Specification <span class="directive">implements</span> ControllerUnitTest&lt;HelloController&gt; {
<span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">Test message action</span><span class="delimiter">&quot;</span></span>() {
<span class="key">when</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">The message action is invoked</span><span class="delimiter">&quot;</span></span>
controller.message()
<span class="key">then</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">Hello is returned</span><span class="delimiter">&quot;</span></span>
response.text == <span class="string"><span class="delimiter">'</span><span class="content">Hello</span><span class="delimiter">'</span></span>
}
}</code></pre>
</div>
</div>
<h2 id="whatsNewJSONViews">1.1.4 JSON Views 1.2</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/introduction/whatsNew/whatsNewJSONViews.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p><a href="http://views.grails.org/1.2.x">Version 1.2</a> of the JSON Views plugin is included with Grails 3.3&#8217;s "rest-api" profile and includes <a href="http://views.grails.org/1.2.x/#_version_history">a number of new features</a>. Below are some of the highlights:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Support for the <a href="http://jsonapi.org">JSON API</a> specification</p>
</li>
<li>
<p>Ability to register custom converters</p>
</li>
<li>
<p>Multiple configuration options for date formatting, unicode escaping, etc</p>
</li>
</ul>
</div>
<h2 id="dependencyUpgrades">1.1.5 Updated Dependencies</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/introduction/whatsNew/dependencyUpgrades.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails 3.3 ships with the following dependency upgrades:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Hibernate 5.1.5 (now the default version of Hibernate for new applications)</p>
</li>
<li>
<p>Spring Framework 4.3.9</p>
</li>
<li>
<p>Spring Boot 1.5.4</p>
</li>
<li>
<p>Gradle 3.5 (Grails 3.3 is also compatible with Gradle 4.x)</p>
</li>
<li>
<p>Spock 1.1</p>
</li>
</ul>
</div>
<h2 id="otherNovelties">1.1.6 Other Novelties</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/introduction/whatsNew/otherNovelties.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_cache_plugin_rewritten">Cache Plugin Rewritten</h4>
<div class="paragraph">
<p>The <a href="http://plugins.grails.org/plugin/grails/cache">Cache Plugin</a> has been rewritten and no longer use proxies which improves startup time and performance. The plugin is also now <a href="https://grails.apache.org/docs/latest/grails-data/hibernate5/manual//manual/index.html#multiTenancy">Multi-Tenant</a> aware, ensuring that cached data is not seen by other tenants.</p>
</div>
</div>
<div class="sect3">
<h4 id="_converters_plugin_now_separate">Converters plugin now Separate</h4>
<div class="paragraph">
<p>With <a href="http://views.grails.org">JSON Views</a> now being the recommended way to render JSON. The converters plugin has been split out from core into <a href="https://github.com/grails-plugins/grails-plugin-converters">a separate project</a>.</p>
</div>
</div>
<div class="sect3">
<h4 id="_logger_name_changes">Logger name changes</h4>
<div class="paragraph">
<p>Grails logger names for artifacts have been simplifled from <code>grails.app.&lt;type&gt;.&lt;className&gt;</code> to use the the package name.</p>
</div>
<div class="paragraph">
<p>For example <code>grails.app.controller.com.example.BookController</code> is now simply <code>com.example.BookController</code>.</p>
</div>
<div class="paragraph">
<p>For more information see the <a href="https://grails.apache.org/docs/3.3.x/guide/conf.html#loggerName">documentation</a>.</p>
</div>
</div>
<a name="2. Getting Started"><!-- Legacy link --></a>
<h1 id="gettingStarted">2 Getting Started</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/gettingStarted.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<h2 id="requirements">2.1 Installation Requirements</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/gettingStarted/requirements.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Before installing Grails 3.3.2 you will need as a minimum a Java Development Kit (JDK) installed version 1.7 or above.</p>
</div>
<div class="paragraph">
<p>If you want to use JDK 1.7, you need to run Gradle with Java 1.7.0_131-b31 or above to <a href="https://blog.gradle.org/unable-to-download-maven-central-bintray">fix Gradle dependency resolution when TLS v1.1 and v1.0 support is discontinued</a>.</p>
</div>
<div class="paragraph">
<p>Download the appropriate JDK for your operating system, run the installer, and then set up an environment variable called <code>JAVA_HOME</code> pointing to the location of this installation.</p>
</div>
<div class="paragraph">
<p>To automate the installation of Grails we recommend <a href="http://sdkman.io">SDKMAN</a> which greatly simplifies installing and managing multiple Grails versions.</p>
</div>
<div class="paragraph">
<p>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, if you&#8217;re using bash or another variant of the Bourne Shell:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">export JAVA_HOME=/Library/Java/Home
export PATH=&quot;$PATH:$JAVA_HOME/bin&quot;</code></pre>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
On Windows you would have to configure these environment variables in <code>My Computer/Advanced/Environment Variables</code>
</td>
</tr>
</table>
</div>
<a name="2.1 Downloading and Installing"><!-- Legacy link --></a>
<h2 id="downloadingAndInstalling">2.2 Downloading and Installing</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/gettingStarted/downloadingAndInstalling.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>The first step to getting up and running with Grails is to install the distribution.</p>
</div>
<div class="paragraph">
<p>The best way to install Grails on *nix systems is with <a href="http://sdkman.io">SDKMAN</a> which greatly simplifies installing and managing multiple Grails versions.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_install_with_sdkman">Install with SDKMAN</h2>
<div class="sectionbody">
<div class="paragraph">
<p>To install the latest version of Grails using SDKMAN, run this on your terminal:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="shell">sdk install grails</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also specify a version</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="shell">sdk install grails 3.2.3</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can find more information about SDKMAN usage on the <a href="http://sdkman.io/usage.html">SDKMAN Docs</a></p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_manual_installation">Manual installation</h2>
<div class="sectionbody">
<div class="paragraph">
<p>For manual installation follow these steps:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://github.com/grails/grails-core/releases">Download</a> a binary distribution of Grails and extract the resulting zip file to a location of your choice</p>
</li>
<li>
<p>Set the GRAILS_HOME environment variable to the location where you extracted the zip</p>
<div class="ulist">
<ul>
<li>
<p>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</p>
</li>
<li>
<p>On Windows this is typically a matter of setting an environment variable under <code>My Computer/Advanced/Environment Variables</code></p>
</li>
</ul>
</div>
</li>
<li>
<p>Then add the <code>bin</code> directory to your <code>PATH</code> variable:</p>
<div class="ulist">
<ul>
<li>
<p>On Unix/Linux based systems this can be done by adding <code>export PATH="$PATH:$GRAILS_HOME/bin"</code> to your profile</p>
</li>
<li>
<p>On Windows this is done by modifying the <code>Path</code> environment variable under <code>My Computer/Advanced/Environment Variables</code></p>
</li>
</ul>
</div>
</li>
</ul>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">Grails version: 3.3.7</code></pre>
</div>
</div>
</div>
</div>
<a name="2.4 Creating an Application"><!-- Legacy link --></a>
<h2 id="creatingAnApplication">2.3 Creating an Application</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/gettingStarted/creatingAnApplication.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">grails &lt;&lt;command name&gt;&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Run <a href="../ref/Command%20Line/create-app.html">create-app</a> to create an application:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">grails create-app helloworld</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will create a new directory inside the current one that contains the project. Navigate to this directory in your console:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">cd helloworld</code></pre>
</div>
</div>
<a name="2.5 A Hello World Example"><!-- Legacy link --></a>
<h2 id="aHelloWorldExample">2.4 A Hello World Example</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/gettingStarted/aHelloWorldExample.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Let&#8217;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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ cd helloworld
$ grails</code></pre>
</div>
</div>
<div class="paragraph">
<p>You should see a prompt that looks like this:</p>
</div>
<div class="imageblock">
<div class="content">
<img src="../img/interactive-helloworld.png" alt="interactive helloworld">
</div>
</div>
<div class="paragraph">
<p>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&#8217;t yet have a controller, let&#8217;s create one now with the <a href="../ref/Command%20Line/create-controller.html">create-controller</a> command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">grails&gt; create-controller hello</code></pre>
</div>
</div>
<div class="paragraph">
<p>Don&#8217;t forget that in the interactive console, we have auto-completion on command names. So you can type "cre" and then press &lt;tab&gt; to get a list of all <code>create-*</code> commands. Type a few more letters of the command name and then &lt;tab&gt; again to finish.</p>
</div>
<div class="paragraph">
<p>The above command will create a new <a href="theWebLayer.html#controllers">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&#8217;s strongly recommended that all classes are placed into packages, so Grails defaults to the application name if you don&#8217;t provide one. The reference page for <a href="../ref/Command%20Line/create-controller.html">create-controller</a> provides more detail on this.</p>
</div>
<div class="paragraph">
<p>We now have a controller so let&#8217;s add an action to generate the "Hello World!" page. In any text editor, edit the new controller&#8201;&#8212;&#8201;the <code>HelloController.groovy</code> file&#8201;&#8212;&#8201;by adding a render line. The edited file&#8217;s code should look like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> helloworld
<span class="type">class</span> <span class="class">HelloController</span> {
<span class="keyword">def</span> <span class="function">index</span>() {
render <span class="string"><span class="delimiter">&quot;</span><span class="content">Hello World!</span><span class="delimiter">&quot;</span></span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The action is simply a method. In this particular case, it calls a special method provided by Grails to <a href="../ref/Controllers/render.html">render</a> the page.</p>
</div>
<div class="paragraph">
<p>Job done. To see your application in action, you just need to start up a server with another command called <a href="../ref/Command%20Line/run-app.html">run-app</a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">grails&gt; run-app</code></pre>
</div>
</div>
<div class="paragraph">
<p>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/" class="bare">http://localhost:8080/</a> - try it!</p>
</div>
<div class="paragraph">
<p>Note that in previous versions of Grails the context path was by default the name of the application. If you wish to restore this behavior you can configure a context path in <code>grails-app/conf/application.yml</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">server</span>:
<span class="key">contextPath</span>: <span class="string"><span class="content">/helloworld</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>With the above configuration in place the server will instead startup at the URL <a href="http://localhost:8080/helloworld/" class="bare">http://localhost:8080/helloworld/</a>.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
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>run-app -port=9090</code>. '9090' is just an example: you can pretty much choose anything within the range 1024 to 49151.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The result will look something like this:</p>
</div>
<div class="imageblock">
<div class="content">
<img src="../img/intropage.png" alt="intropage">
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>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: /&lt;appname&gt;/&lt;controller&gt;/&lt;action&gt;. This means you can access the Hello World page via <a href="http://localhost:8080/helloworld/hello/index">/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>default action</em>. See the end of the <a href="theWebLayer.html#understandingControllersAndActions">controllers and actions</a> section of the user guide to find out more on default actions.</p>
</div>
<h2 id="usingInteractiveMode">2.5 Using Interactive Mode</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/gettingStarted/usingInteractiveMode.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails 3.0 features an interactive mode which makes command execution faster since the JVM doesn&#8217;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>
</div>
<div class="imageblock">
<div class="content">
<img src="../img/interactive-output.png" alt="interactive output">
</div>
</div>
<div class="paragraph">
<p>For more information on the capabilities of interactive mode refer to the section on <a href="commandLine.html#interactiveMode">Interactive Mode</a> in the user guide.</p>
</div>
<a name="2.6 Getting Set-up in an IDE"><!-- Legacy link --></a>
<h2 id="ide">2.6 Getting Set Up in an IDE</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/gettingStarted/ide.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_intellij_idea">IntelliJ IDEA</h4>
<div class="paragraph">
<p><a href="http://www.jetbrains.com/idea">IntelliJ IDEA</a> is an excellent IDE for Grails 3.0 development. It comes in 2 editions, the free community edition and the paid-for ultimate edition.</p>
</div>
<div class="paragraph">
<p>The community edition can be used for most things, although GSP syntax higlighting is only part of the ultimate edition</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
You can always open GSP files in the HTML editor if you just want highlighting in the community edition.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>To get started with Intellij IDEA and Grails 3.0 simply go to <code>File / Open</code> and point IDEA at your <code>build.gradle</code> file to import and configure the project.</p>
</div>
</div>
<div class="sect3">
<h4 id="_textmate_sublime_vim_etc">TextMate, Sublime, VIM etc.</h4>
<div class="paragraph">
<p>There are several excellent text editors that work nicely with Groovy and Grails. See below for references:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>A <a href="https://github.com/textmate/groovy-grails.tmbundle">TextMate bundle</a> exists Groovy / Grails support in <a href="http://macromates.com">Textmate</a></p>
</li>
<li>
<p>A <a href="https://github.com/osoco/sublimetext-grails">Sublime Text plugin</a> can be installed via Sublime Package Control for the <a href="http://www.sublimetext.com">Sublime Text Editor</a>.</p>
</li>
<li>
<p>See <a href="http://www.objectpartners.com/2012/02/21/using-vim-as-your-grails-ide-part-1-navigating-your-project/">this post</a> for some helpful tips on how to setup VIM as your Grails editor of choice.</p>
</li>
<li>
<p>An <a href="https://atom.io/packages/atom-grails">Atom Package</a> is available for use with the <a href="https://atom.io">Atom editor</a>.</p>
</li>
</ul>
</div>
</div>
<a name="2.7 Convention over Configuration"><!-- Legacy link --></a>
<h2 id="conventionOverConfiguration">2.7 Convention over Configuration</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/gettingStarted/conventionOverConfiguration.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>Here is a breakdown and links to the relevant sections:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>grails-app</code> - top level directory for Groovy sources</p>
<div class="ulist">
<ul>
<li>
<p><code>conf</code> - <a href="conf.html">Configuration sources</a></p>
</li>
<li>
<p><code>controllers</code> - <a href="theWebLayer.html#controllers">Web controllers</a> - The C in MVC.</p>
</li>
<li>
<p><code>domain</code> - The <a href="GORM.html">application domain</a>.</p>
</li>
<li>
<p><code>i18n</code> - Support for <a href="i18n.html">internationalization (i18n)</a>.</p>
</li>
<li>
<p><code>services</code> - The <a href="services.html">service layer</a>.</p>
</li>
<li>
<p><code>taglib</code> - <a href="theWebLayer.html#taglibs">Tag libraries</a>.</p>
</li>
<li>
<p><code>utils</code> - Grails specific utilities.</p>
</li>
<li>
<p><code>views</code> - <a href="theWebLayer.html#gsp">Groovy Server Pages</a> or <a href="http://views.grails.org/latest">JSON Views</a> - The V in MVC.</p>
</li>
</ul>
</div>
</li>
<li>
<p><code>scripts</code> - <a href="commandLine.html">Code generation scripts</a>.</p>
</li>
<li>
<p><code>src/main/groovy</code> - Supporting sources</p>
</li>
<li>
<p><code>src/test/groovy</code> - <a href="testing.html">Unit and integration tests</a>.</p>
</li>
</ul>
</div>
<a name="2.8 Running and Debugging an Application"><!-- Legacy link --></a>
<h2 id="runningAndDebuggingAnApplication">2.8 Running and Debugging an Application</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/gettingStarted/runningAndDebuggingAnApplication.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails applications can be run with the built in Tomcat server using the <a href="../ref/Command%20Line/run-app.html">run-app</a> command which will load a server on port 8080 by default:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">grails run-app</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can specify a different port by using the <code>-port</code> argument:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">grails run-app -port=8090</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that it is better to start up the application in interactive mode since a container restart is much quicker:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails
grails&gt; run-app
| Grails application running at http://localhost:8080 in environment: development
grails&gt; stop-app
| Shutting down application...
| Application shutdown.
grails&gt; run-app
| Grails application running at http://localhost:8080 in environment: development</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can debug a grails app by simply right-clicking on the <code>Application.groovy</code> class in your IDE and choosing the appropriate action (since Grails 3).</p>
</div>
<div class="paragraph">
<p>Alternatively, you can run your app with the following command and then attach a remote debugger to it.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">grails run-app --debug-jvm</code></pre>
</div>
</div>
<div class="paragraph">
<p>More information on the <a href="../ref/Command%20Line/run-app.html">run-app</a> command can be found in the reference guide.</p>
</div>
<a name="2.9 Testing an Application"><!-- Legacy link --></a>
<h2 id="testingAnApplication">2.9 Testing an Application</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/gettingStarted/testingAnApplication.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>The <code>create-*</code> commands in Grails automatically create unit or integration tests for you within the <code>src/test/groovy</code> directory. It is of course up to you to populate these tests with valid test logic, information on which can be found in the section on <a href="testing.html">Unit and integration tests</a>.</p>
</div>
<div class="paragraph">
<p>To execute tests you run the <a href="../ref/Command%20Line/test-app.html">test-app</a> command as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app</code></pre>
</div>
</div>
<a name="2.10 Deploying an Application"><!-- Legacy link --></a>
<h2 id="deployingAnApplication">2.10 Deploying an Application</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/gettingStarted/deployingAnApplication.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails applications can be deployed in a number of different ways.</p>
</div>
<div class="paragraph">
<p>If you are deploying to a traditional container (Tomcat, Jetty etc.) you can create a Web Application Archive (WAR file), and Grails includes the <a href="../ref/Command%20Line/war.html">war</a> command for performing this task:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">grails war</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will produce a WAR file under the <code>build/libs</code> directory which can then be deployed as per your container&#8217;s instructions.</p>
</div>
<div class="paragraph">
<p>Note that by default Grails will include an embeddable version of Tomcat inside the WAR file, this can cause problems if you deploy to a different version of Tomcat. If you don&#8217;t intend to use the embedded container then you should change the scope of the Tomcat dependencies to <code>provided</code> prior to deploying to your production container in <code>build.gradle</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">provided <span class="string"><span class="delimiter">&quot;</span><span class="content">org.springframework.boot:spring-boot-starter-tomcat</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>If you are building a WAR file to deploy on Tomcat 7 then in addition you will need to change the target Tomcat version in the build. Grails is built against Tomcat 8 APIs by default.
To target a Tomcat 7 container, insert a line to <code>build.gradle</code> above the <code>dependencies { }</code> section:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">ext[<span class="string"><span class="delimiter">'</span><span class="content">tomcat.version</span><span class="delimiter">'</span></span>] = <span class="string"><span class="delimiter">'</span><span class="content">7.0.59</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">grails dev war</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you prefer not to operate a separate Servlet container then you can simply run the Grails WAR file as a regular Java application. Example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">grails war
java -Dgrails.env=prod -jar build/libs/mywar-0.1.war</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">-server -Xmx768M -XX:MaxPermSize=256m</code></pre>
</div>
</div>
<a name="2.11 Supported Java EE Containers"><!-- Legacy link --></a>
<h2 id="supportedJavaEEContainers">2.11 Supported Java EE Containers</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/gettingStarted/supportedJavaEEContainers.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails runs on any container that supports Servlet 3.0 and above and is known to work on the following specific container products:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Tomcat 7</p>
</li>
<li>
<p>GlassFish 3 or above</p>
</li>
<li>
<p>Resin 4 or above</p>
</li>
<li>
<p>JBoss 6 or above</p>
</li>
<li>
<p>Jetty 8 or above</p>
</li>
<li>
<p>Oracle Weblogic 12c or above</p>
</li>
<li>
<p>IBM WebSphere 8.0 or above</p>
</li>
</ul>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
It&#8217;s required to set "-Xverify:none" in "Application servers &gt; server &gt; Process Definition &gt; Java Virtual Machine &gt; Generic JVM arguments" for older versions of WebSphere. This is no longer needed for WebSphere version 8 or newer.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Some containers have bugs however, which in most cases can be worked around. A <a href="http://grails.org/Deployment">list of known deployment issues</a> can be found on the Grails wiki.</p>
</div>
<a name="2.13 Creating Artefacts"><!-- Legacy link --></a>
<h2 id="creatingArtefacts">2.12 Creating Artefacts</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/gettingStarted/creatingArtefacts.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails ships with a few convenience targets such as <a href="../ref/Command%20Line/create-controller.html">create-controller</a>, <a href="../ref/Command%20Line/create-domain-class.html">create-domain-class</a> and so on that will create <a href="theWebLayer.html#controllers">controllers</a> and different artefact types for you.
NOTE: These are just for your convenience and you can just as easily use an IDE or your favourite text editor.
For example to create the basis of an application you typically need a <a href="GORM.html">domain model</a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">grails create-app helloworld
cd helloworld
grails create-domain-class book</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will result in the creation of a domain class at <code>grails-app/domain/helloworld/Book.groovy</code> such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> helloworld
<span class="type">class</span> <span class="class">Book</span> {
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>There are many such <code>create-*</code> commands that can be explored in the command line reference guide.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
To decrease the amount of time it takes to run Grails scripts, use the interactive mode.
</td>
</tr>
</table>
</div>
<a name="2.12 Generating an Application"><!-- Legacy link --></a>
<h2 id="generatingAnApplication">2.13 Generating an Application</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/gettingStarted/generatingAnApplication.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>To get started quickly with Grails it is often useful to use a feature called <a href="scaffolding.html">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%20Line/generate-all.html">generate-all</a>, which will generate a <a href="theWebLayer.html#controllers">controller</a> (and its unit test) and the associated <a href="theWebLayer.html#gsp">views</a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails generate-all helloworld.Book</code></pre>
</div>
</div>
<h1 id="upgrading">3 Upgrading from Grails 3.2.x</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/upgrading.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails 3.3 includes several changes to dependencies and Event publishing that may require changes to your application if you are upgrading from Grails 3.2.x.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
For information on upgrading from versions of Grails prior to Grails 3.2.x, see the <a href="https://grails.apache.org/docs/3.2.x/guide/upgrading.html">Grails 3.2.x documentation on upgrading</a>
</td>
</tr>
</table>
</div>
<div class="sect2">
<h3 id="_gorm_6_1_upgrade">GORM 6.1 Upgrade</h3>
<div class="paragraph">
<p>GORM 6.1 <a href="https://grails.apache.org/docs/latest/grails-data/hibernate5/manual//manual/index.html#upgradeNotes">includes changes</a> that may require you to change your application.</p>
</div>
<div class="sect3">
<h4 id="_gorm_async_now_optional">GORM Async Now Optional</h4>
<div class="paragraph">
<p>Notably <code>grails-datastore-gorm-async</code> is now optional and if you use the <code>task</code> method of GORM you will need to manually implement the <code>AsyncEntity</code> trait.</p>
</div>
</div>
<div class="sect3">
<h4 id="_domain_autowiring_disabled">Domain Autowiring Disabled</h4>
<div class="paragraph">
<p>Domain class autowiring is disabled by default due to its impact on performance. You can re-enable autowiring for all domains using the <a href="https://grails.apache.org/docs/latest/grails-data/hibernate5/manual//manual/index.html#_the_default_mapping_constraints">Default Mapping</a> setting:</p>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/application.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails.gorm.default.mapping = {
autowire <span class="predefined-constant">true</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can turn it on only for one domain class:</p>
</div>
<div class="listingblock">
<div class="title">grails-app/domain/demo/Book.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Book</span> {
BookService bookService
<span class="predefined-type">String</span> name
<span class="directive">static</span> mapping {
autowire <span class="predefined-constant">true</span>
}
...
..
.
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_flush_mode_now_commit_by_default">Flush Mode now COMMIT by Default</h4>
<div class="paragraph">
<p>The default flush mode has been change to <code>COMMIT</code> due to the impact the previous flush mode <code>AUTO</code> has on read performance. You can switch back to <code>AUTO</code> use the <code>hibernate.flush.mode</code> setting in <code>application.yml</code></p>
</div>
</div>
<div class="sect3">
<h4 id="_transactionmanager_chaining_for_multiple_data_sources_disabled_by_default">TransactionManager Chaining for Multiple Data Sources Disabled by Default</h4>
<div class="paragraph">
<p>In previous versions of Grails for multiple data sources a best effort transaction chain was used to attempt to manage a transaction across all configured data sources.</p>
</div>
<div class="paragraph">
<p>As of Grails 3.3 this is disabled as it caused confusion since it isn&#8217;t a true XA implementation and also impacts performance as for every transaction you have a transaction for each data source bound regardless if that is the actual requirement.</p>
</div>
<div class="paragraph">
<p>If your application depends on this feature you can re-enable it with the following configuration:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">grails</span>:
<span class="key">transaction</span>:
<span class="key">chainedTransactionManager</span>:
<span class="key">enabled</span>: <span class="string"><span class="content">true</span></span>
<span class="key">blacklistPattern</span>: <span class="string"><span class="content">'.*'</span></span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_tomcat_jdbc">Tomcat JDBC</h4>
<div class="paragraph">
<p>GORM 6.1 and above now supports multiple connection pool options, so the <code>tomcat-jdbc</code> dependency is now optional. If you are upgrading you may need to add it (or another pool implementation) to your <code>build.gradle</code>:</p>
</div>
<div class="listingblock">
<div class="title">build.gradle</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">runtime <span class="string"><span class="delimiter">'</span><span class="content">org.apache.tomcat:tomcat-jdbc</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="__testmixin_testfor_etc_deprecated">@TestMixin, @TestFor etc. Deprecated</h3>
<div class="paragraph">
<p>Since Grails 3.3, the <a href="https://testing.grails.org">Grails Testing Support Framework</a> is used for all unit tests. The new testing framework is much simpler and provides a set of traits that improve readability, debugging and code completion. An example hello world test can be seen below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">spock.lang.Specification</span>
<span class="keyword">import</span> <span class="include">grails.testing.web.controllers.ControllerUnitTest</span>
<span class="type">class</span> <span class="class">HelloControllerTests</span> <span class="directive">extends</span> Specification <span class="directive">implements</span> ControllerUnitTest&lt;HelloController&gt; {
<span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">Test message action</span><span class="delimiter">&quot;</span></span>() {
<span class="key">when</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">The message action is invoked</span><span class="delimiter">&quot;</span></span>
controller.message()
<span class="key">then</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">Hello is returned</span><span class="delimiter">&quot;</span></span>
response.text == <span class="string"><span class="delimiter">'</span><span class="content">Hello</span><span class="delimiter">'</span></span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>For more information on writing tests with Grails Testing Support see the <a href="https://testing.grails.org">dedicated documentation</a>.</p>
</div>
<div class="paragraph">
<p>To simplify upgrades you can can still use the previous AST transformation based framework by adding the following dependency to your Grails application:</p>
</div>
<div class="listingblock">
<div class="title">build.gradle</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">testCompile <span class="string"><span class="delimiter">&quot;</span><span class="content">org.grails:grails-test-mixins:3.3.0</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_default_logger_name">Default Logger Name</h3>
<div class="paragraph">
<p>In previous versions of Grails, if you did not specify a logger in the controller, service, etc, a <code>log</code> variable was injected for you. The naming convention of that logger was <code>grails.app.${artefactType}.package.class</code>. For example:</p>
</div>
<div class="paragraph">
<p><code>grails.app.controllers.foo.bar.MyController</code></p>
</div>
<div class="paragraph">
<p>To make the logger names more intuitive as well as to increase consistency between custom code, plugin dependencies, and third party libraries, the <code>grails.app.${artefactType}</code> convention was removed. The same class as above will now be referenced the same way as any standard class. The way the <code>log</code> variable gets injected was also changed to defer to the Slf4j transformation. That means it is no longer necessary to check <code>if (log.isDebugEnabled())</code>.</p>
</div>
<div class="paragraph">
<p>The downside of this change is that it isn&#8217;t immediately simple to set up the same logging configuration for all controllers, for example. We think this can be solved with a package naming strategy that represents what your requirements are.</p>
</div>
</div>
<div class="sect2">
<h3 id="_dependency_alterations">Dependency Alterations</h3>
<div class="paragraph">
<p>In an effort to trim the size of the produced WAR file by Grails several dependencies are no longer resolved transtively including:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>commons-lang</code></p>
</li>
<li>
<p><code>gson</code></p>
</li>
<li>
<p><code>aspectjweaver</code></p>
</li>
<li>
<p><code>aspectjrt</code></p>
</li>
<li>
<p><code>ehcache</code></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>If you are upgrading and have referenced any of these dependencies in your application you may need to alter your build to reference them.</p>
</div>
</div>
<div class="sect2">
<h3 id="_spring_boot_1_5_x">Spring Boot 1.5.x</h3>
<div class="paragraph">
<p>Spring Boot 1.5.x removes a number of deprecated classes, notably several of the classes within the <code>org.springframework.boot.context.embedded</code> package.</p>
</div>
<div class="paragraph">
<p>If your application is referencing any of the classes within this package you will need to alter your imports to use <code>org.springframework.boot.web.servlet</code> instead.</p>
</div>
<div class="paragraph">
<p>All classes in the <code>org.springframework.boot.context.web</code> package have been deprecated and relocated per the Spring Boot 1.4 Release Notes.</p>
</div>
</div>
<div class="sect2">
<h3 id="_reactor_2_x_deprecated_and_removed">Reactor 2.x Deprecated and Removed</h3>
<div class="paragraph">
<p>Since Reactor 2.x is no longer being maintained and a new <a href="https://grails.apache.org/docs/latest/api/grails/events/bus/EventBus.html">EventBus</a> abstraction has been implemented, Reactor 2.x and all its dependencies have been removed.</p>
</div>
<div class="paragraph">
<p>A compatibility layer has been provided to allow classes compiled with the previous version that uses Reactor to run, however all plugins and application code should be re-compiled and direct references to Reactor 2.x should be removed.</p>
</div>
</div>
<div class="sect2">
<h3 id="_externalized_plugins">Externalized Plugins</h3>
<div class="paragraph">
<p>Several plugins and libraries have been separated from Grails core into standalone projects. The following table summarizes the previous artefact id, the new artefact id and the location of the new sources:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<caption class="title">Table 1. Externalized Plugins</caption>
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">Sources</th>
<th class="tableblock halign-left valign-top">Previous Artefact ID</th>
<th class="tableblock halign-left valign-top">New Artefact ID</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://github.com/grails/grails-gsp">GSP</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>org.grails:grails-plugin-gsp</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>org.grails.plugins:gsp</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://github.com/grails-plugins/grails-plugin-converters">Converters</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>org.grails:grails-plugin-converters</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>org.grails.plugins:converters</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://github.com/grails/grails-async">Async</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>org.grails:grails-plugin-async</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>org.grails.plugins:async</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://github.com/grails/grails-async">Events</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>org.grails:grails-plugin-events</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>org.grails.plugins:events</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://github.com/grails-plugins/grails-test-mixin-plugin">Testing Mixin</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>org.grails:grails-plugin-testing</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>org.grails:grails-test-mixins</code></p></td>
</tr>
</tbody>
</table>
</div>
<div class="sect2">
<h3 id="_new_cache_plugin">New Cache Plugin</h3>
<div class="paragraph">
<p>The Cache plugin has been re-written to no longer use Spring proxies but AST transformations instead.</p>
</div>
<div class="paragraph">
<p>This improves startup and runtime performance, however one caveat is controller action response caching is no longer supported.</p>
</div>
</div>
<div class="sect2">
<h3 id="_grails_domain_class_api_deprecated">Grails Domain Class API Deprecated</h3>
<div class="paragraph">
<p>The legacy classes that represent domain classes and their properties have been deprecated in favor of the mapping context API.</p>
</div>
<div class="paragraph">
<p>The reason for this is to avoid duplicate parsing of the same class data between GORM and Grails and reduce overall startup time.</p>
</div>
<div class="paragraph">
<p>The internal implementation of the methods in those classes now delegates to the mapping context. Due to that change, information about your domain classes is not available until the application context is available.</p>
</div>
<div class="paragraph">
<p>In previous versions of Grails it was possible to access <a href="https://grails.apache.org/docs/latest/api/grails/core/GrailsDomainClass.html">GrailsDomainClass</a> instances and inspect the <a href="https://grails.apache.org/docs/latest/api/grails/core/GrailsDomainClassProperty.html">GrailsDomainClassProperty</a> properties inside of the <code>doWithSpring</code> method in a plugin, for example.</p>
</div>
<div class="paragraph">
<p>If you have code that follows that example, an error will be thrown that looks like "The method &#8230;&#8203; cannot be accessed before GORM has initialized". The solution is to move any logic that executes before the context is available to somewhere else that executes after the context is available.</p>
</div>
<div class="paragraph">
<p>All code that uses the <a href="https://grails.apache.org/docs/latest/api/grails/core/GrailsDomainClass.html">GrailsDomainClass</a> or <a href="https://grails.apache.org/docs/latest/api/grails/core/GrailsDomainClassProperty.html">GrailsDomainClassProperty</a> classes should be re-written to use the mapping context api.</p>
</div>
<div class="paragraph">
<p>To get started, inject the <code>grailsDomainClassMappingContext</code> bean. See the api documentation for more information on the <a href="https://grails.apache.org/docs/latest/api/org/grails/datastore/mapping/model/MappingContext.html">MappingContext</a>, <a href="https://grails.apache.org/docs/latest/api/org/grails/datastore/mapping/model/PersistentEntity.html">PersistentEntity</a> (GrailsDomainClass), and <a href="https://grails.apache.org/docs/latest/api/org/grails/datastore/mapping/model/PersistentProperty.html">PersistentProperty</a> (GrailsDomainClassProperty).</p>
</div>
<div class="paragraph">
<p>The following table summarizes the deprecations:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<caption class="title">Table 2. Deprecated Grails Domain Class API</caption>
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">Deprecated Class or Interface</th>
<th class="tableblock halign-left valign-top">Replacement</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/api/grails/core/GrailsDomainClass.html">GrailsDomainClass</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/api/org/grails/datastore/mapping/model/PersistentEntity.html">PersistentEntity</a></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/api/grails/core/GrailsDomainClassProperty.html">GrailsDomainClassProperty</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/api/org/grails/datastore/mapping/model/PersistentProperty.html">PersistentProperty</a></p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>The <code>GrailsDomainClassProperty</code> interface had many more methods to evaluate the type of the property such as <code>isOneToOne</code>, <code>isOneToMany</code> etc. and while <code>PersistentProperty</code> does not provide direct equivalents you can use <code>instanceof</code> as a replacement using one of the subclasses found in the <a href="https://grails.apache.org/docs/latest/api/org/grails/datastore/mapping/model/types/package-summary.html">org.grails.datastore.mapping.model.types</a> package.</p>
</div>
<div class="paragraph">
<p>The following table summarizes this:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<caption class="title">Table 3. Deprecated GrailsDomainClassProperty method replacements</caption>
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">Deprecated Class or Interface</th>
<th class="tableblock halign-left valign-top">Replacement</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>isAssociation()</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>property instanceof Association</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>isOneToOne()</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>property instanceof OneToOne</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>isManyToOne()</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>property instanceof ManyToOne</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>isEmbedded()</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>property instanceof Embedded</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>isManyToMany()</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>property instanceof ManyToMany</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>isBasicCollectionType()</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>property instanceof Basic</code></p></td>
</tr>
</tbody>
</table>
</div>
<div class="sect2">
<h3 id="_grails_validator_and_constrainedproperty_api_deprecated">Grails Validator and ConstrainedProperty API Deprecated</h3>
<div class="paragraph">
<p>Grails' previous validation API (part of the <code>grails.validation</code> package) has been externalized into a separate project not part of the <code>grails-datastore-gorm-validation</code> dependency.</p>
</div>
<div class="paragraph">
<p>This means that some interfaces previously part of Grails core are deprecated and the replacment in the external project should be used, including:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<caption class="title">Table 4. Deprecated Grails Validator Classes</caption>
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">Deprecated Class or Interface</th>
<th class="tableblock halign-left valign-top">Replacement</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/api/org/grails/validation/GrailsDomainClassValidator.html">GrailsDomainClassValidator</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/api/grails/gorm/validation/PersistentEntityValidator.html">PersistentEntityValidator</a></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/api/grails/validation/CascadingValidator.html">CascadingValidator</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/api/grails/gorm/validation/CascadingValidator.html">CascadingValidator</a></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/api/grails/validation/ConstrainedProperty.html">ConstrainedProperty</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/api/grails/gorm/validation/ConstrainedProperty.html">ConstrainedProperty</a></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/api/grails/validation/Constraint.html">Constraint</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/api/grails/gorm/validation/Constraint.html">Constraint</a></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/api/grails/validation/AbstractConstraint.html">AbstractConstraint</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/api/org/grails/datastore/gorm/validation/constraints/AbstractConstraint.html">AbstractConstraint</a></p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>Generally all classes within the <code>org.grails.validation</code> package are now deprecated.</p>
</div>
<div class="paragraph">
<p>To register a custom constraint you should now use the <a href="https://grails.apache.org/docs/latest/api/org/grails/datastore/gorm/validation/constraints/registry/ConstraintRegistry.html">ConstraintRegistry</a> interface instead.</p>
</div>
<div class="paragraph">
<p>The default <a href="https://grails.apache.org/docs/latest/api/org/grails/datastore/mapping/validation/ValidatorRegistry.html">ValidatorRegistry</a> implements the <code>ConstraintRegistry</code> interface and can be autowired into any controller or service by declaring the following property:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">ValidatorRegistry gormValidatorRegistry
...
gormValidatorRegistry.addConstraint(MyConstraint)</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_grails_transactional_ast_transforms_deprecated">Grails' Transactional AST Transforms Deprecated</h3>
<div class="paragraph">
<p>The transaction management AST transforms that shipped as part of Grails have been ported to GORM and improved to make it possible to use them outside of Grails.</p>
</div>
<div class="paragraph">
<p>With this in mind Grails' versions of <code>@Transactional</code> and <code>@Rollback</code> found within the <code>grails.transaction</code> package have been deprecated in favour of GORMs versions. You should change your imports to use the GORM version instead of the Grails version.</p>
</div>
<div class="paragraph">
<p>The following table summarizes the deprecated classes and their replacements:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<caption class="title">Table 5. Deprecated Grails Transaction Transforms</caption>
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">Deprecated Class or Interface</th>
<th class="tableblock halign-left valign-top">Replacement</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/api/grails/transaction/Transactional.html">grails.transaction.Transactional</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/api/grails/gorm/transactions/Transactional.html">grails.gorm.transactions.Transactional</a></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/api/grails/transaction/Rollback.html">grails.transaction.Rollback</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/api/grails/gorm/transactions/Rollback.html">grails.gorm.transactions.Rollback</a></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/api/grails/transaction/NotTransactional.html">grails.transaction.NotTransactional</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/latest/api/grails/gorm/transactions/NotTransactional.html">grails.gorm.transactions.NotTransactional</a></p></td>
</tr>
</tbody>
</table>
</div>
<div class="sect2">
<h3 id="_spring_proxies_for_services_no_longer_supported">Spring Proxies for Services No Longer Supported</h3>
<div class="paragraph">
<p>Earlier versions of Grails supported the use of Spring proxies for transaction management, but this support was disabled by default in Grails 3.2.x and developers encouraged to use the <code>@Transactional</code> AST transforms instead.</p>
</div>
<div class="paragraph">
<p>In Grails 3.3 the support for Spring proxies has been dropped completely and you must use Grails' AST transforms.</p>
</div>
<div class="paragraph">
<p>If you wish to continue to use Spring proxies for transaction management you will have to configure them manually use the appropriate Spring configuration.</p>
</div>
</div>
<div class="sect2">
<h3 id="_datasource_plugin_refactor">Datasource Plugin Refactor</h3>
<div class="paragraph">
<p>In previous versions of Grails and GORM the multiple data sources support relied on Grails' data sources plugin. The logic for configuring multiple data sources has moved to GORM and as a result of major changes to the dataSources plugin, beans for the lazy and unproxied representation of a dataSource are no longer available.</p>
</div>
<div class="paragraph">
<p>The beans include:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>dataSourceUnproxied</code></p>
</li>
<li>
<p><code>dataSourceLazy</code></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>If you are referencing these beans you will need to remove these references and unwrap the single <code>dataSource</code> proxy manually.</p>
</div>
</div>
<div class="sect2">
<h3 id="_task_groups">Task Groups</h3>
<div class="paragraph">
<p>Several tasks have had their groups changed to better reflect their purpose. If you&#8217;re having trouble finding a task, look through the different groups.</p>
</div>
</div>
<div class="sect2">
<h3 id="_legacy_json_builder_option_removed">Legacy JSON Builder Option Removed</h3>
<div class="paragraph">
<p>In a previous version of Grails, the JSON builder used by default for rendering JSON inline was changed. The previous behavior of using converters to build the JSON was able to be re-enabled by setting <code>grails.json.legacy.builder</code> to true. In Grails 3.3 that setting has been removed and it is no longer possible to use the legacy converter API to render JSON inline via the <code>render</code> method.</p>
</div>
</div>
<a name="3. Configuration"><!-- Legacy link --></a>
<h1 id="conf">4 Configuration</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>It may seem odd that in a framework that embraces "convention-over-configuration" that we tackle this topic now. With Grails' default settings you can actually develop an application without doing any configuration whatsoever, as the quick start demonstrates, but it&#8217;s important to learn where and how to override the conventions when you need to. Later sections of the user guide will mention what configuration settings you can use, but not how to set them. The assumption is that you have at least read the first section of this chapter!</p>
</div>
<a name="3.1 Basic Configuration"><!-- Legacy link --></a>
<h2 id="config">4.1 Basic Configuration</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/config.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Configuration in Grails is generally split across 2 areas: build configuration and runtime configuration.</p>
</div>
<div class="paragraph">
<p>Build configuration is generally done via Gradle and the <code>build.gradle</code> file. Runtime configuration is by default specified in YAML in the <code>grails-app/conf/application.yml</code> file.</p>
</div>
<div class="paragraph">
<p>If you prefer to use Grails 2.0-style Groovy configuration then it is possible to specify configuration using Groovy&#8217;s <a href="http://docs.groovy-lang.org/latest/html/documentation/#_configslurper">ConfigSlurper</a> syntax. Two Groovy configuration files are available: <code>grails-app/conf/application.groovy</code> and <code>grails-app/conf/runtime.groovy</code>:</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Use <code>application.groovy</code> for configuration that doesn&#8217;t depend on application classes</p>
</li>
<li>
<p>Use <code>runtime.groovy</code> for configuration that does depend on application classes</p>
</li>
</ol>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>This separation is necessary because configuration values defined in <code>application.groovy</code> are available to the Grails CLI, which needs to be able to load <code>application.groovy</code> before the application has been compiled. References to application classes in <code>application.groovy</code> will cause an exception when these commands are executed by the CLI:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>Error occurred running Grails CLI:
startup failed:script14738267015581837265078.groovy: 13: unable to resolve class com.foo.Bar</pre>
</div>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>For Groovy configuration the following variables are available to the configuration script:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top"><strong>Variable</strong></th>
<th class="tableblock halign-left valign-top"><strong>Description</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">userHome</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Location of the home directory for the account that is running the Grails application.</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">grailsHome</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Location of the directory where you installed Grails. If the <code>GRAILS_HOME</code> environment variable is set, it is used.</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">appName</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">The application name as it appears in build.gradle.</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">appVersion</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">The application version as it appears in build.gradle.</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">my.tmp.dir = <span class="string"><span class="delimiter">&quot;</span><span class="inline"><span class="inline-delimiter">${</span>userHome<span class="inline-delimiter">}</span></span><span class="content">/.grails/tmp</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>If you want to read runtime configuration settings, i.e. those defined in <code>application.yml</code>, use the <a href="https://grails.apache.org/docs/3.3.7/api/grails/core/GrailsApplication.html">grailsApplication</a> object, which is available as a variable in controllers and tag libraries:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">MyController</span> {
<span class="keyword">def</span> <span class="function">hello</span>() {
<span class="keyword">def</span> recipient = grailsApplication.config.getProperty(<span class="string"><span class="delimiter">'</span><span class="content">foo.bar.hello</span><span class="delimiter">'</span></span>)
render <span class="string"><span class="delimiter">&quot;</span><span class="content">Hello </span><span class="inline"><span class="inline-delimiter">${</span>recipient<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>config</code> property of the <code>grailsApplication</code> object is an instance of the <a href="https://grails.apache.org/docs/3.3.7/api/grails/config/Config.html">Config</a> interface and provides a number of useful methods to read the configuration of the application.</p>
</div>
<div class="paragraph">
<p>In particular, the <code>getProperty</code> method (seen above) is useful for efficiently retrieving configuration properties, while specifying the property type (the default type is String) and/or providing a default fallback value.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">MyController</span> {
<span class="keyword">def</span> <span class="function">hello</span>(Recipient recipient) {
<span class="comment">//Retrieve Integer property 'foo.bar.max.hellos', otherwise use value of 5</span>
<span class="keyword">def</span> max = grailsApplication.config.getProperty(<span class="string"><span class="delimiter">'</span><span class="content">foo.bar.max.hellos</span><span class="delimiter">'</span></span>, <span class="predefined-type">Integer</span>, <span class="integer">5</span>)
<span class="comment">//Retrieve property 'foo.bar.greeting' without specifying type (default is String), otherwise use value &quot;Hello&quot;</span>
<span class="keyword">def</span> greeting = grailsApplication.config.getProperty(<span class="string"><span class="delimiter">'</span><span class="content">foo.bar.greeting</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">&quot;</span><span class="content">Hello</span><span class="delimiter">&quot;</span></span>)
<span class="keyword">def</span> message = (recipient.receivedHelloCount &gt;= max) ?
<span class="string"><span class="delimiter">&quot;</span><span class="content">Sorry, you've been greeted the max number of times</span><span class="delimiter">&quot;</span></span> : <span class="string"><span class="delimiter">&quot;</span><span class="inline"><span class="inline-delimiter">${</span>greeting<span class="inline-delimiter">}</span></span><span class="content">, </span><span class="inline"><span class="inline-delimiter">${</span>recipient<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>
}
render message
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Notice that the <code>Config</code> instance is a merged configuration based on Spring&#8217;s <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/PropertySource.html">PropertySource</a> concept and reads configuration from the environment, system properties and the local application configuration merging them into a single object.</p>
</div>
<div class="paragraph">
<p><code>GrailsApplication</code> can be easily injected into services and other Grails artifacts:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.core.*</span>
<span class="type">class</span> <span class="class">MyService</span> {
GrailsApplication grailsApplication
<span class="predefined-type">String</span> greeting() {
<span class="keyword">def</span> recipient = grailsApplication.config.getProperty(<span class="string"><span class="delimiter">'</span><span class="content">foo.bar.hello</span><span class="delimiter">'</span></span>)
<span class="keyword">return</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">Hello </span><span class="inline"><span class="inline-delimiter">${</span>recipient<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Finally, you can also use Spring&#8217;s <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Value.html">Value</a> annotation to inject configuration values:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">org.springframework.beans.factory.annotation.*</span>
<span class="type">class</span> <span class="class">MyController</span> {
<span class="annotation">@Value</span>(<span class="string"><span class="delimiter">'</span><span class="content">${foo.bar.hello}</span><span class="delimiter">'</span></span>)
<span class="predefined-type">String</span> recipient
<span class="keyword">def</span> <span class="function">hello</span>() {
render <span class="string"><span class="delimiter">&quot;</span><span class="content">Hello </span><span class="inline"><span class="inline-delimiter">${</span>recipient<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>
}
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
In Groovy code you must use single quotes around the string for the value of the <code>Value</code> annotation otherwise it is interpreted as a GString not a Spring expression.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>As you can see, when accessing configuration settings you use the same dot notation as when you define them.</p>
</div>
<h2 id="ymlOptions">4.1.1 Options for the YML format Config</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/config/ymlOptions.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p><code>application.yml</code> was introduced in Grails 3.0 for an alternative format for the configuration tasks.</p>
</div>
<div class="sect2">
<h3 id="_using_system_properties_command_line_arguments">Using system properties / command line arguments</h3>
<div class="paragraph">
<p>Suppose you are using the <code>JDBC_CONNECTION_STRING</code> command line argument and you want to access the same in the yml file then it can be done in the following manner:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">production</span>:
<span class="key">dataSource</span>:
<span class="key">url</span>: <span class="string"><span class="content">'${JDBC_CONNECTION_STRING}'</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Similarly system arguments can be accessed.</p>
</div>
<div class="paragraph">
<p>You will need to have this in <code>build.gradle</code> to modify the <code>bootRun</code> target if <code>grails run-app</code> is used to start the application</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">bootRun {
systemProperties = <span class="predefined-type">System</span>.properties
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>For testing the following will need to change the <code>test</code> task as follows</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">test {
systemProperties = <span class="predefined-type">System</span>.properties
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_external_configuration">External configuration</h3>
<div class="paragraph">
<p>Grails will read <code>application.(properties|yml)</code> from the <code>./config</code> or the current directory by default.
As Grails is a SpringBoot configuration options are available as well, for documentation please consult: <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-application-property-files" class="bare">https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-application-property-files</a></p>
</div>
</div>
<a name="3.1.1 Built in options"><!-- Legacy link --></a>
<h2 id="builtInOptions">4.1.2 Built in options</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/config/builtInOptions.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails has a set of core settings that are worth knowing about. Their defaults are suitable for most projects, but it&#8217;s important to understand what they do because you may need one or more of them later.</p>
</div>
<div class="sect2">
<h3 id="_runtime_settings">Runtime settings</h3>
<div class="paragraph">
<p>On the runtime front, i.e. <code>grails-app/conf/application.yml</code>, there are quite a few more core settings:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>grails.enable.native2ascii</code> - Set this to false if you do not require native2ascii conversion of Grails i18n properties files (default: true).</p>
</li>
<li>
<p><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'.</p>
</li>
<li>
<p><code>grails.views.gsp.encoding</code> - The file encoding used for GSP source files (default: 'utf-8').</p>
</li>
<li>
<p><code>grails.mime.file.extensions</code> - Whether to use the file extension to dictate the mime type in <a href="theWebLayer.html#contentNegotiation">Content Negotiation</a> (default: true).</p>
</li>
<li>
<p><code>grails.mime.types</code> - A map of supported mime types used for <a href="theWebLayer.html#contentNegotiation">Content Negotiation</a>.</p>
</li>
<li>
<p><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="http://gsp.grails.org/latest/ref/Tags/createLink.html">createLink</a>. Also used by redirects.</p>
</li>
<li>
<p><code>grails.views.gsp.sitemesh.preprocess</code> - Determines whether SiteMesh preprocessing happens. Disabling this slows down page rendering, but if you need SiteMesh to parse the generated HTML from a GSP view then disabling it is the right option. Don&#8217;t worry if you don&#8217;t understand this advanced property: leave it set to true.</p>
</li>
<li>
<p><code>grails.reload.excludes</code> and <code>grails.reload.includes</code> - Configuring these directives determines the reload behavior for project specific source files. Each directive takes a list of strings that are the class names for project source files that should be excluded from reloading behavior or included accordingly when running the application in development with the <code>run-app</code> command. If the <code>grails.reload.includes</code> directive is configured, then only the classes in that list will be reloaded.</p>
</li>
</ul>
</div>
</div>
<a name="3.1.2 Logging"><!-- Legacy link --></a>
<h2 id="logging">4.1.3 Logging</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/config/logging.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>By default logging in Grails 3.0 is handled by the <a href="http://logback.qos.ch">Logback logging framework</a> and can be configured with the <code>grails-app/conf/logback.groovy</code> file.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
If you prefer XML you can replace the <code>logback.groovy</code> file with a <code>logback.xml</code> file instead.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>For more information on configuring logging refer to the <a href="http://logback.qos.ch/manual/groovy.html">Logback documentation</a> on the subject.</p>
</div>
<h2 id="loggerName">4.1.3.1 Logger Names</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/config/logging/loggerName.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails artifacts (controllers, services &#8230;&#8203;) get injected a <code>log</code> property automatically.</p>
</div>
<div class="paragraph">
<p>Prior to Grails 3.3.0, the name of the
logger for Grails Artifact followed the convention <code>grails.app.&lt;type&gt;.&lt;className&gt;</code>, where type is the
type of the artifact, for example, <code>controllers</code> or <code>services</code>, and <code>className</code> is the fully
qualified name of the artifact.</p>
</div>
<div class="paragraph">
<p>Grails 3.3.x simplifies logger names. The next examples illustrate the changes:</p>
</div>
<div class="paragraph">
<p><code>BookController.groovy</code> located at <code>grails-app/controllers/com/company</code> NOT annotated with <code><a href="http://docs.groovy-lang.org/latest/html/gapi/groovy/util/logging/Slf4j.html">@Slf4j</a></code></p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><strong>Logger Name (Grails 3.3.x or higher)</strong></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><strong>Logger Name (Grails 3.2.x or lower)</strong></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>com.company.BookController</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>grails.app.controllers.com.company.BookController</code></p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p><code>BookController.groovy</code> located at <code>grails-app/controllers/com/company</code> annotated with <code><a href="http://docs.groovy-lang.org/latest/html/gapi/groovy/util/logging/Slf4j.html">@Slf4j</a></code></p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><strong>Logger Name (Grails 3.3.x or higher)</strong></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><strong>Logger Name (Grails 3.2.x or lower)</strong></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>com.company.BookController</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>com.company.BookController</code></p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p><code>BookService.groovy</code> located at <code>grails-app/services/com/company</code> NOT annotated with <code><a href="http://docs.groovy-lang.org/latest/html/gapi/groovy/util/logging/Slf4j.html">@Slf4j</a></code></p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><strong>Logger Name (Grails 3.3.x or higher)</strong></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><strong>Logger Name (Grails 3.2.x or lower)</strong></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>com.company.BookService</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>grails.app.services.com.company.BookService</code></p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p><code>BookService.groovy</code> located at <code>grails-app/services/com/company</code> annotated with <code><a href="http://docs.groovy-lang.org/latest/html/gapi/groovy/util/logging/Slf4j.html">@Slf4j</a></code></p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><strong>Logger Name (Grails 3.3.x or higher)</strong></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><strong>Logger Name (Grails 3.2.x or lower)</strong></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>com.company.BookService</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>com.company.BookService</code></p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p><code>BookDetail.groovy</code> located at <code>src/main/groovy/com/company</code> annotated with <code><a href="http://docs.groovy-lang.org/latest/html/gapi/groovy/util/logging/Slf4j.html">@Slf4j</a></code></p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><strong>Logger Name (Grails 3.3.x or higher)</strong></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><strong>Logger Name (Grails 3.2.x or lower)</strong></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>com.company.BookDetail</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>com.company.BookDetail</code></p></td>
</tr>
</tbody>
</table>
<h2 id="maskingRequestParametersFromStacktraceLogs">4.1.3.2 Masking Request Parameters From Stacktrace Logs</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/config/logging/maskingRequestParametersFromStacktraceLogs.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/application.yaml</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">grails</span>:
<span class="key">exceptionresolver</span>:
<span class="key">params</span>:
<span class="key">exclude</span>:
- <span class="string"><span class="content">password</span></span>
- <span class="string"><span class="content">creditCard</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Request parameter logging may be turned off altogether by setting the <code>grails.exceptionresolver.logRequestParameters</code>
config property to false. The default value is true when the application is running in DEVELOPMENT mode and false for all other
environments.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/application.yaml</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">grails</span>:
<span class="key">exceptionresolver</span>:
<span class="key">logRequestParameters</span>: <span class="string"><span class="content">false</span></span></code></pre>
</div>
</div>
<h2 id="externalLoggingConfiguration">4.1.3.3 External Configuration File</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/config/logging/externalLoggingConfiguration.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>If you set the configuration property <code>logging.config</code>, you can instruct <code>Logback</code> to use an external configuration file.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/application.yml</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">logging</span>:
<span class="key">config</span>: <span class="string"><span class="content">/Users/me/config/logback.groovy</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Alternatively, you can supply the configuration file location with a system property:</p>
</div>
<div class="paragraph">
<p><code>$ ./gradlew -Dlogging.config=/Users/me/config/logback.groovy bootRun</code></p>
</div>
<div class="paragraph">
<p>Or, you could use an environment variable:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ export LOGGING_CONFIG=/Users/me/config/logback.groovy
$ ./gradlew bootRun</code></pre>
</div>
</div>
<a name="3.1.3 GORM"><!-- Legacy link --></a>
<h2 id="configGORM">4.1.4 GORM</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/config/configGORM.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails provides the following GORM configuration options:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><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="validation.html">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%20Classes/save.html">save</a> method docs for more information.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>For example, to enable failOnError for all domain classes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">grails</span>:
<span class="key">gorm</span>:
<span class="key">failOnError</span>: <span class="string"><span class="content">true</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>and to enable failOnError for domain classes by package:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">grails</span>:
<span class="key">gorm</span>:
<span class="key">failOnError</span>:
- <span class="string"><span class="content">com.companyname.somepackage</span></span>
- <span class="string"><span class="content">com.companyname.someotherpackage</span></span></code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p><code>grails.gorm.autoFlush</code> - If set to <code>true</code>, causes the <a href="../ref/Domain%20Classes/merge.html">merge</a>, <a href="../ref/Domain%20Classes/save.html">save</a> and <a href="../ref/Domain%20Classes/delete.html">delete</a> methods to flush the session, replacing the need to explicitly flush using <code>save(flush: true)</code>.</p>
</li>
</ul>
</div>
<h2 id="proxyConfig">4.1.5 Configuring an HTTP proxy</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/config/proxyConfig.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>To setup Grails to use an HTTP proxy there are two steps. Firstly you need to configure the <code>grails</code> CLI to be aware of the proxy if you wish to use it to create applications and so on. This can be done using the <code>GRAILS_OPTS</code> environment variable, for example on Unix systems:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">export GRAILS_OPTS=&quot;-Dhttps.proxyHost=127.0.0.1 -Dhttps.proxyPort=3128 -Dhttp.proxyUser=test -Dhttp.proxyPassword=test&quot;</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The default profile repository is resolved over HTTPS so <code>https.proxyPort</code> and <code>https.proxyUser</code> are used, however the username and password are specified with <code>http.proxyUser</code> and <code>http.proxyPassword</code>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>For Windows systems the environment variable can be configured under <code>My Computer/Advanced/Environment Variables</code>.</p>
</div>
<div class="paragraph">
<p>With this configuration in place the <code>grails</code> command can connect and authenticate via a proxy.</p>
</div>
<div class="paragraph">
<p>Secondly, since Grails uses Gradle as the build system, you need to configure Gradle to authenticate via the proxy. For instructions on how to do this see the <a href="https://docs.gradle.org/current/userguide/build_environment.html#sec:accessing_the_web_via_a_proxy">Gradle user guide section on the topic</a>.</p>
</div>
<h2 id="applicationClass">4.2 The Application Class</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/applicationClass.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Every new Grails application features an <code>Application</code> class within the <code>grails-app/init</code> directory.</p>
</div>
<div class="paragraph">
<p>The <code>Application</code> class subclasses the <a href="https://grails.apache.org/docs/3.3.7/api/grails/boot/config/GrailsAutoConfiguration.html">GrailsAutoConfiguration</a> class and features a <code>static void main</code> method, meaning it can be run as a regular application.</p>
</div>
<h2 id="executing">4.2.1 Executing the Application Class</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/applicationClass/executing.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>There are several ways to execute the <code>Application</code> class, if you are using an IDE then you can simply right click on the class and run it directly from your IDE which will start your Grails application.</p>
</div>
<div class="paragraph">
<p>This is also useful for debugging since you can debug directly from the IDE without having to connect a remote debugger when using the <code>run-app --debug-jvm</code> command from the command line.</p>
</div>
<div class="paragraph">
<p>You can also package your application into a runnable WAR file, for example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails package
$ java -jar build/libs/myapp-0.1.war</code></pre>
</div>
</div>
<div class="paragraph">
<p>This is useful if you plan to deploy your application using a container-less approach.</p>
</div>
<h2 id="customizing">4.2.2 Customizing the Application Class</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/applicationClass/customizing.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>There are several ways in which you can customize the <code>Application</code> class.</p>
</div>
<div class="sect2">
<h3 id="_customizing_scanning">Customizing Scanning</h3>
<div class="paragraph">
<p>By default Grails will scan all known source directories for controllers, domain class etc., however if there are packages in other JAR files you wish to scan you can do so by overriding the <code>packageNames()</code> method of the <code>Application</code> class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Application</span> <span class="directive">extends</span> GrailsAutoConfiguration {
<span class="annotation">@Override</span>
<span class="predefined-type">Collection</span>&lt;<span class="predefined-type">String</span>&gt; packageNames() {
<span class="local-variable">super</span>.packageNames() + [<span class="string"><span class="delimiter">'</span><span class="content">my.additional.package</span><span class="delimiter">'</span></span>]
}
...
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_registering_additional_beans">Registering Additional Beans</h3>
<div class="paragraph">
<p>The <code>Application</code> class can also be used as a source for Spring bean definitions, simply define a method annotated with the <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Bean.html">Bean</a> and the returned object will become a Spring bean. The name of the method is used as the bean name:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Application</span> <span class="directive">extends</span> GrailsAutoConfiguration {
<span class="annotation">@Bean</span>
MyType myBean() {
<span class="keyword">return</span> <span class="keyword">new</span> MyType()
}
...
}</code></pre>
</div>
</div>
</div>
<h2 id="applicationLifeCycle">4.2.3 The Application LifeCycle</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/applicationClass/applicationLifeCycle.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>The <code>Application</code> class also implements the <a href="https://grails.apache.org/docs/3.3.7/api/grails/core/GrailsApplicationLifeCycle.html">GrailsApplicationLifeCycle</a> interface which all plugins implement.</p>
</div>
<div class="paragraph">
<p>This means that the <code>Application</code> class can be used to perform the same functions as a plugin. You can override the <a href="plugins.html#hookingIntoRuntimeConfiguration">regular plugins hooks</a> such as <code>doWithSpring</code>, <code>doWithApplicationContext</code> and so on by overriding the appropriate method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Application</span> <span class="directive">extends</span> GrailsAutoConfiguration {
<span class="annotation">@Override</span>
Closure doWithSpring() {
{-&gt;
mySpringBean(MyType)
}
}
...
}</code></pre>
</div>
</div>
<a name="3.2 Environments"><!-- Legacy link --></a>
<h2 id="environments">4.3 Environments</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/environments.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect2">
<h3 id="_per_environment_configuration">Per Environment Configuration</h3>
<div class="paragraph">
<p>Grails supports the concept of per environment configuration. The <code>application.yml</code> and <code>application.groovy</code> files in the <code>grails-app/conf</code> directory can use per-environment configuration using either YAML or the syntax provided by <a href="http://docs.groovy-lang.org/latest/html/documentation/#_configslurper">ConfigSlurper</a>. As an example consider the following default <code>application.yml</code> definition provided by Grails:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">environments</span>:
<span class="key">development</span>:
<span class="key">dataSource</span>:
<span class="key">dbCreate</span>: <span class="string"><span class="content">create-drop</span></span>
<span class="key">url</span>: <span class="string"><span class="content">jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE</span></span>
<span class="key">test</span>:
<span class="key">dataSource</span>:
<span class="key">dbCreate</span>: <span class="string"><span class="content">update</span></span>
<span class="key">url</span>: <span class="string"><span class="content">jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE</span></span>
<span class="key">production</span>:
<span class="key">dataSource</span>:
<span class="key">dbCreate</span>: <span class="string"><span class="content">update</span></span>
<span class="key">url</span>: <span class="string"><span class="content">jdbc:h2:prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE</span></span>
<span class="key">properties</span>:
<span class="key">jmxEnabled</span>: <span class="string"><span class="content">true</span></span>
<span class="key">initialSize</span>: <span class="string"><span class="content">5</span></span>
<span class="error">...</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The above can be expressed in Groovy syntax in <code>application.groovy</code> as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">dataSource {
pooled = <span class="predefined-constant">false</span>
driverClassName = <span class="string"><span class="delimiter">&quot;</span><span class="content">org.h2.Driver</span><span class="delimiter">&quot;</span></span>
username = <span class="string"><span class="delimiter">&quot;</span><span class="content">sa</span><span class="delimiter">&quot;</span></span>
password = <span class="string"><span class="delimiter">&quot;</span><span class="delimiter">&quot;</span></span>
}
environments {
development {
dataSource {
dbCreate = <span class="string"><span class="delimiter">&quot;</span><span class="content">create-drop</span><span class="delimiter">&quot;</span></span>
url = <span class="string"><span class="delimiter">&quot;</span><span class="content">jdbc:h2:mem:devDb</span><span class="delimiter">&quot;</span></span>
}
}
test {
dataSource {
dbCreate = <span class="string"><span class="delimiter">&quot;</span><span class="content">update</span><span class="delimiter">&quot;</span></span>
url = <span class="string"><span class="delimiter">&quot;</span><span class="content">jdbc:h2:mem:testDb</span><span class="delimiter">&quot;</span></span>
}
}
production {
dataSource {
dbCreate = <span class="string"><span class="delimiter">&quot;</span><span class="content">update</span><span class="delimiter">&quot;</span></span>
url = <span class="string"><span class="delimiter">&quot;</span><span class="content">jdbc:h2:prodDb</span><span class="delimiter">&quot;</span></span>
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
</div>
<div class="sect2">
<h3 id="_packaging_and_running_for_different_environments">Packaging and Running for Different Environments</h3>
<div class="paragraph">
<p>Grails' <a href="commandLine.html">command line</a> has built in capabilities to execute any command within the context of a specific environment. The format is:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">grails &lt;&lt;environment&gt;&gt; &lt;&lt;command name&gt;&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>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 would run:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">grails test war</code></pre>
</div>
</div>
<div class="paragraph">
<p>To target other environments you can pass a <code>grails.env</code> variable to any command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">grails -Dgrails.env=UAT run-app</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_programmatic_environment_detection">Programmatic Environment Detection</h3>
<div class="paragraph">
<p>Within your code, such as in a Gant script or a bootstrap class you can detect the environment using the <a href="https://grails.apache.org/docs/3.3.7/api/grails/util/Environment.html">Environment</a> class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.util.Environment</span>
...
switch (Environment.current) {
<span class="keyword">case</span> Environment.DEVELOPMENT:
configureForDevelopment()
<span class="keyword">break</span>
<span class="keyword">case</span> Environment.PRODUCTION:
configureForProduction()
<span class="keyword">break</span>
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_per_environment_bootstrapping">Per Environment Bootstrapping</h3>
<div class="paragraph">
<p>It&#8217;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/init/BootStrap.groovy</code> file&#8217;s support for per-environment execution:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> init = { ServletContext ctx -&gt;
environments {
production {
ctx.setAttribute(<span class="string"><span class="delimiter">&quot;</span><span class="content">env</span><span class="delimiter">&quot;</span></span>, <span class="string"><span class="delimiter">&quot;</span><span class="content">prod</span><span class="delimiter">&quot;</span></span>)
}
development {
ctx.setAttribute(<span class="string"><span class="delimiter">&quot;</span><span class="content">env</span><span class="delimiter">&quot;</span></span>, <span class="string"><span class="delimiter">&quot;</span><span class="content">dev</span><span class="delimiter">&quot;</span></span>)
}
}
ctx.setAttribute(<span class="string"><span class="delimiter">&quot;</span><span class="content">foo</span><span class="delimiter">&quot;</span></span>, <span class="string"><span class="delimiter">&quot;</span><span class="content">bar</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_generic_per_environment_execution">Generic Per Environment Execution</h3>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">Environment.executeForCurrentEnvironment {
production {
<span class="comment">// do something in production</span>
}
development {
<span class="comment">// do something only in development</span>
}
}</code></pre>
</div>
</div>
</div>
<a name="3.3 The DataSource"><!-- Legacy link --></a>
<h2 id="dataSource">4.4 The DataSource</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/dataSource.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Since Grails is built on Java technology setting up a data source requires some knowledge of JDBC (the technology that stands for Java Database Connectivity).</p>
</div>
<div class="paragraph">
<p>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/">Connector/J</a>.</p>
</div>
<div class="paragraph">
<p>Drivers typically come in the form of a JAR archive. It&#8217;s best to use the dependency resolution to resolve the jar if it&#8217;s available in a Maven repository, for example you could add a dependency for the MySQL driver like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">dependencies {
runtime <span class="string"><span class="delimiter">'</span><span class="content">mysql:mysql-connector-java:5.1.29</span><span class="delimiter">'</span></span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Once you have the JAR resolved you need to get familiar with how Grails manages its database configuration. The configuration can be maintained in either <code>grails-app/conf/application.groovy</code> or <code>grails-app/conf/application.yml</code>. These files contain the dataSource definition which includes the following settings:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>driverClassName</code> - The class name of the JDBC driver</p>
</li>
<li>
<p><code>username</code> - The username used to establish a JDBC connection</p>
</li>
<li>
<p><code>password</code> - The password used to establish a JDBC connection</p>
</li>
<li>
<p><code>url</code> - The JDBC URL of the database</p>
</li>
<li>
<p><code>dbCreate</code> - Whether to auto-generate the database from the domain model - one of 'create-drop', 'create', 'update' or 'validate'</p>
</li>
<li>
<p><code>pooled</code> - Whether to use a pool of connections (defaults to true)</p>
</li>
<li>
<p><code>logSql</code> - Enable SQL logging to stdout</p>
</li>
<li>
<p><code>formatSql</code> - Format logged SQL</p>
</li>
<li>
<p><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">org.hibernate.dialect</a> package for available dialects.</p>
</li>
<li>
<p><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></p>
</li>
<li>
<p><code>transactional</code> - If <code>false</code> leaves the DataSource&#8217;s transactionManager bean outside the chained BE1PC transaction manager implementation. This only applies to additional datasources.</p>
</li>
<li>
<p><code>persistenceInterceptor</code> - The default datasource is automatically wired up to the persistence interceptor, other datasources are not wired up automatically unless this is set to <code>true</code></p>
</li>
<li>
<p><code>properties</code> - Extra properties to set on the DataSource bean. See the <a href="http://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html#Common_Attributes">Tomcat Pool</a> documentation. There is also a Javadoc format <a href="https://tomcat.apache.org/tomcat-7.0-doc/api/org/apache/tomcat/jdbc/pool/PoolConfiguration.html">documentation of the properties</a>.</p>
</li>
<li>
<p><code>jmxExport</code> - If <code>false</code>, will disable registration of JMX MBeans for all DataSources. By default JMX MBeans are added for DataSources with <code>jmxEnabled = true</code> in properties.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>A typical configuration for MySQL in <code>application.groovy</code> may be something like:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">dataSource {
pooled = <span class="predefined-constant">true</span>
dbCreate = <span class="string"><span class="delimiter">&quot;</span><span class="content">update</span><span class="delimiter">&quot;</span></span>
url = <span class="string"><span class="delimiter">&quot;</span><span class="content">jdbc:mysql://localhost:3306/my_database</span><span class="delimiter">&quot;</span></span>
driverClassName = <span class="string"><span class="delimiter">&quot;</span><span class="content">com.mysql.jdbc.Driver</span><span class="delimiter">&quot;</span></span>
dialect = org.hibernate.dialect.MySQL5InnoDBDialect
username = <span class="string"><span class="delimiter">&quot;</span><span class="content">username</span><span class="delimiter">&quot;</span></span>
password = <span class="string"><span class="delimiter">&quot;</span><span class="content">password</span><span class="delimiter">&quot;</span></span>
properties {
jmxEnabled = <span class="predefined-constant">true</span>
initialSize = <span class="integer">5</span>
maxActive = <span class="integer">50</span>
minIdle = <span class="integer">5</span>
maxIdle = <span class="integer">25</span>
maxWait = <span class="integer">10000</span>
maxAge = <span class="integer">10</span> * <span class="integer">60000</span>
timeBetweenEvictionRunsMillis = <span class="integer">5000</span>
minEvictableIdleTimeMillis = <span class="integer">60000</span>
validationQuery = <span class="string"><span class="delimiter">&quot;</span><span class="content">SELECT 1</span><span class="delimiter">&quot;</span></span>
validationQueryTimeout = <span class="integer">3</span>
validationInterval = <span class="integer">15000</span>
testOnBorrow = <span class="predefined-constant">true</span>
testWhileIdle = <span class="predefined-constant">true</span>
testOnReturn = <span class="predefined-constant">false</span>
jdbcInterceptors = <span class="string"><span class="delimiter">&quot;</span><span class="content">ConnectionState;StatementCache(max=200)</span><span class="delimiter">&quot;</span></span>
defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED
}
}</code></pre>
</div>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
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:
</td>
</tr>
</table>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">dataSource {
<span class="type">boolean</span> pooled = <span class="predefined-constant">true</span> <span class="comment">// type declaration results in ignored local variable</span>
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Example of advanced configuration using extra properties:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">dataSource {
pooled = <span class="predefined-constant">true</span>
dbCreate = <span class="string"><span class="delimiter">&quot;</span><span class="content">update</span><span class="delimiter">&quot;</span></span>
url = <span class="string"><span class="delimiter">&quot;</span><span class="content">jdbc:mysql://localhost:3306/my_database</span><span class="delimiter">&quot;</span></span>
driverClassName = <span class="string"><span class="delimiter">&quot;</span><span class="content">com.mysql.jdbc.Driver</span><span class="delimiter">&quot;</span></span>
dialect = org.hibernate.dialect.MySQL5InnoDBDialect
username = <span class="string"><span class="delimiter">&quot;</span><span class="content">username</span><span class="delimiter">&quot;</span></span>
password = <span class="string"><span class="delimiter">&quot;</span><span class="content">password</span><span class="delimiter">&quot;</span></span>
properties {
<span class="comment">// Documentation for Tomcat JDBC Pool</span>
<span class="comment">// http://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html#Common_Attributes</span>
<span class="comment">// https://tomcat.apache.org/tomcat-7.0-doc/api/org/apache/tomcat/jdbc/pool/PoolConfiguration.html</span>
jmxEnabled = <span class="predefined-constant">true</span>
initialSize = <span class="integer">5</span>
maxActive = <span class="integer">50</span>
minIdle = <span class="integer">5</span>
maxIdle = <span class="integer">25</span>
maxWait = <span class="integer">10000</span>
maxAge = <span class="integer">10</span> * <span class="integer">60000</span>
timeBetweenEvictionRunsMillis = <span class="integer">5000</span>
minEvictableIdleTimeMillis = <span class="integer">60000</span>
validationQuery = <span class="string"><span class="delimiter">&quot;</span><span class="content">SELECT 1</span><span class="delimiter">&quot;</span></span>
validationQueryTimeout = <span class="integer">3</span>
validationInterval = <span class="integer">15000</span>
testOnBorrow = <span class="predefined-constant">true</span>
testWhileIdle = <span class="predefined-constant">true</span>
testOnReturn = <span class="predefined-constant">false</span>
ignoreExceptionOnPreLoad = <span class="predefined-constant">true</span>
<span class="comment">// http://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html#JDBC_interceptors</span>
jdbcInterceptors = <span class="string"><span class="delimiter">&quot;</span><span class="content">ConnectionState;StatementCache(max=200)</span><span class="delimiter">&quot;</span></span>
defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED <span class="comment">// safe default</span>
<span class="comment">// controls for leaked connections</span>
abandonWhenPercentageFull = <span class="integer">100</span> <span class="comment">// settings are active only when pool is full</span>
removeAbandonedTimeout = <span class="integer">120</span>
removeAbandoned = <span class="predefined-constant">true</span>
<span class="comment">// use JMX console to change this setting at runtime</span>
logAbandoned = <span class="predefined-constant">false</span> <span class="comment">// causes stacktrace recording overhead, use only for debugging</span>
<span class="comment">// JDBC driver properties</span>
<span class="comment">// Mysql as example</span>
dbProperties {
<span class="comment">// Mysql specific driver properties</span>
<span class="comment">// http://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html</span>
<span class="comment">// let Tomcat JDBC Pool handle reconnecting</span>
autoReconnect=<span class="predefined-constant">false</span>
<span class="comment">// truncation behaviour</span>
jdbcCompliantTruncation=<span class="predefined-constant">false</span>
<span class="comment">// mysql 0-date conversion</span>
zeroDateTimeBehavior=<span class="string"><span class="delimiter">'</span><span class="content">convertToNull</span><span class="delimiter">'</span></span>
<span class="comment">// Tomcat JDBC Pool's StatementCache is used instead, so disable mysql driver's cache</span>
cachePrepStmts=<span class="predefined-constant">false</span>
cacheCallableStmts=<span class="predefined-constant">false</span>
<span class="comment">// Tomcat JDBC Pool's StatementFinalizer keeps track</span>
dontTrackOpenResources=<span class="predefined-constant">true</span>
<span class="comment">// performance optimization: reduce number of SQLExceptions thrown in mysql driver code</span>
holdResultsOpenOverStatementClose=<span class="predefined-constant">true</span>
<span class="comment">// enable MySQL query cache - using server prep stmts will disable query caching</span>
useServerPrepStmts=<span class="predefined-constant">false</span>
<span class="comment">// metadata caching</span>
cacheServerConfiguration=<span class="predefined-constant">true</span>
cacheResultSetMetadata=<span class="predefined-constant">true</span>
metadataCacheSize=<span class="integer">100</span>
<span class="comment">// timeouts for TCP/IP</span>
connectTimeout=<span class="integer">15000</span>
socketTimeout=<span class="integer">120000</span>
<span class="comment">// timer tuning (disable)</span>
maintainTimeStats=<span class="predefined-constant">false</span>
enableQueryTimeouts=<span class="predefined-constant">false</span>
<span class="comment">// misc tuning</span>
noDatetimeStringSync=<span class="predefined-constant">true</span>
}
}
}</code></pre>
</div>
</div>
<div class="sect3">
<h4 id="_more_on_dbcreate">More on dbCreate</h4>
<div class="paragraph">
<p>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:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><strong>create</strong> - Drops the existing schema and creates the schema on startup, dropping existing tables, indexes, etc. first.</p>
</li>
<li>
<p><strong>create-drop</strong> - Same as <strong>create</strong>, but also drops the tables when the application shuts down cleanly.</p>
</li>
<li>
<p><strong>update</strong> - Creates missing tables and indexes, and updates the current schema without dropping any tables or data. Note that this can&#8217;t properly handle many schema changes like column renames (you&#8217;re left with the old column containing the existing data).</p>
</li>
<li>
<p><strong>validate</strong> - Makes no changes to your database. Compares the configuration with the existing database schema and reports warnings.</p>
</li>
<li>
<p>any other value - does nothing</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Setting the <code>dbCreate</code> setting to "none" 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="https://flywaydb.org/">Flyway</a> or <a href="http://www.liquibase.org/">Liquibase</a>. The <a href="http://plugins.grails.org/plugin/grails/database-migration">Database Migration</a> plugin uses Liquibase.</p>
</div>
</div>
<a name="3.3.1 DataSources and Environments"><!-- Legacy link --></a>
<h2 id="dataSourcesAndEnvironments">4.4.1 DataSources and Environments</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/dataSource/dataSourcesAndEnvironments.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>The previous example configuration assumes you want the same config for all environments: production, test, development etc.</p>
</div>
<div class="paragraph">
<p>Grails' DataSource definition is "environment aware", however, so you can do:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">dataSource {
pooled = <span class="predefined-constant">true</span>
driverClassName = <span class="string"><span class="delimiter">&quot;</span><span class="content">com.mysql.jdbc.Driver</span><span class="delimiter">&quot;</span></span>
dialect = org.hibernate.dialect.MySQL5InnoDBDialect
<span class="comment">// other common settings here</span>
}
environments {
production {
dataSource {
url = <span class="string"><span class="delimiter">&quot;</span><span class="content">jdbc:mysql://liveip.com/liveDb</span><span class="delimiter">&quot;</span></span>
<span class="comment">// other environment-specific settings here</span>
}
}
}</code></pre>
</div>
</div>
<a name="3.3.3 Automatic Database Migration"><!-- Legacy link --></a>
<h2 id="automaticDatabaseMigration">4.4.2 Automatic Database Migration</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/dataSource/automaticDatabaseMigration.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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="GORM.html">GORM</a> classes. The options are described in the <a href="#dataSource">DataSource</a> section:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>create</code></p>
</li>
<li>
<p><code>create-drop</code></p>
</li>
<li>
<p><code>update</code></p>
</li>
<li>
<p><code>validate</code></p>
</li>
<li>
<p>no value</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>In <a href="#environments">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&#8217;ll need to stop dropping and re-creating the database every time you start up your server.</p>
</div>
<div class="paragraph">
<p>It&#8217;s tempting to switch to <code>update</code> so you retain existing data and only update the schema when your code changes, but Hibernate&#8217;s update support is very conservative. It won&#8217;t make any changes that could result in data loss, and doesn&#8217;t detect renamed columns or tables, so you&#8217;ll be left with the old one and will also have the new one.</p>
</div>
<div class="paragraph">
<p>Grails supports migrations with Liquibase or Flyway via plugins.</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="http://plugins.grails.org/plugin/grails/database-migration">Database Migration</a></p>
</li>
<li>
<p><a href="http://plugins.grails.org/plugin/saw303/org.grails.plugins%3Agrails-flyway">Flyway</a></p>
</li>
</ul>
</div>
<a name="3.3.4 Transaction-aware DataSource Proxy"><!-- Legacy link --></a>
<h2 id="transactionAwareDataSourceProxy">4.4.3 Transaction-aware DataSource Proxy</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/dataSource/transactionAwareDataSourceProxy.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>The actual <code>dataSource</code> bean is wrapped in a transaction-aware proxy so you will be given the connection that&#8217;s being used by the current transaction or Hibernate <code>Session</code> if one is active.</p>
</div>
<div class="paragraph">
<p>If this were not the case, then retrieving a connection from the <code>dataSource</code> would be a new connection, and you wouldn&#8217;t be able to see changes that haven&#8217;t been committed yet (assuming you have a sensible transaction isolation setting, e.g. <code>READ_COMMITTED</code> or better).</p>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>You can access this bean like any other Spring bean, i.e. using dependency injection:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">MyService</span> {
<span class="keyword">def</span> dataSourceUnproxied
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>or by pulling it from the <code>ApplicationContext</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> dataSourceUnproxied = ctx.dataSourceUnproxied</code></pre>
</div>
</div>
<a name="3.3.5 Database Console"><!-- Legacy link --></a>
<h2 id="databaseConsole">4.4.4 Database Console</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/dataSource/databaseConsole.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>The <a href="http://h2database.com/html/quickstart.html#h2_console">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&#8217;s very useful to view the database you&#8217;re developing against. It&#8217;s especially useful when running against an in-memory database.</p>
</div>
<div class="paragraph">
<p>You can access the console by navigating to <a href="http://localhost:8080/dbconsole" class="bare">http://localhost:8080/dbconsole</a> in a browser. The URI can be configured using the <code>grails.dbconsole.urlRoot</code> attribute in <code>application.groovy</code> and defaults to <code>'/dbconsole'</code>.</p>
</div>
<div class="paragraph">
<p>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 <code>application.groovy</code>. For example, you could enable the console in production like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">environments {
production {
grails.serverURL = <span class="string"><span class="delimiter">&quot;</span><span class="content">http://www.changeme.com</span><span class="delimiter">&quot;</span></span>
grails.dbconsole.enabled = <span class="predefined-constant">true</span>
grails.dbconsole.urlRoot = <span class="string"><span class="delimiter">'</span><span class="content">/admin/dbconsole</span><span class="delimiter">'</span></span>
}
development {
grails.serverURL = <span class="string"><span class="delimiter">&quot;</span><span class="content">http://localhost:8080/</span><span class="inline"><span class="inline-delimiter">${</span>appName<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>
}
test {
grails.serverURL = <span class="string"><span class="delimiter">&quot;</span><span class="content">http://localhost:8080/</span><span class="inline"><span class="inline-delimiter">${</span>appName<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>
}
}</code></pre>
</div>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
If you enable the console in production be sure to guard access to it using a trusted security framework.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_configuration">Configuration</h4>
<div class="paragraph">
<p>By default the console is configured for an H2 database which will work with the default settings if you haven&#8217;t configured an external database - you just need to change the JDBC URL to <code>jdbc:h2:mem:devDb</code>. If you&#8217;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 <code>application.groovy</code>.</p>
</div>
</div>
<a name="3.3.6 Multiple Datasources"><!-- Legacy link --></a>
<h2 id="multipleDatasources">4.4.5 Multiple Datasources</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/dataSource/multipleDatasources.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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 data sources.</p>
</div>
<div class="sect3">
<h4 id="_configuring_additional_datasources">Configuring Additional DataSources</h4>
<div class="paragraph">
<p>The default <code>DataSource</code> configuration in <code>grails-app/conf/application.yml</code> looks something like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">dataSource</span>:
<span class="key">pooled</span>: <span class="string"><span class="content">true</span></span>
<span class="key">jmxExport</span>: <span class="string"><span class="content">true</span></span>
<span class="key">driverClassName</span>: <span class="string"><span class="content">org.h2.Driver</span></span>
<span class="key">username</span>: <span class="string"><span class="content">sa</span></span>
<span class="key">password</span>:
<span class="key">environments</span>:
<span class="key">development</span>:
<span class="key">dataSource</span>:
<span class="key">dbCreate</span>: <span class="string"><span class="content">create-drop</span></span>
<span class="key">url</span>: <span class="string"><span class="content">jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE</span></span>
<span class="key">test</span>:
<span class="key">dataSource</span>:
<span class="key">dbCreate</span>: <span class="string"><span class="content">update</span></span>
<span class="key">url</span>: <span class="string"><span class="content">jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE</span></span>
<span class="key">production</span>:
<span class="key">dataSource</span>:
<span class="key">dbCreate</span>: <span class="string"><span class="content">update</span></span>
<span class="key">url</span>: <span class="string"><span class="content">jdbc:h2:prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE</span></span>
<span class="key">properties</span>:
<span class="key">jmxEnabled</span>: <span class="string"><span class="content">true</span></span>
<span class="key">initialSize</span>: <span class="string"><span class="content">5</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>This configures a single <code>DataSource</code> with the Spring bean named <code>dataSource</code>. To configure extra data sources, add a <code>dataSources</code> block (at the top level, in an environment block, or both, just like the standard <code>DataSource</code> definition) with a custom name. For example, this configuration adds a second <code>DataSource</code>, using MySQL in the development environment and Oracle in production:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">dataSource</span>:
<span class="key">pooled</span>: <span class="string"><span class="content">true</span></span>
<span class="key">jmxExport</span>: <span class="string"><span class="content">true</span></span>
<span class="key">driverClassName</span>: <span class="string"><span class="content">org.h2.Driver</span></span>
<span class="key">username</span>: <span class="string"><span class="content">sa</span></span>
<span class="key">password</span>:
<span class="key">dataSources</span>:
<span class="key">lookup</span>:
<span class="key">dialect</span>: <span class="string"><span class="content">org.hibernate.dialect.MySQLInnoDBDialect</span></span>
<span class="key">driverClassName</span>: <span class="string"><span class="content">com.mysql.jdbc.Driver</span></span>
<span class="key">username</span>: <span class="string"><span class="content">lookup</span></span>
<span class="key">password</span>: <span class="string"><span class="content">secret</span></span>
<span class="key">url</span>: <span class="string"><span class="content">jdbc:mysql://localhost/lookup</span></span>
<span class="key">dbCreate</span>: <span class="string"><span class="content">update</span></span>
<span class="key">environments</span>:
<span class="key">development</span>:
<span class="key">dataSource</span>:
<span class="key">dbCreate</span>: <span class="string"><span class="content">create-drop</span></span>
<span class="key">url</span>: <span class="string"><span class="content">jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE</span></span>
<span class="key">test</span>:
<span class="key">dataSource</span>:
<span class="key">dbCreate</span>: <span class="string"><span class="content">update</span></span>
<span class="key">url</span>: <span class="string"><span class="content">jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE</span></span>
<span class="key">production</span>:
<span class="key">dataSource</span>:
<span class="key">dbCreate</span>: <span class="string"><span class="content">update</span></span>
<span class="key">url</span>: <span class="string"><span class="content">jdbc:h2:prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE</span></span>
<span class="key">properties</span>:
<span class="key">jmxEnabled</span>: <span class="string"><span class="content">true</span></span>
<span class="key">initialSize</span>: <span class="string"><span class="content">5</span></span>
<span class="error">...</span>
<span class="key">dataSources</span>:
<span class="key">lookup</span>:
<span class="key">dialect</span>: <span class="string"><span class="content">org.hibernate.dialect.Oracle10gDialect</span></span>
<span class="key">driverClassName</span>: <span class="string"><span class="content">oracle.jdbc.driver.OracleDriver</span></span>
<span class="key">username</span>: <span class="string"><span class="content">lookup</span></span>
<span class="key">password</span>: <span class="string"><span class="content">secret</span></span>
<span class="key">url</span>: <span class="string"><span class="content">jdbc:oracle:thin:@localhost:1521:lookup</span></span>
<span class="key">dbCreate</span>: <span class="string"><span class="content">update</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>You can use the same or different databases as long as they&#8217;re supported by Hibernate.</p>
</div>
<div class="paragraph">
<p>If you need to inject the <code>lookup</code> datasource in a Grails artefact, you can do it like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="predefined-type">DataSource</span> dataSource_lookup</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
While defining multiple data sources, one of them <strong>must</strong> be named "dataSource". This is required because Grails determines which data source is the default by determining which one is named "dataSource".
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_configuring_domain_classes">Configuring Domain Classes</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ZipCode</span> {
<span class="predefined-type">String</span> code
<span class="directive">static</span> mapping = {
datasource <span class="string"><span class="delimiter">'</span><span class="content">lookup</span><span class="delimiter">'</span></span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>A domain class can also use two or more data sources. Use the <code>datasources</code> property with a list of names to configure more than one, for example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ZipCode</span> {
<span class="predefined-type">String</span> code
<span class="directive">static</span> mapping = {
datasources([<span class="string"><span class="delimiter">'</span><span class="content">lookup</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">auditing</span><span class="delimiter">'</span></span>])
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ZipCode</span> {
<span class="predefined-type">String</span> code
<span class="directive">static</span> mapping = {
datasources([<span class="string"><span class="delimiter">'</span><span class="content">lookup</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">DEFAULT</span><span class="delimiter">'</span></span>])
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If a domain class uses all configured data sources, use the special value <code>'ALL'</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ZipCode</span> {
<span class="predefined-type">String</span> code
<span class="directive">static</span> mapping = {
datasource <span class="string"><span class="delimiter">'</span><span class="content">ALL</span><span class="delimiter">'</span></span>
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_namespaces_and_gorm_methods">Namespaces and GORM Methods</h4>
<div class="paragraph">
<p>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 data sources:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ZipCode</span> {
<span class="predefined-type">String</span> code
<span class="directive">static</span> mapping = {
datasources([<span class="string"><span class="delimiter">'</span><span class="content">lookup</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">auditing</span><span class="delimiter">'</span></span>])
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The first <code>DataSource</code> specified is the default when not using an explicit namespace, so in this case we default to <code>'lookup'</code>. But you can call GORM methods on the 'auditing' <code>DataSource</code> with the <code>DataSource</code> name, for example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> zipCode = ZipCode.auditing.get(<span class="integer">42</span>)
...
zipCode.auditing.save()</code></pre>
</div>
</div>
<div class="paragraph">
<p>As you can see, you add the <code>DataSource</code> to the method call in both the static case and the instance case.</p>
</div>
</div>
<div class="sect3">
<h4 id="_hibernate_mapped_domain_classes">Hibernate Mapped Domain Classes</h4>
<div class="paragraph">
<p>You can also partition annotated Java classes into separate datasources. Classes using the default datasource are registered in <code>grails-app/conf/hibernate.cfg.xml</code>. To specify that an annotated class uses a non-default datasource, create a <code>hibernate.cfg.xml</code> file for that datasource with the file name prefixed with the datasource name.</p>
</div>
<div class="paragraph">
<p>For example if the <code>Book</code> class is in the default datasource, you would register that in <code>grails-app/conf/hibernate.cfg.xml</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="preprocessor">&lt;?xml version='1.0' encoding='UTF-8'?&gt;</span>
<span class="doctype">&lt;!DOCTYPE hibernate-configuration PUBLIC
'-//Hibernate/Hibernate Configuration DTD 3.0//EN'
'http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd'&gt;</span>
<span class="tag">&lt;hibernate-configuration&gt;</span>
<span class="tag">&lt;session-factory&gt;</span>
<span class="tag">&lt;mapping</span> <span class="attribute-name">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">org.example.Book</span><span class="delimiter">'</span></span><span class="tag">/&gt;</span>
<span class="tag">&lt;/session-factory&gt;</span>
<span class="tag">&lt;/hibernate-configuration&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>and if the <code>Library</code> class is in the "ds2" datasource, you would register that in <code>grails-app/conf/ds2_hibernate.cfg.xml</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="preprocessor">&lt;?xml version='1.0' encoding='UTF-8'?&gt;</span>
<span class="doctype">&lt;!DOCTYPE hibernate-configuration PUBLIC
'-//Hibernate/Hibernate Configuration DTD 3.0//EN'
'http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd'&gt;</span>
<span class="tag">&lt;hibernate-configuration&gt;</span>
<span class="tag">&lt;session-factory&gt;</span>
<span class="tag">&lt;mapping</span> <span class="attribute-name">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">org.example.Library</span><span class="delimiter">'</span></span><span class="tag">/&gt;</span>
<span class="tag">&lt;/session-factory&gt;</span>
<span class="tag">&lt;/hibernate-configuration&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The process is the same for classes mapped with hbm.xml files - just list them in the appropriate hibernate.cfg.xml file.</p>
</div>
</div>
<div class="sect3">
<h4 id="_services">Services</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">DataService</span> {
<span class="directive">static</span> datasource = <span class="string"><span class="delimiter">'</span><span class="content">lookup</span><span class="delimiter">'</span></span>
<span class="type">void</span> someMethod(...) {
...
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>Note that the datasource specified in a service has no bearing on which datasources are used for domain classes; that&#8217;s determined by their declared datasources in the domain classes themselves. It&#8217;s used to declare which transaction manager to use.</p>
</div>
<div class="paragraph">
<p>If you have a <code>Foo</code> domain class in <code>dataSource1</code> and a <code>Bar</code> domain class in <code>dataSource2</code>, if <code>WahooService</code> uses <code>dataSource1</code>, a service method that saves a new <code>Foo</code> and a new <code>Bar</code> will only be transactional for <code>Foo</code> since they share the same datasource. The transaction won&#8217;t affect the <code>Bar</code> instance. If you want both to be transactional you&#8217;d need to use two services and XA datasources for two-phase commit, e.g. with the Atomikos plugin.</p>
</div>
</div>
<div class="sect3">
<h4 id="_transactions_across_multiple_data_sources">Transactions across multiple data sources</h4>
<div class="paragraph">
<p>Grails does not by default by default try to handle transactions that span multiple data sources.</p>
</div>
<div class="paragraph">
<p>You can enable Grails to use the Best Effort 1PC pattern for handling transactions across multiple datasources. To do so you must set the <code>grails.transaction.chainedTransactionManagerPostProcessor.enabled</code> setting to <code>true</code> in <code>application.yml</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">grails</span>:
<span class="key">transaction</span>:
<span class="key">chainedTransactionManagerPostProcessor</span>:
<span class="key">enabled</span>: <span class="string"><span class="content">true</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The <a href="https://www.javaworld.com/article/2077963/open-source-tools/distributed-transactions-in-spring-with-and-without-xa.html">Best Efforts 1PC pattern</a> is fairly general but can fail in some circumstances that the developer must be aware of.</p>
</div>
<div class="paragraph">
<p>This is a non-XA pattern that involves a synchronized single-phase commit of a number of resources. Because the <a href="#ref-orgwiki-twophasecommit-2PC">2PC</a> is not used, it can never be as safe as an <a href="#ref-orgwiki-x-open-xa-XA">XA</a> transaction, but is often good enough if the participants are aware of the compromises.</p>
</div>
<div class="paragraph">
<p>The basic idea is to delay the commit of all resources as late as possible in a transaction so that the only thing that can go wrong is an infrastructure failure (not a business-processing error). Systems that rely on Best Efforts 1PC reason that infrastructure failures are rare enough that they can afford to take the risk in return for higher throughput. If business-processing services are also designed to be idempotent, then little can go wrong in practice.</p>
</div>
<div class="paragraph">
<p>The BE1PC implementation was added in Grails 2.3.6. . Before this change additional datasources didn&#8217;t take part in transactions initiated in Grails. The transactions in additional datasources were basically in auto commit mode. In some cases this might be the wanted behavior. One reason might be performance: on the start of each new transaction, the BE1PC transaction manager creates a new transaction to each datasource. It&#8217;s possible to leave an additional datasource out of the BE1PC transaction manager by setting <code>transactional = false</code> in the respective configuration block of the additional dataSource. Datasources with <code>readOnly = true</code> will also be left out of the chained transaction manager (since 2.3.7).</p>
</div>
<div class="paragraph">
<p>By default, the BE1PC implementation will add all beans implementing the Spring <code><a href="https://docs.spring.io/spring/docs/current/javadoc-api//org/springframework/transaction/PlatformTransactionManager.html">PlatformTransactionManager</a></code> interface to the chained BE1PC transaction manager. For example, a possible <code><a href="https://docs.spring.io/spring/docs/current/javadoc-api//org/springframework/jms/connection/JmsTransactionManager.html">JMSTransactionManager</a></code> bean in the Grails application context would be added to the Grails BE1PC transaction manager&#8217;s chain of transaction managers.</p>
</div>
<div class="paragraph">
<p>You can exclude transaction manager beans from the BE1PC implementation with this configuration option:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">grails</span>:
<span class="key">transaction</span>:
<span class="key">chainedTransactionManagerPostProcessor</span>:
<span class="key">enabled</span>: <span class="string"><span class="content">true</span></span>
<span class="key">blacklistPattern</span>: <span class="string"><span class="content">'.*'</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The exclude matching is done on the name of the transaction manager bean. The transaction managers of datasources with <code>transactional = false</code> or <code>readOnly = true</code> will be skipped and using this configuration option is not required in that case.</p>
</div>
</div>
<div class="sect3">
<h4 id="_xa_and_two_phase_commit">XA and Two-phase Commit</h4>
<div class="paragraph">
<p>When the Best Efforts 1PC pattern isn&#8217;t suitable for handling transactions across multiple transactional resources (not only datasources), there are several options available for adding XA/2PC support to Grails applications.</p>
</div>
<div class="paragraph">
<p>The <a href="{springdocs}/transaction.html#transaction-application-server-integration">Spring transactions documentation</a> contains information about integrating the JTA/XA transaction manager of different application servers. In this case, you can configure a bean with the name <code>transactionManager</code> manually in <code>resources.groovy</code> or <code>resources.xml</code> file.</p>
</div>
</div>
<a name="3.5 Versioning"><!-- Legacy link --></a>
<h2 id="versioning">4.5 Versioning</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/versioning.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_detecting_versions_at_runtime">Detecting Versions at Runtime</h4>
<div class="paragraph">
<p>You can detect the application version using Grails' support for application metadata using the <a href="https://grails.apache.org/docs/3.3.7/api/grails/core/GrailsApplication.html">GrailsApplication</a> class. For example within <a href="theWebLayer.html#controllers">controllers</a> there is an implicit <a href="../ref/Controllers/grailsApplication.html">grailsApplication</a> variable that can be used:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> version = grailsApplication.metadata.getApplicationVersion()</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can retrieve the version of Grails that is running with:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> grailsVersion = grailsApplication.metadata.getGrailsVersion()</code></pre>
</div>
</div>
<div class="paragraph">
<p>or the <code>GrailsUtil</code> class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.util.GrailsUtil</span>
...
def grailsVersion = GrailsUtil.grailsVersion</code></pre>
</div>
</div>
</div>
<a name="3.7 Dependency Resolution"><!-- Legacy link --></a>
<h2 id="dependencyResolution">4.6 Dependency Resolution</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/conf/dependencyResolution.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Dependency resolution is handled by the <a href="http://gradle.org">Gradle build tool</a>, all dependencies are defined in the <code>build.gradle</code> file. Refer to the <a href="commandLine.html#gradleBuild">Gradle user guide</a> for more information.</p>
</div>
<a name="4. The Command Line"><!-- Legacy link --></a>
<h1 id="commandLine">5 The Command Line</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/commandLine.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails 3.0&#8217;s command line system differs greatly from previous versions of Grails and features APIs for invoking Gradle for build related tasks, as well as performing code generation.</p>
</div>
<div class="paragraph">
<p>When you type:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails &lt;&lt;command name&gt;&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Grails searches the <a href="http://bintray.com/grails/profiles">profile repository</a> based on the profile of the current application. If the profile is for a web application then commands are read from the web profile and the base profile which it inherits from.</p>
</div>
<div class="paragraph">
<p>Since command behavior is profile specific the web profile may provide different behavior for the <code>run-app</code> command then say a profile for running batch applications.</p>
</div>
<div class="paragraph">
<p>When you type the following command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails run-app</code></pre>
</div>
</div>
<div class="paragraph">
<p>It will first search the application, and then the profile for commands:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>PROJECT_HOME/src/main/scripts/run-app.groovy</code></p>
</li>
<li>
<p><code><a href="#profile">[profile]</a>/commands/run-app.groovy</code></p>
</li>
<li>
<p><code><a href="#profile">[profile]</a>/commands/run-app.yml</code></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>To get a list of all commands and some help about the available commands type:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">grails help</code></pre>
</div>
</div>
<div class="paragraph">
<p>which outputs usage instructions and the list of commands Grails is aware of:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">grails &lt;&lt;environment&gt;&gt;* &lt;&lt;target&gt;&gt; &lt;&lt;arguments&gt;&gt;*'
| Examples:
$ grails dev run-app
$ grails create-app books
| Available Commands (type grails help 'command-name' for more info):
| Command Name Command Description
----------------------------------------------------------------------------------------------------
clean Cleans a Grails application's compiled sources
compile Compiles a Grails application
...</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Refer to the Command Line reference in the Quick Reference menu of the reference guide for more information about individual commands
</td>
</tr>
</table>
</div>
<div class="sect2">
<h3 id="_arguments">Arguments</h3>
<div class="paragraph">
<p>The <code>grails</code> command is a front to a <code>gradle</code> invocation, because of this there can be unexpected side-effects.
For example, when executing <code>grails -Dapp.foo=bar run-app</code> the <code>app.foo</code> system property won&#8217;t be available to your application. This is because <code>bootRun</code> in your <code>build.gradle</code> configures the system properties.
To make this work you can simply append all <code>System.properties</code> to <code>bootRun</code> in <code>build.gradle</code> like:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">bootRun{
systemProperties <span class="predefined-type">System</span>.properties <span class="comment">// Please note not to use '=', because this will override all configured systemProperties. This will append them.</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or if you only want to pass through a limited set, you can prefix your system properties using an arbitrary prefix and configure <code>bootRun</code> like:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">bootRun{
bootRun {
systemProperties <span class="predefined-type">System</span>.properties.inject([:]){acc,item-&gt; item.key.startsWith(<span class="string"><span class="delimiter">'</span><span class="content">boot.</span><span class="delimiter">'</span></span>)?acc &lt;&lt; [(item.key.substring(<span class="string"><span class="delimiter">'</span><span class="content">boot.</span><span class="delimiter">'</span></span>.length())):item.value]:acc }
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this example only system properties starting with <code>boot.</code> are passed through.</p>
</div>
<div class="paragraph">
<p>Application and JVM arguments should be specified in <code>bootRun</code> as well.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">bootRun{
bootRun {
jvmArgs(<span class="string"><span class="delimiter">'</span><span class="content">-Dspring.output.ansi.enabled=always</span><span class="delimiter">'</span></span>)
args(<span class="string"><span class="delimiter">'</span><span class="content">--app.foo=bar</span><span class="delimiter">'</span></span>,<span class="string"><span class="delimiter">'</span><span class="content">--app.bar=foo</span><span class="delimiter">'</span></span>) <span class="comment">// Override the `app.foo` and `app.bar` config options (`grailsApplication.config`)</span>
}
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_non_interactive_mode">non-interactive mode</h3>
<div class="paragraph">
<p>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&#8217;s no way to "answer" the questions. So you can pass the <code>\--non-interactive</code> switch to the script command to tell Grails to accept the default answer for any questions, for example whether to install a missing plugin.</p>
</div>
<div class="paragraph">
<p>For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails war --non-interactive</code></pre>
</div>
</div>
</div>
<h2 id="interactiveMode">5.1 Interactive Mode</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/commandLine/interactiveMode.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Interactive mode is 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>
</div>
<div class="imageblock">
<div class="content">
<img src="../img/interactive-output.png" alt="interactive output">
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="imageblock">
<div class="content">
<img src="../img/interactive-open-cmd.png" alt="interactive open cmd">
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>TAB completion also works for class names after the <code>create-*</code> commands:</p>
</div>
<div class="imageblock">
<div class="content">
<img src="../img/interactive-complete-class.png" alt="interactive complete class">
</div>
</div>
<div class="paragraph">
<p>If you need to run an external process whilst interactive mode is running you can do so by starting the command with a !:</p>
</div>
<div class="imageblock">
<div class="content">
<img src="../img/interactive-run-external.png" alt="interactive run external">
</div>
</div>
<div class="paragraph">
<p>Note that with ! (bang) commands, you get file path auto completion - ideal for external commands that operate on the file system such as 'ls', 'cat', 'git', etc.</p>
</div>
<div class="paragraph">
<p>To exit interactive mode enter the <code>exit</code> command. Note that if the Grails application has been run with <code>run-app</code> normally it will terminate when the interactive mode console exits because the JVM will be terminated. An exception to this would be if the application were running in forked mode which means the application is running in a different JVM. In that case the application will be left running after the interactive mode console terminates. If you want to exit interactive mode and stop an application that is running in forked mode, use the <code>quit</code> command. The <code>quit</code> command will stop the running application and then close interactive mode.</p>
</div>
<h2 id="creatingCustomScripts">5.2 Creating Custom Scripts</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/commandLine/creatingCustomScripts.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>You can create your own Command scripts by running the <a href="../ref/Command%20Line/create-script.html">create-script</a> command from the root of your project. For example the following command will create a script called <code>src/main/scripts/hello-world.groovy</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails create-script hello-world</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
In general Grails scripts should be used for scripting the Gradle based build system and code generation. Scripts cannot load application classes and in fact should not since Gradle is required to construct the application classpath.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>See below for an example script that prints "Hello World":</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">description <span class="string"><span class="delimiter">&quot;</span><span class="content">Example description</span><span class="delimiter">&quot;</span></span>, <span class="string"><span class="delimiter">&quot;</span><span class="content">grails hello-world</span><span class="delimiter">&quot;</span></span>
println <span class="string"><span class="delimiter">&quot;</span><span class="content">Hello World</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>description</code> method is used to define the output seen by <code>grails help</code> and to aid users of the script. The following is a more complete example of providing a description taken from the <code>generate-all</code> command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">description( <span class="string"><span class="delimiter">&quot;</span><span class="content">Generates a controller that performs CRUD operations and the associated views</span><span class="delimiter">&quot;</span></span> ) {
usage <span class="string"><span class="delimiter">&quot;</span><span class="content">grails generate-all &lt;&lt;DOMAIN CLASS&gt;&gt;</span><span class="delimiter">&quot;</span></span>
flag <span class="key">name</span>:<span class="string"><span class="delimiter">'</span><span class="content">force</span><span class="delimiter">'</span></span>, <span class="key">description</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">Whether to overwrite existing files</span><span class="delimiter">&quot;</span></span>
argument <span class="key">name</span>:<span class="string"><span class="delimiter">'</span><span class="content">Domain Class</span><span class="delimiter">'</span></span>, <span class="key">description</span>:<span class="string"><span class="delimiter">'</span><span class="content">The name of the domain class</span><span class="delimiter">'</span></span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>As you can see this description profiles usage instructions, a flag and an argument. This allows the command to be used as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails generate-all MyClass --force</code></pre>
</div>
</div>
<div class="sect3">
<h4 id="_template_generation">Template Generation</h4>
<div class="paragraph">
<p>Plugins and applications that need to define template generation tasks can do so using scripts. A example of this is the Scaffolding plugin which defines the <code>generate-all</code> and <code>generate-controllers</code> commands.</p>
</div>
<div class="paragraph">
<p>Every Grails script implements the <a href="https://grails.apache.org/docs/3.3.7/api/org/grails/cli/profile/commands/templates/TemplateRenderer.html">TemplateRenderer</a> interface which makes it trivial to render templates to the users project workspace.</p>
</div>
<div class="paragraph">
<p>The following is an example of the <a href="../ref/Command%20Line/create-script.html">create-script</a> command written in Groovy:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">description( <span class="string"><span class="delimiter">&quot;</span><span class="content">Creates a Grails script</span><span class="delimiter">&quot;</span></span> ) {
usage <span class="string"><span class="delimiter">&quot;</span><span class="content">grails create-script &lt;&lt;SCRIPT NAME&gt;&gt;</span><span class="delimiter">&quot;</span></span>
argument <span class="key">name</span>:<span class="string"><span class="delimiter">'</span><span class="content">Script Name</span><span class="delimiter">'</span></span>, <span class="key">description</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">The name of the script to create</span><span class="delimiter">&quot;</span></span>
flag <span class="key">name</span>:<span class="string"><span class="delimiter">'</span><span class="content">force</span><span class="delimiter">'</span></span>, <span class="key">description</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">Whether to overwrite existing files</span><span class="delimiter">&quot;</span></span>
}
<span class="keyword">def</span> scriptName = args[<span class="integer">0</span>]
<span class="keyword">def</span> model = model(scriptName)
<span class="keyword">def</span> overwrite = flag(<span class="string"><span class="delimiter">'</span><span class="content">force</span><span class="delimiter">'</span></span>) ? <span class="predefined-constant">true</span> : <span class="predefined-constant">false</span>
render <span class="key">template</span>: template(<span class="string"><span class="delimiter">'</span><span class="content">artifacts/Script.groovy</span><span class="delimiter">'</span></span>),
<span class="key">destination</span>: file(<span class="string"><span class="delimiter">&quot;</span><span class="content">src/main/scripts/</span><span class="inline"><span class="inline-delimiter">${</span>model.lowerCaseName<span class="inline-delimiter">}</span></span><span class="content">.groovy</span><span class="delimiter">&quot;</span></span>),
<span class="key">model</span>: model,
<span class="key">overwrite</span>: overwrite</code></pre>
</div>
</div>
<div class="paragraph">
<p>If a script is defined in a plugin or profile, the <code>template(String)</code> method will search for the template in the application before using the template provided by your plugin or profile. This allows users of your plugin or profile to customize what gets generated.</p>
</div>
<div class="paragraph">
<p>It is common to provide an easy way to allow users to copy the templates from your plugin or profile. Here is one example on how the angular scaffolding copies templates.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">templates(<span class="string"><span class="delimiter">&quot;</span><span class="content">angular/**/*</span><span class="delimiter">&quot;</span></span>).each { Resource r -&gt;
<span class="predefined-type">String</span> path = r.URL.toString().replaceAll(<span class="regexp"><span class="delimiter">/</span><span class="content">^.*?META-INF</span><span class="delimiter">/</span></span>, <span class="string"><span class="delimiter">&quot;</span><span class="content">src/main</span><span class="delimiter">&quot;</span></span>)
<span class="keyword">if</span> (path.endsWith(<span class="string"><span class="delimiter">'</span><span class="content">/</span><span class="delimiter">'</span></span>)) {
mkdir(path)
} <span class="keyword">else</span> {
<span class="predefined-type">File</span> to = <span class="keyword">new</span> <span class="predefined-type">File</span>(path)
SpringIOUtils.copy(r, to)
println(<span class="string"><span class="delimiter">&quot;</span><span class="content">Copied </span><span class="inline"><span class="inline-delimiter">${</span>r.filename<span class="inline-delimiter">}</span></span><span class="content"> to location </span><span class="inline"><span class="inline-delimiter">${</span>to.canonicalPath<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>)
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_the_model">The "model"</h4>
<div class="paragraph">
<p>Executing the <code>model</code> method with a <code>Class</code>/<code>String</code>/<code>File</code>/<code>Resource</code> will return an instance of <a href="https://grails.apache.org/docs/3.3.7/api/grails/codegen/model/Model.html">Model</a>. The model contains several properties that can help you generate code.</p>
</div>
<div class="paragraph">
<p>Example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> domain = model(com.foo.Bar)
domain.className == <span class="string"><span class="delimiter">&quot;</span><span class="content">FooBar</span><span class="delimiter">&quot;</span></span>
domain.fullName == <span class="string"><span class="delimiter">&quot;</span><span class="content">com.foo.FooBar</span><span class="delimiter">&quot;</span></span>
domain.packageName == <span class="string"><span class="delimiter">&quot;</span><span class="content">com.foo</span><span class="delimiter">&quot;</span></span>
domain.packagePath == <span class="string"><span class="delimiter">&quot;</span><span class="content">com/foo</span><span class="delimiter">&quot;</span></span>
domain.propertyName == <span class="string"><span class="delimiter">&quot;</span><span class="content">fooBar</span><span class="delimiter">&quot;</span></span>
domain.lowerCaseName == <span class="string"><span class="delimiter">&quot;</span><span class="content">foo-bar</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>In addition, an <code>asMap</code> method is available to turn all of the properties into a map to pass to the <code>render</code> method.</p>
</div>
</div>
<div class="sect3">
<h4 id="_working_with_files">Working with files</h4>
<div class="paragraph">
<p>All scripts have access to methods on the <a href="https://grails.apache.org/docs/3.3.7/api/org/grails/cli/profile/commands/io/FileSystemInteraction.html">FileSystemInteraction</a> class. It contains helpful methods to copy, delete, and create files.</p>
</div>
</div>
<h2 id="creatingCustomCommands">5.3 Creating Custom Commands</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/commandLine/creatingCustomCommands.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>You can create your own commands by running the <a href="#ref-command-line-create-command">create-command</a> command from the root of your project. For example the following command will create a command called <code>grails-app/commands/HelloWorldCommand</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails create-command HelloWorld</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Unlike scripts, commands cause the Grails environment to start and you have full access to the application context and the runtime.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Since Grails 3.2.0, commands have similar abilities as scripts in regards to retrieving arguments, template generation, file access, and model building.</p>
</div>
<div class="paragraph">
<p>If you created a command in a previous version of grails, you can update your command to have those abilities by changing which trait you are implementing.</p>
</div>
<div class="paragraph">
<p>Commands created in Grails 3.1.x or lower implement the <a href="https://grails.apache.org/docs/latest/api/grails/dev/commands/ApplicationCommand.html">ApplicationCommand</a> trait by default which requires your command to implement the following method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">boolean</span> handle(ExecutionContext executionContext)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Commands created in Grails 3.2.0 or higher implement the <a href="https://grails.apache.org/docs/latest/api/grails/dev/commands/GrailsApplicationCommand.html">GrailsApplicationCommand</a> trait by default which requires your command to implement the following method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">boolean</span> handle()</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Commands defined this way still have access to the execution context via a variable called "executionContext".
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Custom commands can be executed using <strong>grails run-command</strong>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>grails run-command my-example</code></pre>
</div>
</div>
<div class="paragraph">
<p>Commands can also be executed using the <strong>runCommand</strong> gradle task. Note that the gradle task uses camelCase:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>gradle runCommand -Pargs="my-example"</code></pre>
</div>
</div>
<div class="paragraph">
<p>If the grails server is a subproject (e.g., in a project created with the <strong>angular</strong> profile), the subproject command can still be invoked from the gradle wrapper in the parent project:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>./gradlew server:runCommand -Pargs="my-example"</code></pre>
</div>
</div>
<a name="4.2 Re-using Grails scripts"><!-- Legacy link --></a>
<h2 id="reusingGrailsScripts">5.4 Re-using Grails scripts</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/commandLine/reusingGrailsScripts.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails ships with a lot of command line functionality out of the box that you may find useful in your own scripts (See the command line reference in the reference guide for info on all the commands).</p>
</div>
<div class="paragraph">
<p>Any script you create can invoke another Grails script simply by invoking a method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">testApp()</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above will invoke the <code>test-app</code> command. You can also pass arguments using the method arguments:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">testApp(<span class="string"><span class="delimiter">'</span><span class="content">--debug-jvm</span><span class="delimiter">'</span></span>)</code></pre>
</div>
</div>
<div class="sect3">
<h4 id="_invoking_gradle">Invoking Gradle</h4>
<div class="paragraph">
<p>Instead of invoking another Grails CLI command you can invoke Gradle directory using the <code>gradle</code> property.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">gradle.compileGroovy()</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_invoking_ant">Invoking Ant</h4>
<div class="paragraph">
<p>You can also invoke Ant tasks from scripts which can help if you need to writing code generation and automation tasks:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">ant.mkdir(<span class="key">dir</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">path</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
</div>
<h2 id="gradleBuild">5.5 Building with Gradle</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/commandLine/gradleBuild.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails 3.1 uses the <a href="http://gradle.org">Gradle Build System</a> for build related tasks such as compilation, runnings tests and producing binary distrubutions of your project. It is recommended to use Gradle 2.2 or above with Grails 3.1.</p>
</div>
<div class="paragraph">
<p>The build is defined by the <code>build.gradle</code> file which specifies the version of your project, the dependencies of the project and the repositories where to find those dependencies (amongst other things).</p>
</div>
<div class="paragraph">
<p>When you invoke the <code>grails</code> command the version of Gradle that ships with Grails 3.1 (currently 2.9) is invoked by the <code>grails</code> process via the <a href="http://www.gradle.org/docs/current/userguide/embedding.html">Gradle Tooling API</a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash"># Equivalent to 'gradle classes'
$ grails compile</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can invoke Gradle directly using the <code>gradle</code> command and use your own local version of Gradle, however you will need Gradle 2.2 or above to work with Grails 3.0:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ gradle assemble</code></pre>
</div>
</div>
<h2 id="gradleDependencies">5.5.1 Defining Dependencies with Gradle</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/commandLine/gradleBuild/gradleDependencies.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Dependencies for your project are defined in the <code>dependencies</code> block. In general you can follow the <a href="http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html">Gradle documentation on dependency management</a> to understand how to configure additional dependencies.</p>
</div>
<div class="paragraph">
<p>The default dependencies for the "web" profile can be seen below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">dependencies {
compile <span class="string"><span class="delimiter">'</span><span class="content">org.springframework.boot:spring-boot-starter-logging</span><span class="delimiter">'</span></span>
compile(<span class="string"><span class="delimiter">'</span><span class="content">org.springframework.boot:spring-boot-starter-actuator</span><span class="delimiter">'</span></span>)
compile <span class="string"><span class="delimiter">'</span><span class="content">org.springframework.boot:spring-boot-autoconfigure</span><span class="delimiter">'</span></span>
compile <span class="string"><span class="delimiter">'</span><span class="content">org.springframework.boot:spring-boot-starter-tomcat</span><span class="delimiter">'</span></span>
compile <span class="string"><span class="delimiter">'</span><span class="content">org.grails:grails-dependencies</span><span class="delimiter">'</span></span>
compile <span class="string"><span class="delimiter">'</span><span class="content">org.grails:grails-web-boot</span><span class="delimiter">'</span></span>
compile <span class="string"><span class="delimiter">'</span><span class="content">org.grails.plugins:hibernate</span><span class="delimiter">'</span></span>
compile <span class="string"><span class="delimiter">'</span><span class="content">org.grails.plugins:cache</span><span class="delimiter">'</span></span>
compile <span class="string"><span class="delimiter">'</span><span class="content">org.hibernate:hibernate-ehcache</span><span class="delimiter">'</span></span>
runtime <span class="string"><span class="delimiter">'</span><span class="content">org.grails.plugins:asset-pipeline</span><span class="delimiter">'</span></span>
runtime <span class="string"><span class="delimiter">'</span><span class="content">org.grails.plugins:scaffolding</span><span class="delimiter">'</span></span>
testCompile <span class="string"><span class="delimiter">'</span><span class="content">org.grails:grails-plugin-testing</span><span class="delimiter">'</span></span>
testCompile <span class="string"><span class="delimiter">'</span><span class="content">org.grails.plugins:geb</span><span class="delimiter">'</span></span>
<span class="comment">// Note: It is recommended to update to a more robust driver (Chrome, Firefox etc.)</span>
testRuntime <span class="string"><span class="delimiter">'</span><span class="content">org.seleniumhq.selenium:selenium-htmlunit-driver:2.44.0</span><span class="delimiter">'</span></span>
console <span class="string"><span class="delimiter">'</span><span class="content">org.grails:grails-console</span><span class="delimiter">'</span></span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that version numbers are not present in the majority of the dependencies. This is thanks to the dependency management plugin which configures a Maven BOM that defines the default dependency versions for certain commonly used dependencies and plugins:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">dependencyManagement {
imports {
mavenBom <span class="string"><span class="delimiter">'</span><span class="content">org.grails:grails-bom:</span><span class="delimiter">'</span></span> + grailsVersion
}
applyMavenExclusions <span class="predefined-constant">false</span>
}</code></pre>
</div>
</div>
<h2 id="gradleTasks">5.5.2 Working with Gradle Tasks</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/commandLine/gradleBuild/gradleTasks.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>As mentioned previously the <code>grails</code> command uses an embedded version of Gradle and certain Grails commands that existed in previous versions of Grails map onto their Gradle equivalents. The following table shows which Grails command invoke which Gradle task:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top"><strong>Grails Command</strong></th>
<th class="tableblock halign-left valign-top"><strong>Gradle Task</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">clean</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">clean</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">compile</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">classes</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">package</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">assemble</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">run-app</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">bootRun</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">test-app</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">test</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">test-app --integration</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">integrationTest</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">war</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">assemble</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>You can invoke any of these Grails commands using their Gradle equivalents if you prefer:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ gradle test</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note however that you will need to use a version of Gradle compatible with Grails 3.1 (Gradle 2.2 or above). If you wish to invoke a Gradle task using the version of Gradle used by Grails you can do so with the <code>grails</code> command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails gradle compileGroovy</code></pre>
</div>
</div>
<div class="paragraph">
<p>However, it is recommended you do this via interactive mode, as it greatly speeds up execution and provides TAB completion for the available Gradle tasks:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails
| Enter a command name to run. Use TAB for completion:
grails&gt; gradle compileGroovy
...</code></pre>
</div>
</div>
<div class="paragraph">
<p>To find out what Gradle tasks are available without using interactive mode TAB completion you can use the Gradle <code>tasks</code> task:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">gradle tasks</code></pre>
</div>
</div>
<h2 id="gradlePlugins">5.5.3 Grails plugins for Gradle</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/commandLine/gradleBuild/gradlePlugins.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>When you create a new project with the <a href="../ref/Command%20Line/create-app.html">create-app</a> command, a default <code>build.gradle</code> is created. The default <code>build.gradle</code> configures the build with a set of Gradle plugins that allow Gradle to build the Grails project:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">apply <span class="key">plugin</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">war</span><span class="delimiter">&quot;</span></span>
apply <span class="key">plugin</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">org.grails.grails-web</span><span class="delimiter">&quot;</span></span>
apply <span class="key">plugin</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">org.grails.grails-gsp</span><span class="delimiter">&quot;</span></span>
apply <span class="key">plugin</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">asset-pipeline</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The default plugins are as follows:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>war</code> - The <a href="http://www.gradle.org/docs/current/userguide/war_plugin.html">WAR plugin</a> changes the packaging so that Gradle creates as WAR file from your application. You can comment out this plugin if you wish to create only a runnable JAR file for standalone deployment.</p>
</li>
<li>
<p><code>asset-pipeline</code> - The <a href="https://grails.org/plugins.html#plugin/asset-pipeline">asset pipeline</a> plugin enables the compilation of static assets (JavaScript, CSS etc.)</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Many of these are built in plugins provided by Gradle or third party plugins. The Gradle plugins that Grails provides are as follows:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>org.grails.grails-core</code> - The primary Grails plugin for Gradle, included by all other plugins and designed to operate with all profiles.</p>
</li>
<li>
<p><code>org.grails.grails-gsp</code> - The Grails GSP plugin adds precompilation of GSP files for production deployments.</p>
</li>
<li>
<p><code>org.grails.grails-doc</code> - A plugin for Gradle for using Grails 2.0&#8217;s documentation engine.</p>
</li>
<li>
<p><code>org.grails.grails-plugin</code> - A plugin for Gradle for building Grails plugins.</p>
</li>
<li>
<p><code>org.grails.grails-plugin-publish</code> - A plugin for publishing Grails plugins to the central repository.</p>
</li>
<li>
<p><code>org.grails.grails-profile</code> - A plugin for use when creating Grails <a href="#profiles">Profiles</a>.</p>
</li>
<li>
<p><code>org.grails.grails-profile-publish</code> - A plugin for publishing Grails profiles to the central repository.</p>
</li>
<li>
<p><code>org.grails.grails-web</code> - The Grails Web gradle plugin configures Gradle to understand the Grails conventions and directory structure.</p>
</li>
</ul>
</div>
<h1 id="profiles">6 Application Profiles</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/profiles.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>When you create a Grails application with the <a href="../ref/Command%20Line/create-app.html">create-app</a> command by default the "web" profile is used:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">grails create-app myapp</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can specify a different profile with the profile argument:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">grails create-app myapp --profile=rest-api</code></pre>
</div>
</div>
<div class="paragraph">
<p>Profiles encapsulate the project commands, templates and plugins that are designed to work for a given profile. The source for the profiles can be found <a href="https://github.com/grails-profiles">on Github</a>, whilst the profiles themselves are published as JAR files to the Grails central repository.</p>
</div>
<div class="paragraph">
<p>To find out what profiles are available use the <a href="../ref/Command%20Line/list-profiles.html">list-profiles</a> command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails list-profiles</code></pre>
</div>
</div>
<div class="paragraph">
<p>For more information on a particular profile use the <a href="../ref/Command%20Line/profile-info.html">profile-info</a> command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails profile-info rest-api</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Commands such as <code>profile-info</code> or <code>list-profiles</code> are not available when you invoke the Grails CLI inside a grails project.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_profile_repositories">Profile Repositories</h4>
<div class="paragraph">
<p>By default Grails will resolve profiles from the <a href="https://repo.grails.org/grails/core/org/grails/profiles/">Grails central repository</a>. However, you can override what repositories will be searched by specifying repositories in the <code>USER_HOME/.grails/settings.groovy</code> file.</p>
</div>
<div class="paragraph">
<p>If you want profiles to be resolved with a custom repository in addition to the Grails central repository, you must specify Grails central in the file as well:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails {
profiles {
repositories {
myRepo {
url = <span class="string"><span class="delimiter">&quot;</span><span class="content">http://foo.com/repo</span><span class="delimiter">&quot;</span></span>
snapshotsEnabled = <span class="predefined-constant">true</span>
}
grailsCentral {
url = <span class="string"><span class="delimiter">&quot;</span><span class="content">https://repo.grails.org/grails/core</span><span class="delimiter">&quot;</span></span>
snapshotsEnabled = <span class="predefined-constant">true</span>
}
}
}
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Grails uses Aether to resolve profiles, as a Gradle instance is not yet available when the <code>create-app</code> command is executed. This means that you can also define repositories and more advanced configuration (proxies, authentication etc.) in your <code>USER_HOME/.m2/settings.xml</code> file if you wish.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>It is also possible to store simple credentials for profile repositories directly in the <code>USER_HOME/.grails/settings.groovy</code> file.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails {
profiles {
repositories {
myRepo {
url = <span class="string"><span class="delimiter">&quot;</span><span class="content">http://foo.com/repo</span><span class="delimiter">&quot;</span></span>
snapshotsEnabled = <span class="predefined-constant">true</span>
username = <span class="string"><span class="delimiter">&quot;</span><span class="content">user</span><span class="delimiter">&quot;</span></span>
password = <span class="string"><span class="delimiter">&quot;</span><span class="content">pass</span><span class="delimiter">&quot;</span></span>
}
...
}
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_profile_defaults">Profile Defaults</h4>
<div class="paragraph">
<p>To create an application that uses a custom profile, you must specify the full artifact.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails create-app myapp --profile=com.mycompany.grails.profiles:myprofile:1.0.0</code></pre>
</div>
</div>
<div class="paragraph">
<p>To make this process easier, you can define defaults for a given profile in the <code>USER_HOME/.grails/settings.groovy</code> file.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails {
profiles {
myprofile {
groupId = <span class="string"><span class="delimiter">&quot;</span><span class="content">com.mycompany.grails.profiles</span><span class="delimiter">&quot;</span></span>
version = <span class="string"><span class="delimiter">&quot;</span><span class="content">1.0.0</span><span class="delimiter">&quot;</span></span>
}
repositories {
...
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>With the default values specified, the command to create an application using that profile becomes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails create-app myapp --profile=myprofile</code></pre>
</div>
</div>
</div>
<h2 id="creatingProfiles">6.1 Creating Profiles</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/profiles/creatingProfiles.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>The idea behind creating a new profile is that you can setup a default set of commands and plugins that are tailored to a particular technology or organisation.</p>
</div>
<div class="paragraph">
<p>To create a new profile you can use the <a href="../ref/Command%20Line/create-profile.html">create-profile</a> command which will create a new empty profile that extends the base profile:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails create-profile mycompany</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above command will create a new profile in the "mycompany" directory where the command is executed. If you start interactive mode within the directory you will get a set of commands for creating profiles:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ cd mycompany
$ grails
| Enter a command name to run. Use TAB for completion:
grails&gt;
create-command create-creator-command create-feature create-generator-command create-gradle-command create-template</code></pre>
</div>
</div>
<div class="paragraph">
<p>The commands are as follows:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>create-command</code> - creates a new command that will be available from the Grails CLI when the profile is used</p>
</li>
<li>
<p><code>create-creator-command</code> - creates a command available to the CLI that renders a template (Example: create-controller)</p>
</li>
<li>
<p><code>create-generator-command</code> - creates a command available to the CLI that renders a template based on a domain class (Example: generate-controller)</p>
</li>
<li>
<p><code>create-feature</code> - creates a feature that can be used with this profile</p>
</li>
<li>
<p><code>create-gradle-command</code> - creates a CLI command that can invoke gradle</p>
</li>
<li>
<p><code>create-template</code> - creates a template that can be rendered by a command</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>To customize the dependencies for your profile you can specify additional dependencies in <code>profile.yml</code>.</p>
</div>
<div class="paragraph">
<p>Below is an example <code>profile.yml</code> file:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">features</span>:
<span class="key">defaults</span>:
- <span class="string"><span class="content">hibernate</span></span>
- <span class="string"><span class="content">asset-pipeline</span></span>
<span class="key">build</span>:
<span class="key">plugins</span>:
- <span class="string"><span class="content">org.grails.grails-web</span></span>
<span class="key">excludes</span>:
- <span class="string"><span class="content">org.grails.grails-core</span></span>
<span class="key">dependencies</span>:
<span class="key">compile</span>:
- <span class="string"><span class="delimiter">&quot;</span><span class="content">org.mycompany:myplugin:1.0.1</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>With the above configuration in place you can publish the profile to your local repository with <code>gradle install</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ gradle install</code></pre>
</div>
</div>
<div class="paragraph">
<p>Your profile is now usable with the <code>create-app</code> command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails create-app myapp --profile mycompany</code></pre>
</div>
</div>
<div class="paragraph">
<p>With the above command the application will be created with the "mycompany" profile which includes an additional dependency on the "myplugin" plugin and also includes the "hibernate" and "asset-pipeline" features (more on features later).</p>
</div>
<div class="paragraph">
<p>Note that if you customize the dependency coordinates of the profile (group, version etc.) then you may need to use the fully qualified coordinates to create an application:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails create-app myapp --profile com.mycompany:mycompany:1.0.1</code></pre>
</div>
</div>
<h2 id="profileInheritance">6.2 Profile Inheritance</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/profiles/profileInheritance.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>One profile can extend one or many different parent profiles. To define profile inheritance you can modify the <code>build.gradle</code> of a profile and define the profile dependences. For example typically you want to extend the <code>base</code> profile:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">dependencies {
runtime project(<span class="string"><span class="delimiter">'</span><span class="content">:base</span><span class="delimiter">'</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>By inheriting from a parent profile you get the following benefits:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>When the <a href="../ref/Command%20Line/create-app.html">create-app</a> command is executed the parent profile&#8217;s skeleton is copied first</p>
</li>
<li>
<p>Dependencies and <code>build.gradle</code> is merged from the parent(s)</p>
</li>
<li>
<p>The <code>application.yml</code> file is merged from the parent(s)</p>
</li>
<li>
<p>CLI commands from the parent profile are inherited</p>
</li>
<li>
<p>Features from the parent profile are inherited</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>To define the order of inheritance ensure that your dependencies are declared in the correct order. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">dependencies {
runtime project(<span class="string"><span class="delimiter">'</span><span class="content">:plugin</span><span class="delimiter">'</span></span>)
runtime project(<span class="string"><span class="delimiter">'</span><span class="content">:web</span><span class="delimiter">'</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the above snippet the skeleton from the "plugin" profile is copied first, followed by the "web" profile. In addition, the "web" profile overrides commands from the "plugin" profile, whilst if the dependency order was reversed the "plugin" profile would override the "web" profile.</p>
</div>
<h2 id="publishingProfiles">6.3 Publishing Profiles</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/profiles/publishingProfiles.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_publishing_profiles_to_the_grails_central_repository">Publishing Profiles to the Grails Central Repository</h4>
<div class="paragraph">
<p>Any profile created with the <a href="../ref/Command%20Line/create-profile.html">create-profile</a> command already comes configured with a <code>grails-profile-publish</code> plugin defined in <code>build.gradle</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">apply <span class="key">plugin</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">org.grails.grails-profile-publish</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>To publish a profile using this plugin to the Grails central repository first upload the source to <a href="https://github.com">Github</a> (closed source profiles will not be accepted). Then register for an account on <a href="http://bintray.com">Bintray</a> and configure your keys as follows in the profile&#8217;s <code>build.gradle</code> file:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grailsPublish {
user = <span class="string"><span class="delimiter">'</span><span class="content">YOUR USERNAME</span><span class="delimiter">'</span></span>
key = <span class="string"><span class="delimiter">'</span><span class="content">YOUR KEY</span><span class="delimiter">'</span></span>
githubSlug = <span class="string"><span class="delimiter">'</span><span class="content">your-repo/your-profile</span><span class="delimiter">'</span></span>
license = <span class="string"><span class="delimiter">'</span><span class="content">Apache-2.0</span><span class="delimiter">'</span></span>
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The <code>githubSlug</code> argument should point to the path to your Github repository. For example if your repository is located at <a href="https://github.com/foo/bar" class="bare">https://github.com/foo/bar</a> then your <code>githubSlug</code> is <code>foo/bar</code>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>With this in place you can run <code>gradle publishProfile</code> to publish your profile:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ gradle publishProfile</code></pre>
</div>
</div>
<div class="paragraph">
<p>The profile will be uploaded to Bintray. You can then go the <a href="https://github.com/grails-profiles">Grails profiles repository</a> and request to have your profile included by clicking "Include My Package" button on Bintray&#8217;s interface (you must be logged in to see this).</p>
</div>
</div>
<div class="sect3">
<h4 id="_publishing_profiles_to_an_internal_repository">Publishing Profiles to an Internal Repository</h4>
<div class="paragraph">
<p>The aforementioned <code>grails-profile-publish</code> plugin configures <a href="https://docs.gradle.org/current/userguide/publishing_maven.html">Gradle&#8217;s Maven Publish plugin</a>. In order to publish to an internal repository all you need to do is define the repository in <code>build.gradle</code>. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">publishing {
repositories {
maven {
credentials {
username <span class="string"><span class="delimiter">&quot;</span><span class="content">foo</span><span class="delimiter">&quot;</span></span>
password <span class="string"><span class="delimiter">&quot;</span><span class="content">bar</span><span class="delimiter">&quot;</span></span>
}
url <span class="string"><span class="delimiter">&quot;</span><span class="content">http://foo.com/repo</span><span class="delimiter">&quot;</span></span>
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Once configured you can publish your plugin with <code>gradle publish</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ gradle publish</code></pre>
</div>
</div>
</div>
<h2 id="profileStructure">6.4 Understanding Profiles</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/profiles/profileStructure.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>A profile is a simple directory that contains a <code>profile.yml</code> file and directories containing the "commands", "skeleton" and "templates" defined by the profile. Example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>/web
commands/
create-controller.yml
run-app.groovy
...
features/
asset-pipeline/
skeleton
feature.yml
skeleton/
grails-app/
controllers/
...
build.gradle
templates/
artifacts/
Controller.groovy
profile.yml</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above example is a snippet of structure of the 'web' profile. The <code>profile.yml</code> file is used to describe the profile and control how the build is configured.</p>
</div>
<div class="sect3">
<h4 id="_understanding_the_profile_yml_descriptor">Understanding the profile.yml descriptor</h4>
<div class="paragraph">
<p>The <code>profile.yml</code> can contain the following child elements.</p>
</div>
</div>
<div class="sect3">
<h4 id="_1_repositories">1) repositories</h4>
<div class="paragraph">
<p>A list of Maven repositories to include in the generated build. Example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">repositories</span>:
- <span class="string"><span class="delimiter">&quot;</span><span class="content">https://repo.grails.org/grails/core</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_2_build_repositories">2) build.repositories</h4>
<div class="paragraph">
<p>A list of Maven repositories to include in the buildscript section of the generated build. Example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">build</span>:
<span class="key">repositories</span>:
- <span class="string"><span class="delimiter">&quot;</span><span class="content">https://repo.grails.org/grails/core</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_3_build_plugins">3) build.plugins</h4>
<div class="paragraph">
<p>A list of Gradle plugins to configure in the generated build. Example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">build</span>:
<span class="key">plugins</span>:
- <span class="string"><span class="content">eclipse</span></span>
- <span class="string"><span class="content">idea</span></span>
- <span class="string"><span class="content">org.grails.grails-core</span></span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_4_build_excludes">4) build.excludes</h4>
<div class="paragraph">
<p>A list of Gradle plugins to exclude from being inherited from the parent profile:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">build</span>:
<span class="key">excludes</span>:
- <span class="string"><span class="content">org.grails.grails-core</span></span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_5_dependencies">5) dependencies</h4>
<div class="paragraph">
<p>A map of scopes and dependencies to configure. The <code>excludes</code> scope can be used to exclude from the parent profile. Example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">dependencies</span>:
<span class="key">excludes</span>:
- <span class="string"><span class="delimiter">&quot;</span><span class="content">org.grails:hibernate:*</span><span class="delimiter">&quot;</span></span>
<span class="key">build</span>:
- <span class="string"><span class="delimiter">&quot;</span><span class="content">org.grails:grails-gradle-plugin:$grailsVersion</span><span class="delimiter">&quot;</span></span>
<span class="key">compile</span>:
- <span class="string"><span class="delimiter">&quot;</span><span class="content">org.springframework.boot:spring-boot-starter-logging</span><span class="delimiter">&quot;</span></span>
- <span class="string"><span class="delimiter">&quot;</span><span class="content">org.springframework.boot:spring-boot-autoconfigure</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_6_features_defaults">6) features.defaults</h4>
<div class="paragraph">
<p>A default list of features to use if no explicit features are specified.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">features</span>:
<span class="key">defaults</span>:
- <span class="string"><span class="content">hibernate</span></span>
- <span class="string"><span class="content">asset-pipeline</span></span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_7_skeleton_excludes">7) skeleton.excludes</h4>
<div class="paragraph">
<p>A list of files to exclude from parent profile&#8217;s skeletons (supports wildcards).</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="key">skeleton</span>:
<span class="key">excludes</span>:
- gradlew
- gradlew.bat
- gradle/</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_8_skeleton_parent_target">8) skeleton.parent.target</h4>
<div class="paragraph">
<p>The target folder that parent profile&#8217;s skeleton should be copied into. This can be used to create multi-project builds.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="key">skeleton</span>:
<span class="key">parent</span>:
<span class="key">target</span>: app</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_9_skeleton_binaryextensions">9) skeleton.binaryExtensions</h4>
<div class="paragraph">
<p>Which file extensions should be copied from the profile as binary. Inherited and combined from parent profiles.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="key">skeleton</span>:
<span class="key">binaryExtensions</span>: [exe, zip]</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_10_skeleton_executable">10) skeleton.executable</h4>
<div class="paragraph">
<p>File patterns that should be marked as executable in the resulting application. Inherited and combined from parent profiles. The patterns are parsed with <a href="https://ant.apache.org/manual/dirtasks.html#patterns">Ant</a>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="key">skeleton</span>:
<span class="key">executable</span>:
- <span class="string"><span class="delimiter">&quot;</span><span class="content">**/gradlew*</span><span class="delimiter">&quot;</span></span>
- <span class="string"><span class="delimiter">&quot;</span><span class="content">**/grailsw*</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_11_instructions">11) instructions</h4>
<div class="paragraph">
<p>Text to be displayed to the user after the application is created</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="key">instructions</span>: Here are some instructions</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_what_happens_when_a_profile_is_used">What happens when a profile is used?</h4>
<div class="paragraph">
<p>When the <code>create-app</code> command runs it takes the skeleton of the parent profiles and copies the skeletons into a new project structure.</p>
</div>
<div class="paragraph">
<p>The <code>build.gradle</code> file is generated is result of obtaining all of the dependency information defined in the <code>profile.yml</code> files and produces the required dependencies.</p>
</div>
<div class="paragraph">
<p>The command will also merge any <code>build.gradle</code> files defined within a profile and its parent profiles.</p>
</div>
<div class="paragraph">
<p>The <code>grails-app/conf/application.yml</code> file is also merged into a single YAML file taking into account the profile and all of the parent profiles.</p>
</div>
</div>
<h2 id="profileCommands">6.5 Creating Profile Commands</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/profiles/profileCommands.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>A profile can define new commands that apply only to that profile using YAML or Groovy scripts. Below is an example of the <a href="../ref/Command%20Line/create-controller.html">create-controller</a> command defined in YAML:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">description</span>:
- <span class="string"><span class="content">Creates a controller</span></span>
- <span class="string"><span class="content">usage: 'create-controller &lt;&lt;controller name&gt;&gt;'</span></span>
- <span class="string"><span class="content">completer: org.grails.cli.interactive.completers.DomainClassCompleter</span></span>
- <span class="string"><span class="content">argument: &quot;Controller Name&quot;</span></span>
<span class="key">description</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">The name of the controller</span><span class="delimiter">&quot;</span></span>
<span class="key">steps</span>:
- <span class="string"><span class="content">command: render</span></span>
<span class="key">template</span>: <span class="string"><span class="content">templates/artifacts/Controller.groovy</span></span>
<span class="key">destination</span>: <span class="string"><span class="content">grails-app/controllers/`artifact.package.path`/`artifact.name`Controller.groovy</span></span>
- <span class="string"><span class="content">command: render</span></span>
<span class="key">template</span>: <span class="string"><span class="content">templates/testing/Controller.groovy</span></span>
<span class="key">destination</span>: <span class="string"><span class="content">src/test/groovy/`artifact.package.path`/`artifact.name`ControllerSpec.groovy</span></span>
- <span class="string"><span class="content">command: mkdir</span></span>
<span class="key">location</span>: <span class="string"><span class="content">grails-app/views/`artifact.propertyName`</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Commands defined in YAML must define one or many steps. Each step is a command in itself. The available step types are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>render</code> - To render a template to a given destination (as seen in the previous example)</p>
</li>
<li>
<p><code>mkdir</code> - To make a directory specified by the <code>location</code> parameter</p>
</li>
<li>
<p><code>execute</code> - To execute a command specified by the <code>class</code> parameter. Must be a class that implements the <a href="https://grails.apache.org/docs/3.3.7/api/org/grails/cli/profile/Command.html">Command</a> interface.</p>
</li>
<li>
<p><code>gradle</code> - To execute one or many Gradle tasks specified by the <code>tasks</code> parameter.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>For example to invoke a Gradle task, you can define the following YAML:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">description</span>: <span class="string"><span class="content">Creates a WAR file for deployment to a container (like Tomcat)</span></span>
<span class="key">minArguments</span>: <span class="string"><span class="content">0</span></span>
<span class="key">usage</span>: <span class="string"><span class="delimiter">|</span><span class="content">
war</span></span>
<span class="key">steps</span>:
- <span class="string"><span class="content">command: gradle</span></span>
<span class="key">tasks</span>:
- <span class="string"><span class="content">war</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>If you need more flexiblity than what the declarative YAML approach provides you can create Groovy script commands. Each Command script is extends from the <a href="https://grails.apache.org/docs/3.3.7/api/org/grails/cli/profile/commands/script/GroovyScriptCommand.html">GroovyScriptCommmand</a> class and hence has all of the methods of that class available to it.</p>
</div>
<div class="paragraph">
<p>The following is an example of the <a href="../ref/Command%20Line/create-script.html">create-script</a> command written in Groovy:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">description( <span class="string"><span class="delimiter">&quot;</span><span class="content">Creates a Grails script</span><span class="delimiter">&quot;</span></span> ) {
usage <span class="string"><span class="delimiter">&quot;</span><span class="content">grails create-script &lt;&lt;SCRIPT NAME&gt;&gt;</span><span class="delimiter">&quot;</span></span>
argument <span class="key">name</span>:<span class="string"><span class="delimiter">'</span><span class="content">Script Name</span><span class="delimiter">'</span></span>, <span class="key">description</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">The name of the script to create</span><span class="delimiter">&quot;</span></span>
flag <span class="key">name</span>:<span class="string"><span class="delimiter">'</span><span class="content">force</span><span class="delimiter">'</span></span>, <span class="key">description</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">Whether to overwrite existing files</span><span class="delimiter">&quot;</span></span>
}
<span class="keyword">def</span> scriptName = args[<span class="integer">0</span>]
<span class="keyword">def</span> model = model(scriptName)
<span class="keyword">def</span> overwrite = flag(<span class="string"><span class="delimiter">'</span><span class="content">force</span><span class="delimiter">'</span></span>) ? <span class="predefined-constant">true</span> : <span class="predefined-constant">false</span>
render <span class="key">template</span>: template(<span class="string"><span class="delimiter">'</span><span class="content">artifacts/Script.groovy</span><span class="delimiter">'</span></span>),
<span class="key">destination</span>: file(<span class="string"><span class="delimiter">&quot;</span><span class="content">src/main/scripts/</span><span class="inline"><span class="inline-delimiter">${</span>model.lowerCaseName<span class="inline-delimiter">}</span></span><span class="content">.groovy</span><span class="delimiter">&quot;</span></span>),
<span class="key">model</span>: model,
<span class="key">overwrite</span>: overwrite</code></pre>
</div>
</div>
<div class="paragraph">
<p>For more information on creating CLI commands see the section on <a href="commandLine.html#creatingCustomScripts">creating custom scripts</a> in the Command Line section of the user guide.</p>
</div>
<h2 id="profileFeatures">6.6 Creating Profile Features</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/profiles/profileFeatures.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>A Profile feature is a shareable set of templates and dependencies that may span multiple profiles. Typically you create a base profile that has multiple features and child profiles that inherit from the parent and hence can use the features available from the parent.</p>
</div>
<div class="paragraph">
<p>To create a feature use the <code>create-feature</code> command from the root directory of your profile:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails create-feature myfeature</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will create a <code>myfeature/feature.yml</code> file that looks like the following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">description</span>: <span class="string"><span class="content">Description of the feature</span></span>
<span class="comment"># customize versions here</span>
<span class="comment"># dependencies:</span>
<span class="comment"># compile:</span>
<span class="comment"># - &quot;org.grails.plugins:myplugin2:1.0&quot;</span>
<span class="comment">#</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>As a more concrete example. The following is the <code>feature.yml</code> file from the "asset-pipeline" feature:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">description</span>: <span class="string"><span class="content">Adds Asset Pipeline to a Grails project</span></span>
<span class="key">build</span>:
<span class="key">plugins</span>:
- <span class="string"><span class="content">asset-pipeline</span></span>
<span class="key">dependencies</span>:
<span class="key">build</span>:
- <span class="string"><span class="content">'com.bertramlabs.plugins:asset-pipeline-gradle:2.5.0'</span></span>
<span class="key">runtime</span>:
- <span class="string"><span class="delimiter">&quot;</span><span class="content">org.grails.plugins:asset-pipeline</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The structure of a feature is as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>FEATURE_DIR
feature.yml
skeleton/
grails-app/
conf/
application.yml
build.gradle</code></pre>
</div>
</div>
<div class="paragraph">
<p>The contents of the skeleton get copied into the application tree, whilst the <code>application.yml</code> and <code>build.gradle</code> get merged with their respective counterparts in the profile by used.</p>
</div>
<div class="paragraph">
<p>With the <code>feature.yml</code> you can define additional dependencies. This allows users to create applications with optional features. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails create-app myapp --profile myprofile --features myfeature,hibernate</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above example will create a new application using your new feature and the "hibernate" feature.</p>
</div>
<a name="5. Object Relational Mapping (GORM)"><!-- Legacy link --></a>
<h1 id="GORM">7 Object Relational Mapping (GORM)</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/GORM.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>GORM is Grails' object relational mapping (ORM) implementation. Under the hood it uses Hibernate (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>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> book = <span class="predefined-type">Book</span>.findByTitle(<span class="string"><span class="delimiter">&quot;</span><span class="content">Groovy in Action</span><span class="delimiter">&quot;</span></span>)
book
.addToAuthors(<span class="key">name</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">Dierk Koenig</span><span class="delimiter">&quot;</span></span>)
.addToAuthors(<span class="key">name</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">Guillaume LaForge</span><span class="delimiter">&quot;</span></span>)
.save()</code></pre>
</div>
</div>
<a name="5.1 Quick Start Guide"><!-- Legacy link --></a>
<h2 id="quickStartGuide">7.1 Quick Start Guide</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/GORM/quickStartGuide.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>A domain class can be created with the <a href="#ref-command-line-create-domain-class">create-domain-class</a> command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails create-domain-<span class="type">class</span> <span class="class">helloworld</span>.Person</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
If no package is specified with the create-domain-class script, Grails automatically uses the application name as the package name.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>This will create a class at the location <code>grails-app/domain/helloworld/Person.groovy</code> such as the one below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> helloworld
<span class="type">class</span> <span class="class">Person</span> {
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
If you have the <code>dbCreate</code> property set to "update", "create" or "create-drop" on your <a href="conf.html#dataSource">DataSource</a>, Grails will automatically generate/modify the database tables for you.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>You can customize the class by adding properties:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Person</span> {
<span class="predefined-type">String</span> name
<span class="predefined-type">Integer</span> age
<span class="predefined-type">Date</span> lastVisit
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Once you have a domain class try and manipulate it with the <a href="#ref-command-line-shell">shell</a> or <a href="#ref-command-line-console">console</a> by typing:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails console</code></pre>
</div>
</div>
<div class="paragraph">
<p>This loads an interactive GUI where you can run Groovy commands with access to the Spring ApplicationContext, GORM, etc.</p>
</div>
<a name="5.1.1 Basic CRUD"><!-- Legacy link --></a>
<h2 id="basicCRUD">7.1.1 Basic CRUD</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/GORM/quickStartGuide/basicCRUD.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Try performing some basic CRUD (Create/Read/Update/Delete) operations.</p>
</div>
<div class="sect2">
<h3 id="_create">Create</h3>
<div class="paragraph">
<p>To create a domain class use Map constructor to set its properties and call <a href="#ref-domain-classes-save">save</a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> p = <span class="keyword">new</span> Person(<span class="key">name</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">Fred</span><span class="delimiter">&quot;</span></span>, <span class="key">age</span>: <span class="integer">40</span>, <span class="key">lastVisit</span>: <span class="keyword">new</span> <span class="predefined-type">Date</span>())
p.save()</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <a href="#ref-domain-classes-save">save</a> method will persist your class to the database using the underlying Hibernate ORM layer.</p>
</div>
</div>
<div class="sect2">
<h3 id="_read">Read</h3>
<div class="paragraph">
<p>Grails transparently adds an implicit <code>id</code> property to your domain class which you can use for retrieval:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> p = Person.get(<span class="integer">1</span>)
<span class="keyword">assert</span> <span class="integer">1</span> == p.id</code></pre>
</div>
</div>
<div class="paragraph">
<p>This uses the <a href="#ref-domain-classes-get">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">read</a> method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> p = Person.read(<span class="integer">1</span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>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">save</a> method then the object is placed back into a read-write state.</p>
</div>
<div class="paragraph">
<p>In addition, you can also load a proxy for an instance by using the <a href="#ref-domain-classes-load">load</a> method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> p = Person.load(<span class="integer">1</span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
</div>
<div class="sect2">
<h3 id="_update">Update</h3>
<div class="paragraph">
<p>To update an instance, change some properties and then call <a href="#ref-domain-classes-save">save</a> again:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> p = Person.get(<span class="integer">1</span>)
p.name = <span class="string"><span class="delimiter">&quot;</span><span class="content">Bob</span><span class="delimiter">&quot;</span></span>
p.save()</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_delete">Delete</h3>
<div class="paragraph">
<p>To delete an instance use the <a href="#ref-domain-classes-delete">delete</a> method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> p = Person.get(<span class="integer">1</span>)
p.delete()</code></pre>
</div>
</div>
</div>
<h2 id="furtherReading">7.2 Further Reading on GORM</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/GORM/furtherReading.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>For more information on using GORM see the <a href="https://grails.apache.org/docs-legacy-gorm/6.1.x/hibernate">dedicated documentation</a> for the GORM project.</p>
</div>
<a name="7. The Web Layer"><!-- Legacy link --></a>
<h1 id="theWebLayer">8 The Web Layer</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<a name="7.1 Controllers"><!-- Legacy link --></a>
<h2 id="controllers">8.1 Controllers</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/controllers.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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&#8217;s in a package).</p>
</div>
<div class="paragraph">
<p>The default <a href="#urlmappings">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.</p>
</div>
<a name="7.1.1 Understanding Controllers and Actions"><!-- Legacy link --></a>
<h2 id="understandingControllersAndActions">8.1.1 Understanding Controllers and Actions</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/controllers/understandingControllersAndActions.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_creating_a_controller">Creating a controller</h4>
<div class="paragraph">
<p>Controllers can be created with the <a href="../ref/Command%20Line/create-controller.html">create-controller</a> or <a href="../ref/Command%20Line/generate-controller.html">generate-controller</a> command. For example try running the following command from the root of a Grails project:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">grails create-controller book</code></pre>
</div>
</div>
<div class="paragraph">
<p>The command will create a controller at the location <code>grails-app/controllers/myapp/BookController.groovy</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> myapp
<span class="type">class</span> <span class="class">BookController</span> {
<span class="keyword">def</span> <span class="function">index</span>() { }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>where "myapp" will be the name of your application, the default package name if one isn&#8217;t specified.</p>
</div>
<div class="paragraph">
<p><code>BookController</code> by default maps to the /book URI (relative to your application root).</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
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
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_creating_actions">Creating Actions</h4>
<div class="paragraph">
<p>A controller can have multiple public action methods; each one maps to a URI:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> {
<span class="keyword">def</span> <span class="function">list</span>() {
<span class="comment">// do controller logic</span>
<span class="comment">// create model</span>
<span class="keyword">return</span> model
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This example maps to the <code>/book/list</code> URI by default thanks to the property being named <code>list</code>.</p>
</div>
</div>
<div class="sect3">
<h4 id="_the_default_action">The Default Action</h4>
<div class="paragraph">
<p>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:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>If there is only one action, it&#8217;s the default</p>
</li>
<li>
<p>If you have an action named <code>index</code>, it&#8217;s the default</p>
</li>
<li>
<p>Alternatively you can set it explicitly with the <code>defaultAction</code> property:</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> defaultAction = <span class="string"><span class="delimiter">&quot;</span><span class="content">list</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
</div>
<a name="7.1.2 Controllers and Scopes"><!-- Legacy link --></a>
<h2 id="controllersAndScopes">8.1.2 Controllers and Scopes</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/controllers/controllersAndScopes.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_available_scopes">Available Scopes</h4>
<div class="paragraph">
<p>Scopes are hash-like objects where you can store variables. The following scopes are available to controllers:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="../ref/Controllers/servletContext.html">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="https://docs.oracle.com/javaee/7/api/javax/servlet/ServletContext.html">ServletContext</a></p>
</li>
<li>
<p><a href="../ref/Controllers/session.html">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="https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpSession.html">HttpSession</a></p>
</li>
<li>
<p><a href="../ref/Controllers/request.html">request</a> - The request object allows the storage of objects for the current request only. The request object is an instance of <a href="https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html">HttpServletRequest</a></p>
</li>
<li>
<p><a href="../ref/Controllers/params.html">params</a> - Mutable map of incoming request query string or POST parameters</p>
</li>
<li>
<p><a href="../ref/Controllers/flash.html">flash</a> - See below</p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_accessing_scopes">Accessing Scopes</h4>
<div class="paragraph">
<p>Scopes can be accessed using the variable names above in combination with Groovy&#8217;s array index operator, even on classes provided by the Servlet API such as the <a href="https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html">HttpServletRequest</a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> {
<span class="keyword">def</span> <span class="function">find</span>() {
<span class="keyword">def</span> findBy = params[<span class="string"><span class="delimiter">&quot;</span><span class="content">findBy</span><span class="delimiter">&quot;</span></span>]
<span class="keyword">def</span> appContext = request[<span class="string"><span class="delimiter">&quot;</span><span class="content">foo</span><span class="delimiter">&quot;</span></span>]
<span class="keyword">def</span> loggedUser = session[<span class="string"><span class="delimiter">&quot;</span><span class="content">logged_user</span><span class="delimiter">&quot;</span></span>]
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also access values within scopes using the de-reference operator, making the syntax even more clear:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> {
<span class="keyword">def</span> <span class="function">find</span>() {
<span class="keyword">def</span> findBy = params.findBy
<span class="keyword">def</span> appContext = request.foo
<span class="keyword">def</span> loggedUser = session.logged_user
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This is one of the ways that Grails unifies access to the different scopes.</p>
</div>
</div>
<div class="sect3">
<h4 id="_using_flash_scope">Using Flash Scope</h4>
<div class="paragraph">
<p>Grails supports the concept of <a href="../ref/Controllers/flash.html">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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">delete</span>() {
<span class="keyword">def</span> b = <span class="predefined-type">Book</span>.get(params.id)
<span class="keyword">if</span> (!b) {
flash.message = <span class="string"><span class="delimiter">&quot;</span><span class="content">User not found for id </span><span class="inline"><span class="inline-delimiter">${</span>params.id<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>
redirect(<span class="key">action</span>:list)
}
... <span class="comment">// remaining code</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>When the <code>delete</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>
</div>
<div class="paragraph">
<p>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>
</div>
</div>
<div class="sect3">
<h4 id="_scoped_controllers">Scoped Controllers</h4>
<div class="paragraph">
<p>Newly created applications have the <code>grails.controllers.defaultScope</code> property set to a value of "singleton" in <code>application.yml</code>. You may change this value to any
of the supported scopes listed below. If the property is not assigned a value at all, controllers will default to "prototype" scope.</p>
</div>
<div class="paragraph">
<p>Supported controller scopes are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>prototype</code> (default) - A new controller will be created for each request (recommended for actions as Closure properties)</p>
</li>
<li>
<p><code>session</code> - One controller is created for the scope of a user session</p>
</li>
<li>
<p><code>singleton</code> - Only one instance of the controller ever exists (recommended for actions as methods)</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> scope = <span class="string"><span class="delimiter">&quot;</span><span class="content">singleton</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>You can define the default strategy in <code>application.yml</code> with the <code>grails.controllers.defaultScope</code> key, for example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="key">grails</span>:
<span class="key">controllers</span>:
<span class="key">defaultScope</span>: singleton</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Use scoped controllers wisely. For instance, we don&#8217;t recommend having any properties in a singleton-scoped controller since they will be shared for <em>all</em> requests.
</td>
</tr>
</table>
</div>
</div>
<a name="7.1.3 Models and Views"><!-- Legacy link --></a>
<h2 id="modelsAndViews">8.1.3 Models and Views</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/controllers/modelsAndViews.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_returning_the_model">Returning the Model</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">show</span>() {
[<span class="key">book</span>: <span class="predefined-type">Book</span>.get(params.id)]
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The above does <em>not</em> reflect what you should use with the scaffolding views - see the <a href="scaffolding.html">scaffolding section</a> for more details.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>A more advanced approach is to return an instance of the Spring <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/ModelAndView.html">ModelAndView</a> class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">org.springframework.web.servlet.ModelAndView</span>
<span class="keyword">def</span> <span class="function">index</span>() {
<span class="comment">// get some books just for the index page, perhaps your favorites</span>
<span class="keyword">def</span> favoriteBooks = ...
<span class="comment">// forward to the list view to show them</span>
<span class="keyword">return</span> <span class="keyword">new</span> ModelAndView(<span class="string"><span class="delimiter">&quot;</span><span class="content">/book/list</span><span class="delimiter">&quot;</span></span>, [ bookList : favoriteBooks ])
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>One thing to bear in mind is that certain variable names can not be used in your model:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>attributes</code></p>
</li>
<li>
<p><code>application</code></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Currently, no error will be reported if you do use them, but this will hopefully change in a future version of Grails.</p>
</div>
</div>
<div class="sect3">
<h4 id="_selecting_the_view">Selecting the View</h4>
<div class="paragraph">
<p>In both of the previous two examples there was no code that specified which <a href="#gsp">view</a> to render. So how does Grails know which one to pick? The answer lies in the conventions. Grails will look for a view at the location <code>grails-app/views/book/show.gsp</code> for this <code>show</code> action:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> {
<span class="keyword">def</span> <span class="function">show</span>() {
[<span class="key">book</span>: <span class="predefined-type">Book</span>.get(params.id)]
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>To render a different view, use the <a href="../ref/Controllers/render.html">render</a> method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">show</span>() {
<span class="keyword">def</span> map = [<span class="key">book</span>: <span class="predefined-type">Book</span>.get(params.id)]
render(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">display</span><span class="delimiter">&quot;</span></span>, <span class="key">model</span>: map)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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 use an absolute path instead of a relative one:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">show</span>() {
<span class="keyword">def</span> map = [<span class="key">book</span>: <span class="predefined-type">Book</span>.get(params.id)]
render(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/shared/display</span><span class="delimiter">&quot;</span></span>, <span class="key">model</span>: map)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this case Grails will attempt to render a view at the location <code>grails-app/views/shared/display.gsp</code>.</p>
</div>
<div class="paragraph">
<p>Grails also supports JSPs as views, so if a GSP isn&#8217;t found in the expected location but a JSP is, it will be used instead.</p>
</div>
</div>
<div class="sect3">
<h4 id="_selecting_views_for_namespaced_controllers">Selecting Views For Namespaced Controllers</h4>
<div class="paragraph">
<p>If a controller defines a namespace for itself with the <a href="#namespacedControllers">namespace</a> property that will affect the root directory in which Grails will look for views which are specified with a relative path. The default root directory for views rendered by a namespaced controller is <code>grails-app/views/&lt;namespace name&gt;/&lt;controller name&gt;/</code>. If the view is not found in the namespaced directory then Grails will fallback to looking for the view in the non-namespaced directory.</p>
</div>
<div class="paragraph">
<p>See the example below.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ReportingController</span> {
<span class="directive">static</span> namespace = <span class="string"><span class="delimiter">'</span><span class="content">business</span><span class="delimiter">'</span></span>
<span class="keyword">def</span> <span class="function">humanResources</span>() {
<span class="comment">// This will render grails-app/views/business/reporting/humanResources.gsp</span>
<span class="comment">// if it exists.</span>
<span class="comment">// If grails-app/views/business/reporting/humanResources.gsp does not</span>
<span class="comment">// exist the fallback will be grails-app/views/reporting/humanResources.gsp.</span>
<span class="comment">// The namespaced GSP will take precedence over the non-namespaced GSP.</span>
[<span class="key">numberOfEmployees</span>: <span class="integer">9</span>]
}
<span class="keyword">def</span> <span class="function">accountsReceivable</span>() {
<span class="comment">// This will render grails-app/views/business/reporting/numberCrunch.gsp</span>
<span class="comment">// if it exists.</span>
<span class="comment">// If grails-app/views/business/reporting/numberCrunch.gsp does not</span>
<span class="comment">// exist the fallback will be grails-app/views/reporting/numberCrunch.gsp.</span>
<span class="comment">// The namespaced GSP will take precedence over the non-namespaced GSP.</span>
render <span class="key">view</span>: <span class="string"><span class="delimiter">'</span><span class="content">numberCrunch</span><span class="delimiter">'</span></span>, <span class="key">model</span>: [<span class="key">numberOfEmployees</span>: <span class="integer">13</span>]
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_rendering_a_response">Rendering a Response</h4>
<div class="paragraph">
<p>Sometimes it&#8217;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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">render <span class="string"><span class="delimiter">&quot;</span><span class="content">Hello World!</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The above code writes the text "Hello World!" to the response. Other examples include:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// write some markup</span>
render {
<span class="keyword">for</span> (b <span class="keyword">in</span> books) {
div(<span class="key">id</span>: b.id, b.title)
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// render a specific view</span>
render(<span class="key">view</span>: <span class="string"><span class="delimiter">'</span><span class="content">show</span><span class="delimiter">'</span></span>)</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// render a template for each item in a collection</span>
render(<span class="key">template</span>: <span class="string"><span class="delimiter">'</span><span class="content">book_template</span><span class="delimiter">'</span></span>, <span class="key">collection</span>: <span class="predefined-type">Book</span>.list())</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// render some text with encoding and content type</span>
render(<span class="key">text</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">&lt;xml&gt;some xml&lt;/xml&gt;</span><span class="delimiter">&quot;</span></span>, <span class="key">contentType</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">text/xml</span><span class="delimiter">&quot;</span></span>, <span class="key">encoding</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">UTF-8</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you plan on using Groovy&#8217;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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">groovy.xml.MarkupBuilder</span>
...
def login() {
<span class="keyword">def</span> writer = <span class="keyword">new</span> <span class="predefined-type">StringWriter</span>()
<span class="keyword">def</span> builder = <span class="keyword">new</span> MarkupBuilder(writer)
builder.html {
head {
title <span class="string"><span class="delimiter">'</span><span class="content">Log in</span><span class="delimiter">'</span></span>
}
body {
h1 <span class="string"><span class="delimiter">'</span><span class="content">Hello</span><span class="delimiter">'</span></span>
form {
}
}
}
<span class="keyword">def</span> html = writer.toString()
render html
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will actually <a href="#tagsAsMethodCalls">call the form tag</a> (which will return some text that will be ignored by the <code>MarkupBuilder</code>). To correctly output a <code>&lt;form&gt;</code> element, use the following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">login</span>() {
<span class="comment">// ...</span>
body {
h1 <span class="string"><span class="delimiter">'</span><span class="content">Hello</span><span class="delimiter">'</span></span>
builder.form {
}
}
<span class="comment">// ...</span>
}</code></pre>
</div>
</div>
</div>
<a name="7.1.4 Redirects and Chaining"><!-- Legacy link --></a>
<h2 id="redirectsAndChaining">8.1.4 Redirects and Chaining</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/controllers/redirectsAndChaining.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_redirects">Redirects</h4>
<div class="paragraph">
<p>Actions can be redirected using the <a href="../ref/Controllers/redirect.html">redirect</a> controller method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">OverviewController</span> {
<span class="keyword">def</span> <span class="function">login</span>() {}
<span class="keyword">def</span> <span class="function">find</span>() {
<span class="keyword">if</span> (!session.user)
redirect(<span class="key">action</span>: <span class="string"><span class="delimiter">'</span><span class="content">login</span><span class="delimiter">'</span></span>)
<span class="keyword">return</span>
}
...
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Internally the <a href="../ref/Controllers/redirect.html">redirect</a> method uses the <a href="https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletResponse.html">HttpServletResponse</a> object&#8217;s <code>sendRedirect</code> method.</p>
</div>
<div class="paragraph">
<p>The <code>redirect</code> method expects one of:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>The name of an action (and controller name if the redirect isn&#8217;t to an action in the current controller):</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// Also redirects to the index action in the home controller</span>
redirect(<span class="key">controller</span>: <span class="string"><span class="delimiter">'</span><span class="content">home</span><span class="delimiter">'</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">'</span><span class="content">index</span><span class="delimiter">'</span></span>)</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>A URI for a resource relative the application context path:</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// Redirect to an explicit URI</span>
redirect(<span class="key">uri</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/login.html</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>Or a full URL:</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// Redirect to a URL</span>
redirect(<span class="key">url</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">http://grails.org</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>A <a href="GORM.html">domain class</a> instance:</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// Redirect to the domain instance</span>
<span class="predefined-type">Book</span> book = ... <span class="comment">// obtain a domain instance</span>
redirect book</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the above example Grails will construct a link using the domain class <code>id</code> (if present).</p>
</div>
<div class="paragraph">
<p>Parameters can optionally be passed from one action to the next using the <code>params</code> argument of the method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">redirect(<span class="key">action</span>: <span class="string"><span class="delimiter">'</span><span class="content">myaction</span><span class="delimiter">'</span></span>, <span class="key">params</span>: [<span class="key">myparam</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">myvalue</span><span class="delimiter">&quot;</span></span>])</code></pre>
</div>
</div>
<div class="paragraph">
<p>These parameters are made available through the <a href="../ref/Controllers/params.html">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>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">redirect(<span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">next</span><span class="delimiter">&quot;</span></span>, <span class="key">params</span>: params)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Finally, you can also include a fragment in the target URI:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">redirect(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">test</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>, <span class="key">fragment</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">profile</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>which will (depending on the URL mappings) redirect to something like "/myapp/test/show#profile".</p>
</div>
</div>
<div class="sect3">
<h4 id="_chaining">Chaining</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ExampleChainController</span> {
<span class="keyword">def</span> <span class="function">first</span>() {
chain(<span class="key">action</span>: second, <span class="key">model</span>: [<span class="key">one</span>: <span class="integer">1</span>])
}
<span class="keyword">def</span> <span class="function">second</span> () {
chain(<span class="key">action</span>: third, <span class="key">model</span>: [<span class="key">two</span>: <span class="integer">2</span>])
}
<span class="keyword">def</span> <span class="function">third</span>() {
[<span class="key">three</span>: <span class="integer">3</span>])
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>results in the model:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">[<span class="key">one</span>: <span class="integer">1</span>, <span class="key">two</span>: <span class="integer">2</span>, <span class="key">three</span>: <span class="integer">3</span>]</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ChainController</span> {
<span class="keyword">def</span> <span class="function">nextInChain</span>() {
<span class="keyword">def</span> model = chainModel.myModel
...
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Like the <code>redirect</code> method you can also pass parameters to the <code>chain</code> method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">chain(<span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">action1</span><span class="delimiter">&quot;</span></span>, <span class="key">model</span>: [<span class="key">one</span>: <span class="integer">1</span>], <span class="key">params</span>: [<span class="key">myparam</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">param1</span><span class="delimiter">&quot;</span></span>])</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The chain method uses the HTTP session and hence should only be used if your application is stateful.
</td>
</tr>
</table>
</div>
</div>
<a name="7.1.6 Data Binding"><!-- Legacy link --></a>
<h2 id="dataBinding">8.1.5 Data Binding</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/controllers/dataBinding.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="sect3">
<h4 id="_map_based_binding">Map Based Binding</h4>
<div class="paragraph">
<p>The data binder is capable of converting and assigning values in a Map to properties of an object. The binder will associate entries in the Map to properties of the object using the keys in the Map that have values which correspond to property names on the object. The following code demonstrates the basics:</p>
</div>
<div class="listingblock">
<div class="title">grails-app/domain/Person.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Person</span> {
<span class="predefined-type">String</span> firstName
<span class="predefined-type">String</span> lastName
<span class="predefined-type">Integer</span> age
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> bindingMap = [<span class="key">firstName</span>: <span class="string"><span class="delimiter">'</span><span class="content">Peter</span><span class="delimiter">'</span></span>, <span class="key">lastName</span>: <span class="string"><span class="delimiter">'</span><span class="content">Gabriel</span><span class="delimiter">'</span></span>, <span class="key">age</span>: <span class="integer">63</span>]
<span class="keyword">def</span> person = <span class="keyword">new</span> Person(bindingMap)
<span class="keyword">assert</span> person.firstName == <span class="string"><span class="delimiter">'</span><span class="content">Peter</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> person.lastName == <span class="string"><span class="delimiter">'</span><span class="content">Gabriel</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> person.age == <span class="integer">63</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>To update properties of a domain object you may assign a Map to the <code>properties</code> property of the domain class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> bindingMap = [<span class="key">firstName</span>: <span class="string"><span class="delimiter">'</span><span class="content">Peter</span><span class="delimiter">'</span></span>, <span class="key">lastName</span>: <span class="string"><span class="delimiter">'</span><span class="content">Gabriel</span><span class="delimiter">'</span></span>, <span class="key">age</span>: <span class="integer">63</span>]
<span class="keyword">def</span> person = Person.get(someId)
person.properties = bindingMap
<span class="keyword">assert</span> person.firstName == <span class="string"><span class="delimiter">'</span><span class="content">Peter</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> person.lastName == <span class="string"><span class="delimiter">'</span><span class="content">Gabriel</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> person.age == <span class="integer">63</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The binder can populate a full graph of objects using Maps of Maps.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Person</span> {
<span class="predefined-type">String</span> firstName
<span class="predefined-type">String</span> lastName
<span class="predefined-type">Integer</span> age
Address homeAddress
}
<span class="type">class</span> <span class="class">Address</span> {
<span class="predefined-type">String</span> county
<span class="predefined-type">String</span> country
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> bindingMap = [<span class="key">firstName</span>: <span class="string"><span class="delimiter">'</span><span class="content">Peter</span><span class="delimiter">'</span></span>, <span class="key">lastName</span>: <span class="string"><span class="delimiter">'</span><span class="content">Gabriel</span><span class="delimiter">'</span></span>, <span class="key">age</span>: <span class="integer">63</span>, <span class="key">homeAddress</span>: [<span class="key">county</span>: <span class="string"><span class="delimiter">'</span><span class="content">Surrey</span><span class="delimiter">'</span></span>, <span class="key">country</span>: <span class="string"><span class="delimiter">'</span><span class="content">England</span><span class="delimiter">'</span></span>] ]
<span class="keyword">def</span> person = <span class="keyword">new</span> Person(bindingMap)
<span class="keyword">assert</span> person.firstName == <span class="string"><span class="delimiter">'</span><span class="content">Peter</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> person.lastName == <span class="string"><span class="delimiter">'</span><span class="content">Gabriel</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> person.age == <span class="integer">63</span>
<span class="keyword">assert</span> person.homeAddress.county == <span class="string"><span class="delimiter">'</span><span class="content">Surrey</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> person.homeAddress.country == <span class="string"><span class="delimiter">'</span><span class="content">England</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_binding_to_collections_and_maps">Binding To Collections And Maps</h4>
<div class="paragraph">
<p>The data binder can populate and update Collections and Maps. The following code shows a simple example of populating a <code>List</code> of objects in a domain class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Band</span> {
<span class="predefined-type">String</span> name
<span class="directive">static</span> hasMany = [<span class="key">albums</span>: Album]
<span class="predefined-type">List</span> albums
}
<span class="type">class</span> <span class="class">Album</span> {
<span class="predefined-type">String</span> title
<span class="predefined-type">Integer</span> numberOfTracks
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> bindingMap = [<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Genesis</span><span class="delimiter">'</span></span>,
<span class="string"><span class="delimiter">'</span><span class="content">albums[0]</span><span class="delimiter">'</span></span>: [<span class="key">title</span>: <span class="string"><span class="delimiter">'</span><span class="content">Foxtrot</span><span class="delimiter">'</span></span>, <span class="key">numberOfTracks</span>: <span class="integer">6</span>],
<span class="string"><span class="delimiter">'</span><span class="content">albums[1]</span><span class="delimiter">'</span></span>: [<span class="key">title</span>: <span class="string"><span class="delimiter">'</span><span class="content">Nursery Cryme</span><span class="delimiter">'</span></span>, <span class="key">numberOfTracks</span>: <span class="integer">7</span>]]
<span class="keyword">def</span> band = <span class="keyword">new</span> Band(bindingMap)
<span class="keyword">assert</span> band.name == <span class="string"><span class="delimiter">'</span><span class="content">Genesis</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> band.albums.size() == <span class="integer">2</span>
<span class="keyword">assert</span> band.albums[<span class="integer">0</span>].title == <span class="string"><span class="delimiter">'</span><span class="content">Foxtrot</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> band.albums[<span class="integer">0</span>].numberOfTracks == <span class="integer">6</span>
<span class="keyword">assert</span> band.albums[<span class="integer">1</span>].title == <span class="string"><span class="delimiter">'</span><span class="content">Nursery Cryme</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> band.albums[<span class="integer">1</span>].numberOfTracks == <span class="integer">7</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>That code would work in the same way if <code>albums</code> were an array instead of a <code>List</code>.</p>
</div>
<div class="paragraph">
<p>Note that when binding to a <code>Set</code> the structure of the <code>Map</code> being bound to the <code>Set</code> is the same as that of a <code>Map</code> being bound to a <code>List</code> but since a <code>Set</code> is unordered, the indexes don&#8217;t necessarily correspond to the order of elements in the <code>Set</code>. In the code example above, if <code>albums</code> were a <code>Set</code> instead of a <code>List</code>, the <code>bindingMap</code> could look exactly the same but 'Foxtrot' might be the first album in the <code>Set</code> or it might be the second. When updating existing elements in a <code>Set</code> the <code>Map</code> being assigned to the <code>Set</code> must have <code>id</code> elements in it which represent the element in the <code>Set</code> being updated, as in the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">/*
* The value of the indexes 0 and 1 in albums[0] and albums[1] are arbitrary
* values that can be anything as long as they are unique within the Map.
* They do not correspond to the order of elements in albums because albums
* is a Set.
*/</span>
<span class="keyword">def</span> bindingMap = [<span class="string"><span class="delimiter">'</span><span class="content">albums[0]</span><span class="delimiter">'</span></span>: [<span class="key">id</span>: <span class="integer">9</span>, <span class="key">title</span>: <span class="string"><span class="delimiter">'</span><span class="content">The Lamb Lies Down On Broadway</span><span class="delimiter">'</span></span>]
<span class="string"><span class="delimiter">'</span><span class="content">albums[1]</span><span class="delimiter">'</span></span>: [<span class="key">id</span>: <span class="integer">4</span>, <span class="key">title</span>: <span class="string"><span class="delimiter">'</span><span class="content">Selling England By The Pound</span><span class="delimiter">'</span></span>]]
<span class="keyword">def</span> band = Band.get(someBandId)
<span class="comment">/*
* This will find the Album in albums that has an id of 9 and will set its title
* to 'The Lamb Lies Down On Broadway' and will find the Album in albums that has
* an id of 4 and set its title to 'Selling England By The Pound'. In both
* cases if the Album cannot be found in albums then the album will be retrieved
* from the database by id, the Album will be added to albums and will be updated
* with the values described above. If a Album with the specified id cannot be
* found in the database, then a binding error will be created and associated
* with the band object. More on binding errors later.
*/</span>
band.properties = bindingMap</code></pre>
</div>
</div>
<div class="paragraph">
<p>When binding to a <code>Map</code> the structure of the binding <code>Map</code> is the same as the structure of a <code>Map</code> used for binding to a <code>List</code> or a <code>Set</code> and the index inside of square brackets corresponds to the key in the <code>Map</code> being bound to. See the following code:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Album</span> {
<span class="predefined-type">String</span> title
<span class="directive">static</span> hasMany = [<span class="key">players</span>: Player]
<span class="predefined-type">Map</span> players
}
<span class="type">class</span> <span class="class">Player</span> {
<span class="predefined-type">String</span> name
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> bindingMap = [<span class="key">title</span>: <span class="string"><span class="delimiter">'</span><span class="content">The Lamb Lies Down On Broadway</span><span class="delimiter">'</span></span>,
<span class="string"><span class="delimiter">'</span><span class="content">players[guitar]</span><span class="delimiter">'</span></span>: [<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Steve Hackett</span><span class="delimiter">'</span></span>],
<span class="string"><span class="delimiter">'</span><span class="content">players[vocals]</span><span class="delimiter">'</span></span>: [<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Peter Gabriel</span><span class="delimiter">'</span></span>],
<span class="string"><span class="delimiter">'</span><span class="content">players[keyboards]</span><span class="delimiter">'</span></span>: [<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Tony Banks</span><span class="delimiter">'</span></span>]]
<span class="keyword">def</span> album = <span class="keyword">new</span> Album(bindingMap)
<span class="keyword">assert</span> album.title == <span class="string"><span class="delimiter">'</span><span class="content">The Lamb Lies Down On Broadway</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> album.players.size() == <span class="integer">3</span>
<span class="keyword">assert</span> album.players.guitar.name == <span class="string"><span class="delimiter">'</span><span class="content">Steve Hackett</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> album.players.vocals.name == <span class="string"><span class="delimiter">'</span><span class="content">Peter Gabriel</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> album.players.keyboards.name == <span class="string"><span class="delimiter">'</span><span class="content">Tony Banks</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>When updating an existing <code>Map</code>, if the key specified in the binding <code>Map</code> does not exist in the <code>Map</code> being bound to then a new value will be created and added to the <code>Map</code> with the specified key as in the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> bindingMap = [<span class="key">title</span>: <span class="string"><span class="delimiter">'</span><span class="content">The Lamb Lies Down On Broadway</span><span class="delimiter">'</span></span>,
<span class="string"><span class="delimiter">'</span><span class="content">players[guitar]</span><span class="delimiter">'</span></span>: [<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Steve Hackett</span><span class="delimiter">'</span></span>],
<span class="string"><span class="delimiter">'</span><span class="content">players[vocals]</span><span class="delimiter">'</span></span>: [<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Peter Gabriel</span><span class="delimiter">'</span></span>],
<span class="string"><span class="delimiter">'</span><span class="content">players[keyboards]</span><span class="delimiter">'</span></span>: [<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Tony Banks</span><span class="delimiter">'</span></span>]]
<span class="keyword">def</span> album = <span class="keyword">new</span> Album(bindingMap)
<span class="keyword">assert</span> album.title == <span class="string"><span class="delimiter">'</span><span class="content">The Lamb Lies Down On Broadway</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> album.players.size() == <span class="integer">3</span>
<span class="keyword">assert</span> album.players.guitar.name == <span class="string"><span class="delimiter">'</span><span class="content">Steve Hackett</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> album.players.vocals.name == <span class="string"><span class="delimiter">'</span><span class="content">Peter Gabriel</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> album.players.keyboards.name == <span class="string"><span class="delimiter">'</span><span class="content">Tony Banks</span><span class="delimiter">'</span></span>
<span class="keyword">def</span> updatedBindingMap = [<span class="string"><span class="delimiter">'</span><span class="content">players[drums]</span><span class="delimiter">'</span></span>: [<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Phil Collins</span><span class="delimiter">'</span></span>],
<span class="string"><span class="delimiter">'</span><span class="content">players[keyboards]</span><span class="delimiter">'</span></span>: [<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Anthony George Banks</span><span class="delimiter">'</span></span>]]
album.properties = updatedBindingMap
<span class="keyword">assert</span> album.title == <span class="string"><span class="delimiter">'</span><span class="content">The Lamb Lies Down On Broadway</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> album.players.size() == <span class="integer">4</span>
<span class="keyword">assert</span> album.players.guitar.name == <span class="string"><span class="delimiter">'</span><span class="content">Steve Hackett</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> album.players.vocals.name == <span class="string"><span class="delimiter">'</span><span class="content">Peter Gabriel</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> album.players.keyboards.name == <span class="string"><span class="delimiter">'</span><span class="content">Anthony George Banks</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> album.players.drums.name == <span class="string"><span class="delimiter">'</span><span class="content">Phil Collins</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_binding_request_data_to_the_model">Binding Request Data to the Model</h4>
<div class="paragraph">
<p>The <a href="../ref/Controllers/params.html">params</a> object that is available in a controller has special behavior that helps convert dotted request parameter names into nested Maps that the data binder can work with. For example, if a request includes request parameters named <code>person.homeAddress.country</code> and <code>person.homeAddress.city</code> with values 'USA' and 'St. Louis' respectively, <code>params</code> would include entries like these:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">[<span class="key">person</span>: [<span class="key">homeAddress</span>: [<span class="key">country</span>: <span class="string"><span class="delimiter">'</span><span class="content">USA</span><span class="delimiter">'</span></span>, <span class="key">city</span>: <span class="string"><span class="delimiter">'</span><span class="content">St. Louis</span><span class="delimiter">'</span></span>]]]</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">save</span>() {
<span class="keyword">def</span> b = <span class="keyword">new</span> <span class="predefined-type">Book</span>(params)
b.save()
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The data binding happens within the code <code>new Book(params)</code>. By passing the <a href="../ref/Controllers/params.html">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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>/book/save?title=The%20Stand&amp;author=Stephen%20King</code></pre>
</div>
</div>
<div class="paragraph">
<p>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%20Classes/properties.html">properties</a> property to perform data binding onto an existing instance:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">save</span>() {
<span class="keyword">def</span> b = <span class="predefined-type">Book</span>.get(params.id)
b.properties = params
b.save()
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This has the same effect as using the implicit constructor.</p>
</div>
<div class="paragraph">
<p>When binding an empty String (a String with no characters in it, not even spaces), the data binder will convert the empty String to null. This simplifies the most common case where the intent is to treat an empty form field as having the value null since there isn&#8217;t a way to actually submit a null as a request parameter. When this behavior is not desirable the application may assign the value directly.</p>
</div>
<div class="paragraph">
<p>The mass property binding mechanism will by default automatically trim all Strings at binding time. To disable this behavior set the <code>grails.databinding.trimStrings</code> property to false in <code>grails-app/conf/application.groovy</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// the default value is true</span>
grails.databinding.trimStrings = <span class="predefined-constant">false</span>
<span class="comment">// ...</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The mass property binding mechanism will by default automatically convert all empty Strings to null at binding time. To disable this behavior set the <code>grails.databinding.convertEmptyStringsToNull</code> property to false in <code>grails-app/conf/application.groovy</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// the default value is true</span>
grails.databinding.convertEmptyStringsToNull = <span class="predefined-constant">false</span>
<span class="comment">// ...</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The order of events is that the String trimming happens and then null conversion happens so if <code>trimStrings</code> is <code>true</code> and <code>convertEmptyStringsToNull</code> is <code>true</code>, not only will empty Strings be converted to null but also blank Strings. A blank String is any String such that the <code>trim()</code> method returns an empty String.</p>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
These forms of data binding in Grails are very convenient, but also indiscriminate. In other words, they will bind <em>all</em> non-transient, typed instance properties of the target object, including ones that you may not want bound. Just because the form in your UI doesn&#8217;t submit all the properties, an attacker can still send malign data via a raw HTTP request. Fortunately, Grails also makes it easy to protect against such attacks - see the section titled "Data Binding and Security concerns" for more information.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_data_binding_and_single_ended_associations">Data binding and Single-ended Associations</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>/book/save?author.id=20</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> b = <span class="keyword">new</span> <span class="predefined-type">Book</span>(params)</code></pre>
</div>
</div>
<div class="paragraph">
<p>An association property can be set to <code>null</code> by passing the literal <code>String</code> "null". For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>/book/save?author.id=null</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_data_binding_and_many_ended_associations">Data Binding and Many-ended Associations</h4>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>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>&lt;g:select&gt;</code> below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:select</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books</span><span class="delimiter">&quot;</span></span>
<span class="attribute-name">from</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${Book.list()}</span><span class="delimiter">&quot;</span></span>
<span class="attribute-name">size</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">5</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">multiple</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">yes</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">optionKey</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">id</span><span class="delimiter">&quot;</span></span>
<span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${author?.books}</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>However, if you have a scenario where you want to update the properties of the associated objects the this technique won&#8217;t work. Instead you use the subscript operator:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:textField</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[0].title</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">the Stand</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
<span class="tag">&lt;g:textField</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[1].title</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">the Shining</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>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&#8217;re referring to <code>books[0]</code> and <code>books[1]</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>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:textField</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[0].title</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">the Stand</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
<span class="tag">&lt;g:textField</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[1].title</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">the Shining</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
<span class="tag">&lt;g:textField</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[2].title</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">Red Madder</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Then Grails will automatically create a new instance for you at the defined position.</p>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:select</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[0].id</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">from</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${bookList}</span><span class="delimiter">&quot;</span></span>
<span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${author?.books[0]?.id}</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
<span class="tag">&lt;g:select</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[1].id</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">from</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${bookList}</span><span class="delimiter">&quot;</span></span>
<span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${author?.books[1]?.id}</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
<span class="tag">&lt;g:select</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[2].id</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">from</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${bookList}</span><span class="delimiter">&quot;</span></span>
<span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${author?.books[2]?.id}</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Would allow individual entries in the <code>books List</code> to be selected separately.</p>
</div>
<div class="paragraph">
<p>Entries at particular indexes can be removed in the same way too. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:select</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[0].id</span><span class="delimiter">&quot;</span></span>
<span class="attribute-name">from</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${Book.list()}</span><span class="delimiter">&quot;</span></span>
<span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${author?.books[0]?.id}</span><span class="delimiter">&quot;</span></span>
<span class="attribute-name">noSelection</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">['null': '']</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Will render a select box that will remove the association at <code>books[0]</code> if the empty option is chosen.</p>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:select</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">images[cover].id</span><span class="delimiter">&quot;</span></span>
<span class="attribute-name">from</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${Image.list()}</span><span class="delimiter">&quot;</span></span>
<span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${book?.images[cover]?.id}</span><span class="delimiter">&quot;</span></span>
<span class="attribute-name">noSelection</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">['null': '']</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>This would bind the selected image into the <code>Map</code> property <code>images</code> under a key of <code>"cover"</code>.</p>
</div>
<div class="paragraph">
<p>When binding to Maps, Arrays and Collections the data binder will automatically grow the size of the collections as necessary.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The default limit to how large the binder will grow a collection is 256. If the data binder encounters an entry that requires the collection be grown beyond that limit, the entry is ignored. The limit may be configured by assigning a value to the <code>grails.databinding.autoGrowCollectionLimit</code> property in <code>application.groovy</code>.
</td>
</tr>
</table>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/application.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// the default value is 256</span>
grails.databinding.autoGrowCollectionLimit = <span class="integer">128</span>
<span class="comment">// ...</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_data_binding_with_multiple_domain_classes">Data binding with Multiple domain classes</h4>
<div class="paragraph">
<p>It is possible to bind data to multiple domain objects from the <a href="../ref/Controllers/params.html">params</a> object.</p>
</div>
<div class="paragraph">
<p>For example so you have an incoming request to:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">/book/save?book.title=The%20Stand&amp;author.name=Stephen%20King</code></pre>
</div>
</div>
<div class="paragraph">
<p>You&#8217;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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> b = <span class="keyword">new</span> <span class="predefined-type">Book</span>(params.book)</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> a = <span class="keyword">new</span> Author(params.author)</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_data_binding_and_action_arguments">Data Binding and Action Arguments</h4>
<div class="paragraph">
<p>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="theWebLayer.html#commandObjects">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="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html">java.lang.String</a>. The default behavior is to map request parameters to action arguments by name:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">AccountingController</span> {
<span class="comment">// accountNumber will be initialized with the value of params.accountNumber</span>
<span class="comment">// accountType will be initialized with params.accountType</span>
<span class="keyword">def</span> <span class="function">displayInvoice</span>(<span class="predefined-type">String</span> accountNumber, <span class="type">int</span> accountType) {
<span class="comment">// ...</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">/accounting/displayInvoice?accountNumber=B59786&amp;accountType=bogusValue</code></pre>
</div>
</div>
<div class="paragraph">
<p>Since "bogusValue" cannot be converted to type int, the value of accountType will be zero, the controller&#8217;s <code>errors.hasErrors()</code> will be true, the controller&#8217;s <code>errors.errorCount</code> will be equal to 1 and the controller&#8217;s <code>errors.getFieldError('accountType')</code> will contain the corresponding error.</p>
</div>
<div class="paragraph">
<p>If the argument name does not match the name of the request parameter then the <code>@grails.web.RequestParameter</code> annotation may be applied to an argument to express the name of the request parameter which should be bound to that argument:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.web.RequestParameter</span>
<span class="type">class</span> <span class="class">AccountingController</span> {
<span class="comment">// mainAccountNumber will be initialized with the value of params.accountNumber</span>
<span class="comment">// accountType will be initialized with params.accountType</span>
<span class="keyword">def</span> <span class="function">displayInvoice</span>(<span class="annotation">@RequestParameter</span>(<span class="string"><span class="delimiter">'</span><span class="content">accountNumber</span><span class="delimiter">'</span></span>) <span class="predefined-type">String</span> mainAccountNumber, <span class="type">int</span> accountType) {
<span class="comment">// ...</span>
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_data_binding_and_type_conversion_errors">Data binding and type conversion errors</h4>
<div class="paragraph">
<p>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%20Classes/errors.html">errors</a> property of a Grails domain class. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Book</span> {
...
URL publisherURL
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">/book/save?publisherURL=a-bad-url</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> b = <span class="keyword">new</span> <span class="predefined-type">Book</span>(params)
<span class="keyword">if</span> (b.hasErrors()) {
println <span class="string"><span class="delimiter">&quot;</span><span class="content">The value </span><span class="inline"><span class="inline-delimiter">${</span>b.errors.getFieldError(<span class="string"><span class="delimiter">'</span><span class="content">publisherURL</span><span class="delimiter">'</span></span>).rejectedValue<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span> +
<span class="string"><span class="delimiter">&quot;</span><span class="content"> is not a valid URL!</span><span class="delimiter">&quot;</span></span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Although we have not yet covered error codes (for more information see the section on <a href="validation.html">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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">typeMismatch.java.net.URL=The field {<span class="integer">0</span>} is not a valid <span class="predefined-type">URL</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Or a more specific one:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">typeMismatch.Book.publisherURL=The publisher <span class="predefined-type">URL</span> you specified is not a valid <span class="predefined-type">URL</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_the_bindusing_annotation">The BindUsing Annotation</h4>
<div class="paragraph">
<p>The <a href="https://grails.apache.org/docs/3.3.7/api/grails/databinding/BindUsing.html">BindUsing</a> annotation may be used to define a custom binding mechanism for a particular field in a class. Any time data binding is being applied to the field the closure value of the annotation will be invoked with 2 arguments. The first argument is the object that data binding is being applied to and the second argument is <a href="https://grails.apache.org/docs/3.3.7/api/grails/databinding/DataBindingSource.html">DataBindingSource</a> which is the data source for the data binding. The value returned from the closure will be bound to the property. The following example would result in the upper case version of the <code>name</code> value in the source being applied to the <code>name</code> field during data binding.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.databinding.BindUsing</span>
<span class="type">class</span> <span class="class">SomeClass</span> {
<span class="annotation">@BindUsing</span>({obj, source -&gt;
<span class="comment">//source is DataSourceBinding which is similar to a Map</span>
<span class="comment">//and defines getAt operation but source.name cannot be used here.</span>
<span class="comment">//In order to get name from source use getAt instead as shown below.</span>
source[<span class="string"><span class="delimiter">'</span><span class="content">name</span><span class="delimiter">'</span></span>]?.toUpperCase()
})
<span class="predefined-type">String</span> name
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Note that data binding is only possible when the name of the request parameter matches with the field name in the class.
Here, <code>name</code> from request parameters matches with <code>name</code> from <code>SomeClass</code>.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The <a href="https://grails.apache.org/docs/3.3.7/api/grails/databinding/BindUsing.html">BindUsing</a> annotation may be used to define a custom binding mechanism for all of the fields on a particular class. When the annotation is applied to a class, the value assigned to the annotation should be a class which implements the <a href="https://grails.apache.org/docs/3.3.7/api/grails/databinding/BindingHelper.html">BindingHelper</a> interface. An instance of that class will be used any time a value is bound to a property in the class that this annotation has been applied to.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="annotation">@BindUsing</span>(SomeClassWhichImplementsBindingHelper)
<span class="type">class</span> <span class="class">SomeClass</span> {
<span class="predefined-type">String</span> someProperty
<span class="predefined-type">Integer</span> someOtherProperty
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_the_bindinitializer_annotation">The BindInitializer Annotation</h4>
<div class="paragraph">
<p>The <a href="https://grails.apache.org/docs/3.3.7/api/grails/databinding/BindInitializer.html">BindInitializer</a> annotation may be used to initialize an associated field in a class if it is undefined.
Unlike the <a href="https://grails.apache.org/docs/3.3.7/api/grails/databinding/BindUsing.html">BindUsing</a> annotation, databinding will continue binding all nested properties on this association.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.databinding.BindInitializer</span>
<span class="type">class</span> <span class="class">Account</span>{}
<span class="type">class</span> <span class="class">User</span> {
Account account
<span class="comment">// BindInitializer expects you to return a instance of the type</span>
<span class="comment">// where it's declared on. You can use source as a parameter, in this case user.</span>
<span class="annotation">@BindInitializer</span>({user-&gt; <span class="keyword">new</span> Contact(<span class="key">account</span>:user.account) })
Contact contact
}
<span class="type">class</span> <span class="class">Contact</span>{
Account account
<span class="predefined-type">String</span> firstName
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
@BindInitializer only makes sense for associated entities, as per this use case.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_custom_data_converters">Custom Data Converters</h4>
<div class="paragraph">
<p>The binder will do a lot of type conversion automatically. Some applications may want to define their own mechanism for converting values and a simple way to do this is to write a class which implements <a href="https://grails.apache.org/docs/3.3.7/api/grails/databinding/converters/ValueConverter.html">ValueConverter</a> and register an instance of that class as a bean in the Spring application context.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.myapp.converters
<span class="keyword">import</span> <span class="include">grails.databinding.converters.ValueConverter</span>
<span class="comment">/**
* A custom converter which will convert String of the
* form 'city:state' into an Address object.
*/</span>
<span class="type">class</span> <span class="class">AddressValueConverter</span> <span class="directive">implements</span> ValueConverter {
<span class="type">boolean</span> canConvert(value) {
value <span class="keyword">instanceof</span> <span class="predefined-type">String</span>
}
<span class="keyword">def</span> <span class="function">convert</span>(value) {
<span class="keyword">def</span> pieces = value.split(<span class="string"><span class="delimiter">'</span><span class="content">:</span><span class="delimiter">'</span></span>)
<span class="keyword">new</span> com.myapp.Address(<span class="key">city</span>: pieces[<span class="integer">0</span>], <span class="key">state</span>: pieces[<span class="integer">1</span>])
}
<span class="predefined-type">Class</span>&lt;?&gt; getTargetType() {
com.myapp.Address
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>An instance of that class needs to be registered as a bean in the Spring application context. The bean name is not important. All beans that implemented ValueConverter will be automatically plugged in to the data binding process.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/spring/resources.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">beans = {
addressConverter com.myapp.converters.AddressValueConverter
<span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Person</span> {
<span class="predefined-type">String</span> firstName
Address homeAddress
}
<span class="type">class</span> <span class="class">Address</span> {
<span class="predefined-type">String</span> city
<span class="predefined-type">String</span> state
}
<span class="keyword">def</span> person = <span class="keyword">new</span> Person()
person.properties = [<span class="key">firstName</span>: <span class="string"><span class="delimiter">'</span><span class="content">Jeff</span><span class="delimiter">'</span></span>, <span class="key">homeAddress</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">O'Fallon:Missouri</span><span class="delimiter">&quot;</span></span>]
<span class="keyword">assert</span> person.firstName == <span class="string"><span class="delimiter">'</span><span class="content">Jeff</span><span class="delimiter">'</span></span>
<span class="keyword">assert</span> person.homeAddress.city = <span class="string"><span class="delimiter">&quot;</span><span class="content">O'Fallon</span><span class="delimiter">&quot;</span></span>
<span class="keyword">assert</span> person.homeAddress.state = <span class="string"><span class="delimiter">'</span><span class="content">Missouri</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_date_formats_for_data_binding">Date Formats For Data Binding</h4>
<div class="paragraph">
<p>A custom date format may be specified to be used when binding a String to a Date value by applying the <a href="https://grails.apache.org/docs/3.3.7/api/grails/databinding/BindingFormat.html">BindingFormat</a> annotation to a Date field.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.databinding.BindingFormat</span>
<span class="type">class</span> <span class="class">Person</span> {
<span class="annotation">@BindingFormat</span>(<span class="string"><span class="delimiter">'</span><span class="content">MMddyyyy</span><span class="delimiter">'</span></span>)
<span class="predefined-type">Date</span> birthDate
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>A global setting may be configured in <code>application.groovy</code> to define date formats which will be used application wide when binding to Date.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/application.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails.databinding.dateFormats = [<span class="string"><span class="delimiter">'</span><span class="content">MMddyyyy</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">yyyy-MM-dd HH:mm:ss.S</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">&quot;</span><span class="content">yyyy-MM-dd'T'hh:mm:ss'Z'</span><span class="delimiter">&quot;</span></span>]</code></pre>
</div>
</div>
<div class="paragraph">
<p>The formats specified in <code>grails.databinding.dateFormats</code> will be attempted in the order in which they are included in the List. If a property is marked with <code>@BindingFormat</code>, the <code>@BindingFormat</code> will take precedence over the values specified in <code>grails.databinding.dateFormats</code>.</p>
</div>
<div class="paragraph">
<p>The formats configured by default are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>yyyy-MM-dd HH:mm:ss.S</code></p>
</li>
<li>
<p><code>yyyy-MM-dd&#8217;T&#8217;hh:mm:ss&#8217;Z'</code></p>
</li>
<li>
<p><code>yyyy-MM-dd HH:mm:ss.S z</code></p>
</li>
<li>
<p><code>yyyy-MM-dd&#8217;T&#8217;HH:mm:ss.SSSX</code></p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_custom_formatted_converters">Custom Formatted Converters</h4>
<div class="paragraph">
<p>You may supply your own handler for the <a href="https://grails.apache.org/docs/3.3.7/api/grails/databinding/BindingFormat.html">BindingFormat</a> annotation by writing a class which implements the <a href="https://grails.apache.org/docs/3.3.7/api/grails/databinding/converters/FormattedValueConverter.html">FormattedValueConverter</a> interface and registering an instance of that class as a bean in the Spring application context. Below is an example of a trivial custom String formatter that might convert the case of a String based on the value assigned to the BindingFormat annotation.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.myapp.converters
<span class="keyword">import</span> <span class="include">grails.databinding.converters.FormattedValueConverter</span>
<span class="type">class</span> <span class="class">FormattedStringValueConverter</span> <span class="directive">implements</span> FormattedValueConverter {
<span class="keyword">def</span> <span class="function">convert</span>(value, <span class="predefined-type">String</span> format) {
<span class="keyword">if</span>(<span class="string"><span class="delimiter">'</span><span class="content">UPPERCASE</span><span class="delimiter">'</span></span> == format) {
value = value.toUpperCase()
} <span class="keyword">else</span> <span class="keyword">if</span>(<span class="string"><span class="delimiter">'</span><span class="content">LOWERCASE</span><span class="delimiter">'</span></span> == format) {
value = value.toLowerCase()
}
value
}
<span class="predefined-type">Class</span> getTargetType() {
<span class="comment">// specifies the type to which this converter may be applied</span>
<span class="predefined-type">String</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>An instance of that class needs to be registered as a bean in the Spring application context. The bean name is not important. All beans that implemented FormattedValueConverter will be automatically plugged in to the data binding process.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/spring/resources.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">beans = {
formattedStringConverter com.myapp.converters.FormattedStringValueConverter
<span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>With that in place the <code>BindingFormat</code> annotation may be applied to String fields to inform the data binder to take advantage of the custom converter.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.databinding.BindingFormat</span>
<span class="type">class</span> <span class="class">Person</span> {
<span class="annotation">@BindingFormat</span>(<span class="string"><span class="delimiter">'</span><span class="content">UPPERCASE</span><span class="delimiter">'</span></span>)
<span class="predefined-type">String</span> someUpperCaseString
<span class="annotation">@BindingFormat</span>(<span class="string"><span class="delimiter">'</span><span class="content">LOWERCASE</span><span class="delimiter">'</span></span>)
<span class="predefined-type">String</span> someLowerCaseString
<span class="predefined-type">String</span> someOtherString
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_localized_binding_formats">Localized Binding Formats</h4>
<div class="paragraph">
<p>The <code>BindingFormat</code> annotation supports localized format strings by using the optional <code>code</code> attribute. If a value is assigned to the code attribute that value will be used as the message code to retrieve the binding format string from the <code>messageSource</code> bean in the Spring application context and that lookup will be localized.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.databinding.BindingFormat</span>
<span class="type">class</span> <span class="class">Person</span> {
<span class="annotation">@BindingFormat</span>(code=<span class="string"><span class="delimiter">'</span><span class="content">date.formats.birthdays</span><span class="delimiter">'</span></span>)
<span class="predefined-type">Date</span> birthDate
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">#</span> grails-app/conf/i18n/messages.properties
date.formats.birthdays=MMddyyyy</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">#</span> grails-app/conf/i18n/messages_es.properties
date.formats.birthdays=ddMMyyyy</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_structured_data_binding_editors">Structured Data Binding Editors</h4>
<div class="paragraph">
<p>A structured data binding editor is a helper class which can bind structured request parameters to a property. The common use case for structured binding is binding to a <code>Date</code> object which might be constructed from several smaller pieces of information contained in several request parameters with names like <code>birthday_month</code>, <code>birthday_date</code> and <code>birthday_year</code>. The structured editor would retrieve all of those individual pieces of information and use them to construct a <code>Date</code>.</p>
</div>
<div class="paragraph">
<p>The framework provides a structured editor for binding to <code>Date</code> objects. An application may register its own structured editors for whatever types are appropriate. Consider the following classes:</p>
</div>
<div class="listingblock">
<div class="title">src/main/groovy/databinding/Gadget.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> databinding
<span class="type">class</span> <span class="class">Gadget</span> {
<span class="predefined-type">Shape</span> expandedShape
<span class="predefined-type">Shape</span> compressedShape
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">src/main/groovy/databinding/Shape.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> databinding
<span class="type">class</span> <span class="class">Shape</span> {
<span class="type">int</span> area
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>A <code>Gadget</code> has 2 <code>Shape</code> fields. A <code>Shape</code> has an <code>area</code> property. It may be that the application wants to accept request parameters like <code>width</code> and <code>height</code> and use those to calculate the <code>area</code> of a <code>Shape</code> at binding time. A structured binding editor is well suited for that.</p>
</div>
<div class="paragraph">
<p>The way to register a structured editor with the data binding process is to add an instance of the <a href="https://grails.apache.org/docs/3.3.7/api/grails/databinding/TypedStructuredBindingEditor.html">grails.databinding.TypedStructuredBindingEditor</a> interface to the Spring application context. The easiest way to implement the <code>TypedStructuredBindingEditor</code> interface is to extend the <a href="https://grails.apache.org/docs/3.3.7/api/org/grails/databinding/converters/AbstractStructuredDateBindingEditor.html">org.grails.databinding.converters.AbstractStructuredBindingEditor</a> abstract class and override the <code>getPropertyValue</code> method as shown below:</p>
</div>
<div class="listingblock">
<div class="title">src/main/groovy/databinding/converters/StructuredShapeEditor.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> databinding.converters
<span class="keyword">import</span> <span class="include">databinding.Shape</span>
<span class="keyword">import</span> <span class="include">org.grails.databinding.converters.AbstractStructuredBindingEditor</span>
<span class="type">class</span> <span class="class">StructuredShapeEditor</span> <span class="directive">extends</span> AbstractStructuredBindingEditor&lt;<span class="predefined-type">Shape</span>&gt; {
<span class="directive">public</span> <span class="predefined-type">Shape</span> getPropertyValue(<span class="predefined-type">Map</span> values) {
<span class="comment">// retrieve the individual values from the Map</span>
<span class="keyword">def</span> width = values.width <span class="keyword">as</span> <span class="type">int</span>
<span class="keyword">def</span> height = values.height <span class="keyword">as</span> <span class="type">int</span>
<span class="comment">// use the values to calculate the area of the Shape</span>
<span class="keyword">def</span> area = width * height
<span class="comment">// create and return a Shape with the appropriate area</span>
<span class="keyword">new</span> <span class="predefined-type">Shape</span>(<span class="key">area</span>: area)
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>An instance of that class needs to be registered with the Spring application context:</p>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/spring/resources.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">beans = {
shapeEditor databinding.converters.StructuredShapeEditor
<span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>When the data binder binds to an instance of the <code>Gadget</code> class it will check to see if there are request parameters with names <code>compressedShape</code> and <code>expandedShape</code> which have a value of "struct" and if they do exist, that will trigger the use of the <code>StructuredShapeEditor</code>. The individual components of the structure need to have parameter names of the form propertyName_structuredElementName. In the case of the <code>Gadget</code> class above that would mean that the <code>compressedShape</code> request parameter should have a value of "struct" and the <code>compressedShape_width</code> and <code>compressedShape_height</code> parameters should have values which represent the width and the height of the compressed <code>Shape</code>. Similarly, the <code>expandedShape</code> request parameter should have a value of "struct" and the <code>expandedShape_width</code> and <code>expandedShape_height</code> parameters should have values which represent the width and the height of the expanded <code>Shape</code>.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/demo/DemoController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">DemoController</span> {
<span class="keyword">def</span> <span class="function">createGadget</span>(Gadget gadget) {
<span class="comment">/*
/demo/createGadget?expandedShape=struct&amp;expandedShape_width=80&amp;expandedShape_height=30
&amp;compressedShape=struct&amp;compressedShape_width=10&amp;compressedShape_height=3
*/</span>
<span class="comment">// with the request parameters shown above gadget.expandedShape.area would be 2400</span>
<span class="comment">// and gadget.compressedShape.area would be 30</span>
<span class="comment">// ...</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Typically the request parameters with "struct" as their value would be represented by hidden form fields.</p>
</div>
</div>
<div class="sect3">
<h4 id="_data_binding_event_listeners">Data Binding Event Listeners</h4>
<div class="paragraph">
<p>The <a href="https://grails.apache.org/docs/3.3.7/api/grails/databinding/events/DataBindingListener.html">DataBindingListener</a> interface provides a mechanism for listeners to be notified of data binding events. The interface looks like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> grails.databinding.events;
<span class="keyword">import</span> <span class="include">grails.databinding.errors.BindingError</span>;
<span class="comment">/**
* A listener which will be notified of events generated during data binding.
*
* @author Jeff Brown
* @since 3.0
* @see DataBindingListenerAdapter
*/</span>
<span class="directive">public</span> <span class="type">interface</span> DataBindingListener {
<span class="comment">/**
* @return true if the listener is interested in events for the specified type.
*/</span>
<span class="type">boolean</span> supports(<span class="predefined-type">Class</span>&lt;?&gt; clazz);
<span class="comment">/**
* Called when data binding is about to start.
*
* @param target The object data binding is being imposed upon
* @param errors the Spring Errors instance (a org.springframework.validation.BindingResult)
* @return true if data binding should continue
*/</span>
<span class="predefined-type">Boolean</span> beforeBinding(<span class="predefined-type">Object</span> target, <span class="predefined-type">Object</span> errors);
<span class="comment">/**
* Called when data binding is about to imposed on a property
*
* @param target The object data binding is being imposed upon
* @param propertyName The name of the property being bound to
* @param value The value of the property being bound
* @param errors the Spring Errors instance (a org.springframework.validation.BindingResult)
* @return true if data binding should continue, otherwise return false
*/</span>
<span class="predefined-type">Boolean</span> beforeBinding(<span class="predefined-type">Object</span> target, <span class="predefined-type">String</span> propertyName, <span class="predefined-type">Object</span> value, <span class="predefined-type">Object</span> errors);
<span class="comment">/**
* Called after data binding has been imposed on a property
*
* @param target The object data binding is being imposed upon
* @param propertyName The name of the property that was bound to
* @param errors the Spring Errors instance (a org.springframework.validation.BindingResult)
*/</span>
<span class="type">void</span> afterBinding(<span class="predefined-type">Object</span> target, <span class="predefined-type">String</span> propertyName, <span class="predefined-type">Object</span> errors);
<span class="comment">/**
* Called after data binding has finished.
*
* @param target The object data binding is being imposed upon
* @param errors the Spring Errors instance (a org.springframework.validation.BindingResult)
*/</span>
<span class="type">void</span> afterBinding(<span class="predefined-type">Object</span> target, <span class="predefined-type">Object</span> errors);
<span class="comment">/**
* Called when an error occurs binding to a property
* @param error encapsulates information about the binding error
* @param errors the Spring Errors instance (a org.springframework.validation.BindingResult)
* @see BindingError
*/</span>
<span class="type">void</span> bindingError(BindingError error, <span class="predefined-type">Object</span> errors);
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Any bean in the Spring application context which implements that interface will automatically be registered with the data binder. The <a href="https://grails.apache.org/docs/3.3.7/api/grails/databinding/events/DataBindingListenerAdapter.html">DataBindingListenerAdapter</a> class implements the <code>DataBindingListener</code> interface and provides default implementations for all of the methods in the interface so this class is well suited for subclassing so your listener class only needs to provide implementations for the methods your listener is interested in.</p>
</div>
</div>
<div class="sect3">
<h4 id="_using_the_data_binder_directly">Using The Data Binder Directly</h4>
<div class="paragraph">
<p>There are situations where an application may want to use the data binder directly. For example, to do binding in a Service on some arbitrary object which is not a domain class. The following will not work because the <code>properties</code> property is read only.</p>
</div>
<div class="listingblock">
<div class="title">src/main/groovy/bindingdemo/Widget.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> bindingdemo
<span class="type">class</span> <span class="class">Widget</span> {
<span class="predefined-type">String</span> name
<span class="predefined-type">Integer</span> size
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">grails-app/services/bindingdemo/WidgetService.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> bindingdemo
<span class="type">class</span> <span class="class">WidgetService</span> {
<span class="keyword">def</span> <span class="function">updateWidget</span>(Widget widget, <span class="predefined-type">Map</span> data) {
<span class="comment">// this will throw an exception because</span>
<span class="comment">// properties is read-only</span>
widget.properties = data
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>An instance of the data binder is in the Spring application context with a bean name of <code>grailsWebDataBinder</code>. That bean implements the <a href="https://grails.apache.org/docs/3.3.7/api/grails/databinding/DataBinder.html">DataBinder</a> interface. The following code demonstrates using the data binder directly.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/services/bindingdmeo/WidgetService</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> bindingdemo
<span class="keyword">import</span> <span class="include">grails.databinding.SimpleMapDataBindingSource</span>
<span class="type">class</span> <span class="class">WidgetService</span> {
<span class="comment">// this bean will be autowired into the service</span>
<span class="keyword">def</span> grailsWebDataBinder
<span class="keyword">def</span> <span class="function">updateWidget</span>(Widget widget, <span class="predefined-type">Map</span> data) {
grailsWebDataBinder.bind widget, data <span class="keyword">as</span> SimpleMapDataBindingSource
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>See the <a href="https://grails.apache.org/docs/3.3.7/api/grails/databinding/DataBinder.html">DataBinder</a> documentation for more information about overloaded versions
of the <code>bind</code> method.</p>
</div>
</div>
<div class="sect3">
<h4 id="_data_binding_and_security_concerns">Data Binding and Security Concerns</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> p = Person.get(<span class="integer">1</span>)
p.properties[<span class="string"><span class="delimiter">'</span><span class="content">firstName</span><span class="delimiter">'</span></span>,<span class="string"><span class="delimiter">'</span><span class="content">lastName</span><span class="delimiter">'</span></span>] = params</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this case only the <code>firstName</code> and <code>lastName</code> properties will be bound.</p>
</div>
<div class="paragraph">
<p>Another way to do this is is to use <a href="theWebLayer.html#commandObjects">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">bindData</a> method.</p>
</div>
<div class="paragraph">
<p>The <code>bindData</code> method allows the same data binding capability, but to arbitrary objects:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> p = <span class="keyword">new</span> Person()
bindData(p, params)</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>bindData</code> method also lets you exclude certain parameters that you don&#8217;t want updated:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> p = <span class="keyword">new</span> Person()
bindData(p, params, [<span class="key">exclude</span>: <span class="string"><span class="delimiter">'</span><span class="content">dateOfBirth</span><span class="delimiter">'</span></span>])</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or include only certain properties:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> p = <span class="keyword">new</span> Person()
bindData(p, params, [<span class="key">include</span>: [<span class="string"><span class="delimiter">'</span><span class="content">firstName</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">lastName</span><span class="delimiter">'</span></span>]])</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
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.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The <a href="../ref/Constraints/bindable.html">bindable</a> constraint can be used to globally prevent data binding for certain properties.</p>
</div>
</div>
<h2 id="jsonResponses">8.1.6 Responding with JSON</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/controllers/jsonResponses.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_using_the_respond_method_to_output_json">Using the respond method to output JSON</h4>
<div class="paragraph">
<p>The <code>respond</code> method is the preferred way to return JSON and integrates with <a href="theWebLayer.html#contentNegotiation">Content Negotiation</a> and <a href="http://views.grails.org">JSON Views</a>.</p>
</div>
<div class="paragraph">
<p>The <code>respond</code> method provides content negotiation strategies to intelligently produce an appropriate response for the given client.</p>
</div>
<div class="paragraph">
<p>For example given the following controller and action:</p>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/example/BookController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> example
<span class="type">class</span> <span class="class">BookController</span> {
<span class="keyword">def</span> <span class="function">index</span>() {
respond <span class="predefined-type">Book</span>.list()
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>respond</code> method will take the followings steps:</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>If the client <code>Accept</code> header specifies a media type (for example <code>application/json</code>) use that</p>
</li>
<li>
<p>If the file extension of the URI (for example <code>/books.json</code>) includes a format defined in the <code>grails.mime.types</code> property of <code>grails-app/conf/application.yml</code> use the media type defined in the configuration</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>The <code>respond</code> method will then look for an appriopriate <a href="https://grails.apache.org/docs/3.3.7/api/grails/rest/render/Renderer.html">Renderer</a> for the object and the calculated media type from the <a href="https://grails.apache.org/docs/3.3.7/api/grails/rest/render/RendererRegistry.html">RendererRegistry</a>.</p>
</div>
<div class="paragraph">
<p>Grails includes a number of pre-configured <code>Renderer</code> implementations that will produce default representations of JSON responses for the argument passed to <code>respond</code>. For example going to the <code>/book.json</code> URI will produce JSON such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="json">[
{<span class="error">i</span><span class="error">d</span>:<span class="integer">1</span>,<span class="key"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">The Stand</span><span class="delimiter">&quot;</span></span>},
{<span class="error">i</span><span class="error">d</span>:<span class="integer">2</span>,<span class="key"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">Shining</span><span class="delimiter">&quot;</span></span>}
]</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_controlling_the_priority_of_media_types">Controlling the Priority of Media Types</h4>
<div class="paragraph">
<p>By default if you define a controller there is no priority in terms of which format is sent back to the client and Grails assumes you wish to serve HTML as a response type.</p>
</div>
<div class="paragraph">
<p>However if your application is primarily an API, then you can specify the priorty using the <code>responseFormats</code> property:</p>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/example/BookController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> example
<span class="type">class</span> <span class="class">BookController</span> {
<span class="directive">static</span> responseFormats = [<span class="string"><span class="delimiter">'</span><span class="content">json</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">html</span><span class="delimiter">'</span></span>]
<span class="keyword">def</span> <span class="function">index</span>() {
respond <span class="predefined-type">Book</span>.list()
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the above example Grails will respond by default with <code>json</code> if the media type to respond with cannot be calculated from the <code>Accept</code> header or file extension.</p>
</div>
</div>
<div class="sect3">
<h4 id="_using_views_to_output_json_responses">Using Views to Output JSON Responses</h4>
<div class="paragraph">
<p>If you define a view (either a GSP or a <a href="http://views.grails.org">JSON View</a>) then Grails will render the view when using the <code>respond</code> method by calculating a model from the argument passed to <code>respond</code>.</p>
</div>
<div class="paragraph">
<p>For example, in the previous listing, if you were to define <code>grails-app/views/index.gson</code> and <code>grails-app/views/index.gsp</code> views, these would be used if the client requested <code>application/json</code> or <code>text/html</code> media types respectively. Thus allowing you to define a single backend capible of serving responses to a web browser or representing your application&#8217;s API.</p>
</div>
<div class="paragraph">
<p>When rendering the view, Grails will calculate a model to pass to the view based on the type of the value passed to the <code>respond</code> method.</p>
</div>
<div class="paragraph">
<p>The following table summarizes this convention:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">Example</th>
<th class="tableblock halign-left valign-top">Argument Type</th>
<th class="tableblock halign-left valign-top">Calculated Model Variable</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>respond Book.list()</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>java.util.List</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>bookList</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>respond( [] )</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>java.util.List</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>emptyList</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>respond Book.get(1)</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>example.Book</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>book</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>respond( [1,2] )</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>java.util.List</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>integerList</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>respond( [1,2] as Set )</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>java.util.Set</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>integerSet</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>respond( [1,2] as Integer[] )</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>Integer[]</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>integerArray</code></p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>Using this convention you can reference the argument passed to <code>respond</code> from within your view:</p>
</div>
<div class="listingblock">
<div class="title">grails-app/views/book/index.gson</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="annotation">@Field</span> <span class="predefined-type">List</span>&lt;<span class="predefined-type">Book</span>&gt; bookList = <span class="type">[]</span>
json bookList, { <span class="predefined-type">Book</span> book -&gt;
title book.title
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You will notice that if <code>Book.list()</code> returns an empty list then the model variable name is translated to <code>emptyList</code>. This is by design and you should provide a default value in the view if no model variable is specified, such as the <code>List</code> in the example above:</p>
</div>
<div class="listingblock">
<div class="title">grails-app/views/book/index.gson</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// defaults to an empty list</span>
<span class="annotation">@Field</span> <span class="predefined-type">List</span>&lt;<span class="predefined-type">Book</span>&gt; bookList = <span class="type">[]</span>
...</code></pre>
</div>
</div>
<div class="paragraph">
<p>There are cases where you may wish to be more explicit and control the name of the model variable. For example if you have a domain inheritance hierarchy where a call to <code>list()</code> my return different child classes relying on automatic calculation may not be reliable.</p>
</div>
<div class="paragraph">
<p>In this case you should pass the model directly using <code>respond</code> and a map argument:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">respond <span class="key">bookList</span>: <span class="predefined-type">Book</span>.list()</code></pre>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
When responding with any kind of mixed argument types in a collection, always use an explicit model name.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>If you simply wish to augment the calculated model then you can do so by passing a <code>model</code> argument:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">respond <span class="predefined-type">Book</span>.list(), [<span class="key">model</span>: [<span class="key">bookCount</span>: <span class="predefined-type">Book</span>.count()]]</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above example will produce a model like <code>[bookList:books, bookCount:totalBooks]</code>, where the calculated model is combined with the model passed in the <code>model</code> argument.</p>
</div>
</div>
<div class="sect3">
<h4 id="_using_the_render_method_to_output_json">Using the render method to output JSON</h4>
<div class="paragraph">
<p>The <code>render</code> method can also be used to output JSON, but should only be used for simple cases that don&#8217;t warrant the creation of a JSON view:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">list</span>() {
<span class="keyword">def</span> results = <span class="predefined-type">Book</span>.list()
render(<span class="key">contentType</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">application/json</span><span class="delimiter">&quot;</span></span>) {
books(results) { <span class="predefined-type">Book</span> b -&gt;
title b.title
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this case the result would be something along the lines of:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="json">[
{<span class="key"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">The Stand</span><span class="delimiter">&quot;</span></span>},
{<span class="key"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">Shining</span><span class="delimiter">&quot;</span></span>}
]</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
This technique for rendering JSON may be ok for very simple responses, but in general you should favour the use of <a href="webServices.html#jsonViews">JSON Views</a> and use the view layer rather than embedding logic in your application.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The same dangers with naming conflicts described above for XML also apply to JSON building.</p>
</div>
</div>
<a name="7.1.8 More on JSONBuilder"><!-- Legacy link --></a>
<h2 id="moreOnJSONBuilder">8.1.7 More on JSONBuilder</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/controllers/moreOnJSONBuilder.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>The previous section 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-lang.org/processing-xml.html#_xmlparser_and_xmlslurper">XmlSlurper</a> found in Groovy.</p>
</div>
<div class="paragraph">
<p>For JSON, since Grails 3.1, Grails uses Groovy&#8217;s <a href="http://docs.groovy-lang.org/latest/html/documentation/core-domain-specific-languages.html#_streamingjsonbuilder">StreamingJsonBuilder</a> by default and you can refer to the <a href="http://docs.groovy-lang.org/latest/html/documentation/core-domain-specific-languages.html#_streamingjsonbuilder">Groovy documentation</a> and <a href="http://docs.groovy-lang.org/latest/html/gapi/groovy/json/StreamingJsonBuilder.html">StreamingJsonBuilder</a> API documentation on how to use it.</p>
</div>
<h2 id="xmlResponses">8.1.8 Responding with XML</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/controllers/xmlResponses.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<a name="7.1.9 Uploading Files"><!-- Legacy link --></a>
<h2 id="uploadingFiles">8.1.9 Uploading Files</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/controllers/uploadingFiles.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_programmatic_file_uploads">Programmatic File Uploads</h4>
<div class="paragraph">
<p>Grails supports file uploads using Spring&#8217;s <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/multipart/MultipartHttpServletRequest.html">MultipartHttpServletRequest</a> interface. The first step for file uploading is to create a multipart form like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml">Upload Form: <span class="tag">&lt;br</span> <span class="tag">/&gt;</span>
<span class="tag">&lt;g:uploadForm</span> <span class="attribute-name">action</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">upload</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
<span class="tag">&lt;input</span> <span class="attribute-name">type</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">file</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">myFile</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
<span class="tag">&lt;input</span> <span class="attribute-name">type</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">submit</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
<span class="tag">&lt;/g:uploadForm&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>uploadForm</code> tag conveniently adds the <code>enctype="multipart/form-data"</code> attribute to the standard <code>&lt;g:form&gt;</code> tag.</p>
</div>
<div class="paragraph">
<p>There are then a number of ways to handle the file upload. One is to work with the Spring <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/multipart/MultipartFile.html">MultipartFile</a> instance directly:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">upload</span>() {
<span class="keyword">def</span> f = request.getFile(<span class="string"><span class="delimiter">'</span><span class="content">myFile</span><span class="delimiter">'</span></span>)
<span class="keyword">if</span> (f.empty) {
flash.message = <span class="string"><span class="delimiter">'</span><span class="content">file cannot be empty</span><span class="delimiter">'</span></span>
render(<span class="key">view</span>: <span class="string"><span class="delimiter">'</span><span class="content">uploadForm</span><span class="delimiter">'</span></span>)
<span class="keyword">return</span>
}
f.transferTo(<span class="keyword">new</span> <span class="predefined-type">File</span>(<span class="string"><span class="delimiter">'</span><span class="content">/some/local/dir/myfile.txt</span><span class="delimiter">'</span></span>))
response.sendError(<span class="integer">200</span>, <span class="string"><span class="delimiter">'</span><span class="content">Done</span><span class="delimiter">'</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/multipart/MultipartFile.html">MultipartFile</a> interface.</p>
</div>
</div>
<div class="sect3">
<h4 id="_file_uploads_through_data_binding">File Uploads through Data Binding</h4>
<div class="paragraph">
<p>File uploads can also be performed using data binding. Consider this <code>Image</code> domain class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Image</span> {
<span class="type">byte</span><span class="type">[]</span> myFile
<span class="directive">static</span> constraints = {
<span class="comment">// Limit upload file size to 2MB</span>
myFile <span class="key">maxSize</span>: <span class="integer">1024</span> * <span class="integer">1024</span> * <span class="integer">2</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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&#8217;s contents as a <code>byte[]</code> to the <code>myFile</code> property:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> img = <span class="keyword">new</span> <span class="predefined-type">Image</span>(params)</code></pre>
</div>
</div>
<div class="paragraph">
<p>It&#8217;s important that you set the <a href="../ref/Constraints/size.html">size</a> or <a href="../ref/Constraints/maxSize.html">maxSize</a> constraints, otherwise your database may be created with a small column size that can&#8217;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>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Image</span> {
<span class="predefined-type">String</span> myFile
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_increase_upload_max_file_size">Increase Upload Max File Size</h4>
<div class="paragraph">
<p>Grails default size for file uploads is 128000 (~128KB). When this limit is exceeded you&#8217;ll see the following exception:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="java">org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase<span class="error">$</span><span class="exception">SizeLimitExceededException</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>You can configure the limit in your <code>application.yml</code> as follows:</p>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/application.yml</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yml"><span class="key">grails</span>:
<span class="key">controllers</span>:
<span class="key">upload</span>:
<span class="key">maxFileSize</span>: <span class="string"><span class="content">2000000</span></span>
<span class="key">maxRequestSize</span>: <span class="string"><span class="content">2000000</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p><code>maxFileSize</code> = The maximum size allowed for uploaded files.</p>
</div>
<div class="paragraph">
<p><code>maxRequestSize</code> = The maximum size allowed for multipart/form-data requests.</p>
</div>
<div class="paragraph">
<p>You should keep in mind <a href="https://www.owasp.org/index.php/Unrestricted_File_Upload">OWASP recommendations - Unrestricted File Upload</a></p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Limit the file size to a maximum value in order to prevent denial of service attacks.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>These limits exist to prevent DoS attacks and to enforce overall application performance</p>
</div>
</div>
<a name="7.1.10 Command Objects"><!-- Legacy link --></a>
<h2 id="commandObjects">8.1.10 Command Objects</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/controllers/commandObjects.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails controllers support the concept of command objects. A command object is a class that is used in conjunction with <a href="theWebLayer.html#dataBinding">data binding</a>, usually to allow validation of data that may not fit into an existing domain class.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
A class is only considered to be a command object when it is used as a parameter of an action.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_declaring_command_objects">Declaring Command Objects</h4>
<div class="paragraph">
<p>Command object classes are defined just like any other class.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">LoginCommand</span> <span class="directive">implements</span> grails.validation.Validateable {
<span class="predefined-type">String</span> username
<span class="predefined-type">String</span> password
<span class="directive">static</span> constraints = {
username(<span class="key">blank</span>: <span class="predefined-constant">false</span>, <span class="key">minSize</span>: <span class="integer">6</span>)
password(<span class="key">blank</span>: <span class="predefined-constant">false</span>, <span class="key">minSize</span>: <span class="integer">6</span>)
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this example, the command object class implements the <code>Validateable</code> trait. The <code>Validateable</code> trait allows the definition of <a href="validation.html#constraints">Constraints</a> just like in <a href="GORM.html">domain classes</a>. If the command object is defined in the same source file as the controller that is using it, Grails will automatically make it <code>Validateable</code>. It is not required that command object classes be validateable.</p>
</div>
<div class="paragraph">
<p>By default, all <code>Validateable</code> object properties which are not instances of <code>java.util.Collection</code> or <code>java.util.Map</code> are <code>nullable: false</code>. Instances of <code>java.util.Collection</code> and <code>java.util.Map</code> default to <code>nullable: true</code>. If you want a <code>Validateable</code> that has <code>nullable: true</code> properties by default, you can specify this by defining a <code>defaultNullable</code> method in the class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">AuthorSearchCommand</span> <span class="directive">implements</span> grails.validation.Validateable {
<span class="predefined-type">String</span> name
<span class="predefined-type">Integer</span> age
<span class="directive">static</span> <span class="type">boolean</span> defaultNullable() {
<span class="predefined-constant">true</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this example, both <code>name</code> and <code>age</code> will allow null values during validation.</p>
</div>
</div>
<div class="sect3">
<h4 id="_using_command_objects">Using Command Objects</h4>
<div class="paragraph">
<p>To use command objects, controller actions may optionally specify any number of command object parameters. The parameter types must be supplied so that Grails knows what objects to create and initialize.</p>
</div>
<div class="paragraph">
<p>Before the controller action is executed Grails will automatically create an instance of the command object class and populate its properties by binding the request parameters. If the command object class is marked with <code>Validateable</code> then the command object will be validated. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">LoginController</span> {
<span class="keyword">def</span> <span class="function">login</span>(LoginCommand cmd) {
<span class="keyword">if</span> (cmd.hasErrors()) {
redirect(<span class="key">action</span>: <span class="string"><span class="delimiter">'</span><span class="content">loginForm</span><span class="delimiter">'</span></span>)
<span class="keyword">return</span>
}
<span class="comment">// work with the command object data</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If the command object&#8217;s type is that of a domain class and there is an <code>id</code> request parameter then instead of invoking the domain class constructor to create a new instance a call will be made to the static <code>get</code> method on the domain class and the value of the <code>id</code> parameter will be passed as an argument.</p>
</div>
<div class="paragraph">
<p>Whatever is returned from that call to <code>get</code> is what will be passed into the controller action. This means that if there is an <code>id</code> request parameter and no corresponding record is found in the database then the value of the command object will be <code>null</code>. If an error occurs retrieving the instance from the database then <code>null</code> will be passed as an argument to the controller action and an error will be added the controller&#8217;s <code>errors</code> property.</p>
</div>
<div class="paragraph">
<p>If the command object&#8217;s type is a domain class and there is no <code>id</code> request parameter or there is an <code>id</code> request parameter and its value is empty then <code>null</code> will be passed into the controller action unless the HTTP request method is "POST", in which case a new instance of the domain class will be created by invoking the domain class constructor. For all of the cases where the domain class instance is non-null, data binding is only performed if the HTTP request method is "POST", "PUT" or "PATCH".</p>
</div>
</div>
<div class="sect3">
<h4 id="_command_objects_and_request_parameter_names">Command Objects And Request Parameter Names</h4>
<div class="paragraph">
<p>Normally request parameter names will be mapped directly to property names in the command object. Nested parameter names may be used to bind down the object graph in an intuitive way.</p>
</div>
<div class="paragraph">
<p>In the example below a request parameter named <code>name</code> will be bound to the <code>name</code> property of the <code>Person</code> instance and a request parameter named <code>address.city</code> will be bound to the <code>city</code> property of the <code>address</code> property in the <code>Person</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">StoreController</span> {
<span class="keyword">def</span> <span class="function">buy</span>(Person buyer) {
<span class="comment">// ...</span>
}
}
<span class="type">class</span> <span class="class">Person</span> {
<span class="predefined-type">String</span> name
Address address
}
<span class="type">class</span> <span class="class">Address</span> {
<span class="predefined-type">String</span> city
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>A problem may arise if a controller action accepts multiple command objects which happen to contain the same property name. Consider the following example.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">StoreController</span> {
<span class="keyword">def</span> <span class="function">buy</span>(Person buyer, Product product) {
<span class="comment">// ...</span>
}
}
<span class="type">class</span> <span class="class">Person</span> {
<span class="predefined-type">String</span> name
Address address
}
<span class="type">class</span> <span class="class">Address</span> {
<span class="predefined-type">String</span> city
}
<span class="type">class</span> <span class="class">Product</span> {
<span class="predefined-type">String</span> name
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If there is a request parameter named <code>name</code> it isn&#8217;t clear if that should represent the name of the <code>Product</code> or the name of the <code>Person</code>. Another version of the problem can come up if a controller action accepts 2 command objects of the same type as shown below.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">StoreController</span> {
<span class="keyword">def</span> <span class="function">buy</span>(Person buyer, Person seller, Product product) {
<span class="comment">// ...</span>
}
}
<span class="type">class</span> <span class="class">Person</span> {
<span class="predefined-type">String</span> name
Address address
}
<span class="type">class</span> <span class="class">Address</span> {
<span class="predefined-type">String</span> city
}
<span class="type">class</span> <span class="class">Product</span> {
<span class="predefined-type">String</span> name
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>To help deal with this the framework imposes special rules for mapping parameter names to command object types. The command object data binding will treat all parameters that begin with the controller action parameter name as belonging to the corresponding command object.</p>
</div>
<div class="paragraph">
<p>For example, the <code>product.name</code> request parameter will be bound to the <code>name</code> property in the <code>product</code> argument, the <code>buyer.name</code> request parameter will be bound to the <code>name</code> property in the <code>buyer</code> argument the <code>seller.address.city</code> request parameter will be bound to the <code>city</code> property of the <code>address</code> property of the <code>seller</code> argument, etc&#8230;&#8203;</p>
</div>
</div>
<div class="sect3">
<h4 id="_command_objects_and_dependency_injection">Command Objects and Dependency Injection</h4>
<div class="paragraph">
<p>Command objects can participate in dependency injection. This is useful if your command object has some custom validation logic which uses a Grails <a href="services.html">service</a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">LoginCommand</span> <span class="directive">implements</span> grails.validation.Validateable {
<span class="keyword">def</span> loginService
<span class="predefined-type">String</span> username
<span class="predefined-type">String</span> password
<span class="directive">static</span> constraints = {
username <span class="key">validator</span>: { val, obj -&gt;
obj.loginService.canLogin(obj.username, obj.password)
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this example the command object interacts with the <code>loginService</code> bean which is injected by name from the Spring <code>ApplicationContext</code>.</p>
</div>
</div>
<div class="sect3">
<h4 id="_binding_the_request_body_to_command_objects">Binding The Request Body To Command Objects</h4>
<div class="paragraph">
<p>When a request is made to a controller action which accepts a command object and the request contains a body, Grails will attempt to parse the body of the request based on the request content type and use the body to do data binding on the command object. See the following example.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/bindingdemo/DemoController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> bindingdemo
<span class="type">class</span> <span class="class">DemoController</span> {
<span class="keyword">def</span> <span class="function">createWidget</span>(Widget w) {
render <span class="string"><span class="delimiter">&quot;</span><span class="content">Name: </span><span class="inline"><span class="inline-delimiter">${</span>w?.name<span class="inline-delimiter">}</span></span><span class="content">, Size: </span><span class="inline"><span class="inline-delimiter">${</span>w?.size<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>
}
}
<span class="type">class</span> <span class="class">Widget</span> {
<span class="predefined-type">String</span> name
<span class="predefined-type">Integer</span> size
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ curl -H &quot;Content-Type: application/json&quot; -d '{&quot;name&quot;:&quot;Some Widget&quot;,&quot;42&quot;}'[size] localhost:8080/demo/createWidget
Name: Some Widget, Size: 42
$ curl -H &quot;Content-Type: application/xml&quot; -d '&lt;widget&gt;&lt;name&gt;Some Other Widget&lt;/name&gt;&lt;size&gt;2112&lt;/size&gt;&lt;/widget&gt;' localhost:8080/bodybind/demo/createWidget
Name: Some Other Widget, Size: 2112</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The request body will not be parsed under the following conditions:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>The request method is GET</p>
</li>
<li>
<p>The request method is DELETE</p>
</li>
<li>
<p>The content length is 0</p>
</li>
</ul>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Note that the body of the request is being parsed to make that work. Any attempt to read the body of the request after that will fail since the corresponding input stream will be empty. The controller action can either use a command object or it can parse the body of the request on its own (either directly, or by referring to something like request.JSON), but cannot do both.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/bindingdemo/DemoController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> bindingdemo
<span class="type">class</span> <span class="class">DemoController</span> {
<span class="keyword">def</span> <span class="function">createWidget</span>(Widget w) {
<span class="comment">// this will fail because it requires reading the body,</span>
<span class="comment">// which has already been read.</span>
<span class="keyword">def</span> json = request.JSON
<span class="comment">// ...</span>
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_working_with_lists_of_command_objects">Working with Lists of Command Objects</h4>
<div class="paragraph">
<p>A common use case for command objects is a Command Object that contains a collection of another:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">DemoController</span> {
<span class="keyword">def</span> <span class="function">createAuthor</span>(AuthorCommand command) {
<span class="comment">// ...</span>
}
<span class="type">class</span> <span class="class">AuthorCommand</span> {
<span class="predefined-type">String</span> fullName
<span class="predefined-type">List</span>&lt;BookCommand&gt; books
}
<span class="type">class</span> <span class="class">BookCommand</span> {
<span class="predefined-type">String</span> title
<span class="predefined-type">String</span> isbn
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>On this example, we want to create an Author with multiple Books.</p>
</div>
<div class="paragraph">
<p>In order to make this work from the UI layer, you can do the following in your GSP:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:form</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">submit-author-books</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">controller</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">demo</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">action</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">createAuthor</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
<span class="tag">&lt;g:fieldValue</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">fullName</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span>
<span class="tag">&lt;ul&gt;</span>
<span class="tag">&lt;li&gt;</span>
<span class="tag">&lt;g:fieldValue</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[0].title</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span>
<span class="tag">&lt;g:fieldValue</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[0].isbn</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span>
<span class="tag">&lt;/li&gt;</span>
<span class="tag">&lt;li&gt;</span>
<span class="tag">&lt;g:fieldValue</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[1].title</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span>
<span class="tag">&lt;g:fieldValue</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">books[1].isbn</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span>
<span class="tag">&lt;/li&gt;</span>
<span class="tag">&lt;/ul&gt;</span>
<span class="tag">&lt;/g:form&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>There is also support for JSON, so you can submit the following with correct databinding</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="json">{
<span class="key"><span class="delimiter">&quot;</span><span class="content">fullName</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">Graeme Rocher</span><span class="delimiter">&quot;</span></span>,
<span class="key"><span class="delimiter">&quot;</span><span class="content">books</span><span class="delimiter">&quot;</span></span>: [{
<span class="key"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">The Definitive Guide to Grails</span><span class="delimiter">&quot;</span></span>,
<span class="key"><span class="delimiter">&quot;</span><span class="content">isbn</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">1111-343455-1111</span><span class="delimiter">&quot;</span></span>
}, {
<span class="key"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">The Definitive Guide to Grails 2</span><span class="delimiter">&quot;</span></span>,
<span class="key"><span class="delimiter">&quot;</span><span class="content">isbn</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">1111-343455-1112</span><span class="delimiter">&quot;</span></span>
}],
}</code></pre>
</div>
</div>
</div>
<a name="7.1.11 Handling Duplicate Form Submissions"><!-- Legacy link --></a>
<h2 id="formtokens">8.1.11 Handling Duplicate Form Submissions</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/controllers/formtokens.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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="http://gsp.grails.org/latest/ref/Tags/form.html">form</a> tag:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:form</span> <span class="attribute-name">useToken</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">true</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">...</span><span class="tag">&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Then in your controller code you can use the <a href="../ref/Controllers/withForm.html">withForm</a> method to handle valid and invalid requests:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">withForm {
<span class="comment">// good request</span>
}.invalidToken {
<span class="comment">// bad request</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you only provide the <a href="../ref/Controllers/withForm.html">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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:if</span> <span class="attribute-name">test</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${flash.invalidToken}</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
Don't click the button twice!
<span class="tag">&lt;/g:if&gt;</span></code></pre>
</div>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
The <a href="../ref/Controllers/withForm.html">withForm</a> tag makes use of the <a href="../ref/Controllers/session.html">session</a> and hence requires session affinity or clustered sessions if used in a cluster.
</td>
</tr>
</table>
</div>
<a name="7.1.12 Simple Type Converters"><!-- Legacy link --></a>
<h2 id="typeConverters">8.1.12 Simple Type Converters</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/controllers/typeConverters.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect2">
<h3 id="_type_conversion_methods">Type Conversion Methods</h3>
<div class="paragraph">
<p>If you prefer to avoid the overhead of <a href="theWebLayer.html#dataBinding">data binding</a> and simply want to convert incoming parameters (typically Strings) into another more appropriate type the <a href="../ref/Controllers/params.html">params</a> object has a number of convenience methods for each type:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> total = params.int(<span class="string"><span class="delimiter">'</span><span class="content">total</span><span class="delimiter">'</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>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&#8217;t have to perform any additional checks on the parameters.</p>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> total = params.int(<span class="string"><span class="delimiter">'</span><span class="content">total</span><span class="delimiter">'</span></span>, <span class="integer">42</span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>These same type conversion methods are also available on the <code>attrs</code> parameter of GSP tags.</p>
</div>
</div>
<div class="sect2">
<h3 id="_handling_multi_parameters">Handling Multi Parameters</h3>
<div class="paragraph">
<p>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&amp;name=Judy</code>.</p>
</div>
<div class="paragraph">
<p>In this case dealing with one parameter and dealing with many has different semantics since Groovy&#8217;s iteration mechanics for <code>String</code> iterate over each character. To avoid this problem the <a href="../ref/Controllers/params.html">params</a> object provides a <code>list</code> method that always returns a list:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">for</span> (name <span class="keyword">in</span> params.list(<span class="string"><span class="delimiter">'</span><span class="content">name</span><span class="delimiter">'</span></span>)) {
println name
}</code></pre>
</div>
</div>
</div>
<h2 id="controllerExceptionHandling">8.1.13 Declarative Controller Exception Handling</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/controllers/controllerExceptionHandling.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails controllers support a simple mechanism for declarative exception handling. If a controller declares a method that accepts a single argument and the argument type is <code>java.lang.Exception</code> or some subclass of <code>java.lang.Exception</code>, that method will be invoked any time an action in that controller throws an exception of that type. See the following example.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/demo/DemoController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> demo
<span class="type">class</span> <span class="class">DemoController</span> {
<span class="keyword">def</span> <span class="function">someAction</span>() {
<span class="comment">// do some work</span>
}
<span class="keyword">def</span> <span class="function">handleSQLException</span>(<span class="exception">SQLException</span> e) {
render <span class="string"><span class="delimiter">'</span><span class="content">A SQLException Was Handled</span><span class="delimiter">'</span></span>
}
<span class="keyword">def</span> <span class="function">handleBatchUpdateException</span>(<span class="exception">BatchUpdateException</span> e) {
redirect <span class="key">controller</span>: <span class="string"><span class="delimiter">'</span><span class="content">logging</span><span class="delimiter">'</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">'</span><span class="content">batchProblem</span><span class="delimiter">'</span></span>
}
<span class="keyword">def</span> <span class="function">handleNumberFormatException</span>(<span class="exception">NumberFormatException</span> nfe) {
[<span class="key">problemDescription</span>: <span class="string"><span class="delimiter">'</span><span class="content">A Number Was Invalid</span><span class="delimiter">'</span></span>]
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>That controller will behave as if it were written something like this&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/demo/DemoController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> demo
<span class="type">class</span> <span class="class">DemoController</span> {
<span class="keyword">def</span> <span class="function">someAction</span>() {
<span class="keyword">try</span> {
<span class="comment">// do some work</span>
} <span class="keyword">catch</span> (<span class="exception">BatchUpdateException</span> e) {
<span class="keyword">return</span> handleBatchUpdateException(e)
} <span class="keyword">catch</span> (<span class="exception">SQLException</span> e) {
<span class="keyword">return</span> handleSQLException(e)
} <span class="keyword">catch</span> (<span class="exception">NumberFormatException</span> e) {
<span class="keyword">return</span> handleNumberFormatException(e)
}
}
<span class="keyword">def</span> <span class="function">handleSQLException</span>(<span class="exception">SQLException</span> e) {
render <span class="string"><span class="delimiter">'</span><span class="content">A SQLException Was Handled</span><span class="delimiter">'</span></span>
}
<span class="keyword">def</span> <span class="function">handleBatchUpdateException</span>(<span class="exception">BatchUpdateException</span> e) {
redirect <span class="key">controller</span>: <span class="string"><span class="delimiter">'</span><span class="content">logging</span><span class="delimiter">'</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">'</span><span class="content">batchProblem</span><span class="delimiter">'</span></span>
}
<span class="keyword">def</span> <span class="function">handleNumberFormatException</span>(<span class="exception">NumberFormatException</span> nfe) {
[<span class="key">problemDescription</span>: <span class="string"><span class="delimiter">'</span><span class="content">A Number Was Invalid</span><span class="delimiter">'</span></span>]
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The exception handler method names can be any valid method name. The name is not what makes the method an exception handler, the <code>Exception</code> argument type is the important part.</p>
</div>
<div class="paragraph">
<p>The exception handler methods can do anything that a controller action can do including invoking <code>render</code>, <code>redirect</code>, returning a model, etc.</p>
</div>
<div class="paragraph">
<p>One way to share exception handler methods across multiple controllers is to use inheritance. Exception handler methods are inherited into subclasses so an application could define the exception handlers in an abstract class that multiple controllers extend from. Another way to share exception handler methods across multiple controllers is to use a trait, as shown below&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="title">src/main/groovy/com/demo/DatabaseExceptionHandler.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.demo
trait DatabaseExceptionHandler {
<span class="keyword">def</span> <span class="function">handleSQLException</span>(<span class="exception">SQLException</span> e) {
<span class="comment">// handle SQLException</span>
}
<span class="keyword">def</span> <span class="function">handleBatchUpdateException</span>(<span class="exception">BatchUpdateException</span> e) {
<span class="comment">// handle BatchUpdateException</span>
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/com/demo/DemoController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.demo
<span class="type">class</span> <span class="class">DemoController</span> <span class="directive">implements</span> DatabaseExceptionHandler {
<span class="comment">// all of the exception handler methods defined</span>
<span class="comment">// in DatabaseExceptionHandler will be added to</span>
<span class="comment">// this class at compile time</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Exception handler methods must be present at compile time. Specifically, exception handler methods which are runtime metaprogrammed onto a controller class are not supported.</p>
</div>
<a name="7.2 Groovy Server Pages"><!-- Legacy link --></a>
<h2 id="gsp">8.2 Groovy Server Pages</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/gsp.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p><a href="http://gsp.grails.org">Groovy Servers Pages</a> (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>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
Although GSP can render any format, not just HTML, it is more designed around rendering markup. If you are looking for a way to simplify JSON responses take a look at <a href="webServices.html#jsonViews">JSON Views</a>.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>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">render</a> method such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">render(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">index</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>A GSP is typically a mix of mark-up and GSP tags which aid in view rendering.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
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>bad</strong> thing and most GSP pages contain no code and needn&#8217;t do so.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">show</span>() {
[<span class="key">book</span>: <span class="predefined-type">Book</span>.get(params.id)]
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span>{book.title}</code></pre>
</div>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
Embedding data received from user input has the risk of making your application vulnerable to an Cross Site Scripting (XSS) attack. Please read the documentation on <a href="security.html#xssPrevention">XSS prevention</a> for information on how to prevent XSS attacks.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>For more information on using GSP please refer to the <a href="http://gsp.grails.org">dedicated GSP documentation</a>.</p>
</div>
<a name="7.4 URL Mappings"><!-- Legacy link --></a>
<h2 id="urlmappings">8.3 URL Mappings</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/urlmappings.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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/controllers/mypackage/UrlMappings.groovy</code>.</p>
</div>
<div class="paragraph">
<p>The <code>UrlMappings</code> class contains a single property called <code>mappings</code> that has been assigned a block of code:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> mypackage
<span class="type">class</span> <span class="class">UrlMappings</span> {
<span class="directive">static</span> mappings = {
}
}</code></pre>
</div>
</div>
<a name="7.4.1 Mapping to Controllers and Actions"><!-- Legacy link --></a>
<h2 id="mappingToControllersAndActions">8.3.1 Mapping to Controllers and Actions</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/urlmappings/mappingToControllersAndActions.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/product</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">product</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">list</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this case we&#8217;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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/product</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">product</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>An alternative syntax is to assign the controller and action to use within a block passed to the method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/product</span><span class="delimiter">&quot;</span></span> {
controller = <span class="string"><span class="delimiter">&quot;</span><span class="content">product</span><span class="delimiter">&quot;</span></span>
action = <span class="string"><span class="delimiter">&quot;</span><span class="content">list</span><span class="delimiter">&quot;</span></span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Which syntax you use is largely dependent on personal preference.</p>
</div>
<div class="paragraph">
<p>If you have mappings that all fall under a particular path you can group mappings with the <code>group</code> method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">group <span class="string"><span class="delimiter">&quot;</span><span class="content">/product</span><span class="delimiter">&quot;</span></span>, {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/apple</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">product</span><span class="delimiter">&quot;</span></span>, <span class="key">id</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">apple</span><span class="delimiter">&quot;</span></span>)
<span class="string"><span class="delimiter">&quot;</span><span class="content">/htc</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">product</span><span class="delimiter">&quot;</span></span>, <span class="key">id</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">htc</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also create nested <code>group</code> url mappings:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">group <span class="string"><span class="delimiter">&quot;</span><span class="content">/store</span><span class="delimiter">&quot;</span></span>, {
group <span class="string"><span class="delimiter">&quot;</span><span class="content">/product</span><span class="delimiter">&quot;</span></span>, {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">product</span><span class="delimiter">&quot;</span></span>)
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>To rewrite one URI onto another explicit URI (rather than a controller/action pair) do something like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/hello</span><span class="delimiter">&quot;</span></span>(<span class="key">uri</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/hello.dispatch</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Rewriting specific URIs is often useful when integrating with other frameworks.</p>
</div>
<a name="7.4.3 Mapping to REST resources"><!-- Legacy link --></a>
<h2 id="restfulMappings">8.3.2 Mapping to REST resources</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/urlmappings/restfulMappings.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Since Grails 2.3, it possible to create RESTful URL mappings that map onto controllers by convention. The syntax to do so is as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">'</span><span class="content">book</span><span class="delimiter">'</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>You define a base URI and the name of the controller to map to using the <code>resources</code> parameter. The above mapping will result in the following URLs:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">HTTP Method</th>
<th class="tableblock halign-left valign-top">URI</th>
<th class="tableblock halign-left valign-top">Grails Action</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">index</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/create</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">create</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">POST</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">save</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${id}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">show</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${id}/edit</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">edit</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">PUT</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${id}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">update</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">DELETE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${id}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">delete</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>If you are not sure which mapping will be generated for your case just run the command <code>url-mappings-report</code> in your grails console. It will give you a really neat report for all the url mappings.</p>
</div>
<div class="paragraph">
<p>If you wish to include or exclude any of the generated URL mappings you can do so with the <code>includes</code> or <code>excludes</code> parameter, which accepts the name of the Grails action to include or exclude:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">'</span><span class="content">book</span><span class="delimiter">'</span></span>, <span class="key">excludes</span>:[<span class="string"><span class="delimiter">'</span><span class="content">delete</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">update</span><span class="delimiter">'</span></span>])
or
<span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">'</span><span class="content">book</span><span class="delimiter">'</span></span>, <span class="key">includes</span>:[<span class="string"><span class="delimiter">'</span><span class="content">index</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">show</span><span class="delimiter">'</span></span>])</code></pre>
</div>
</div>
<div class="sect3">
<h4 id="_explicit_rest_mappings">Explicit REST Mappings</h4>
<div class="paragraph">
<p>As of Grails 3.1, if you prefer not to rely on a <code>resources</code> mapping to define your mappings then you can prefix any URL mapping with the HTTP method name (in lower case) to indicate the HTTP method it applies to. The following URL mapping:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">'</span><span class="content">book</span><span class="delimiter">'</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Is equivalent to:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">get <span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">index</span><span class="delimiter">&quot;</span></span>)
get <span class="string"><span class="delimiter">&quot;</span><span class="content">/books/create</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">create</span><span class="delimiter">&quot;</span></span>)
post <span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">save</span><span class="delimiter">&quot;</span></span>)
get <span class="string"><span class="delimiter">&quot;</span><span class="content">/books/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>)
get <span class="string"><span class="delimiter">&quot;</span><span class="content">/books/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="content">/edit</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">edit</span><span class="delimiter">&quot;</span></span>)
put <span class="string"><span class="delimiter">&quot;</span><span class="content">/books/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">update</span><span class="delimiter">&quot;</span></span>)
delete <span class="string"><span class="delimiter">&quot;</span><span class="content">/books/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">delete</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Notice how the HTTP method name is prefixed prior to each URL mapping definition.</p>
</div>
</div>
<div class="sect3">
<h4 id="_single_resources">Single resources</h4>
<div class="paragraph">
<p>A single resource is a resource for which there is only one (possibly per user) in the system. You can create a single resource using the <code>single</code> parameter (as opposed to <code>resources</code>):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/book</span><span class="delimiter">&quot;</span></span>(<span class="key">single</span>:<span class="string"><span class="delimiter">'</span><span class="content">book</span><span class="delimiter">'</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>This results in the following URL mappings:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">HTTP Method</th>
<th class="tableblock halign-left valign-top">URI</th>
<th class="tableblock halign-left valign-top">Grails Action</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/book/create</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">create</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">POST</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/book</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">save</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/book</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">show</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/book/edit</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">edit</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">PUT</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/book</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">update</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">DELETE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/book</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">delete</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>The main difference is that the id is not included in the URL mapping.</p>
</div>
</div>
<div class="sect3">
<h4 id="_nested_resources">Nested Resources</h4>
<div class="paragraph">
<p>You can nest resource mappings to generate child resources. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">'</span><span class="content">book</span><span class="delimiter">'</span></span>) {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/authors</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">author</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above will result in the following URL mappings:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">HTTP Method</th>
<th class="tableblock halign-left valign-top">URL</th>
<th class="tableblock halign-left valign-top">Grails Action</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${bookId}/authors</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">index</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${bookId}/authors/create</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">create</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">POST</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${bookId}/authors</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">save</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${bookId}/authors/${id}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">show</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${bookId}/authors/edit/${id}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">edit</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">PUT</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${bookId}/authors/${id}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">update</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">DELETE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${bookId}/authors/${id}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">delete</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>You can also nest regular URL mappings within a resource mapping:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>) {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/publisher</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">publisher</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will result in the following URL being available:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">HTTP Method</th>
<th class="tableblock halign-left valign-top">URL</th>
<th class="tableblock halign-left valign-top">Grails Action</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${bookId}/publisher</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">index</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>To map a URI directly below a resource then use a collection block:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>) {
collection {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/publisher</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">publisher</span><span class="delimiter">&quot;</span></span>)
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will result in the following URL being available (without the ID):</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">HTTP Method</th>
<th class="tableblock halign-left valign-top">URL</th>
<th class="tableblock halign-left valign-top">Grails Action</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/publisher</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">index</p></td>
</tr>
</tbody>
</table>
</div>
<div class="sect3">
<h4 id="_linking_to_restful_mappings">Linking to RESTful Mappings</h4>
<div class="paragraph">
<p>You can link to any URL mapping created with the <code>g:link</code> tag provided by Grails simply by referencing the controller and action to link to:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">&lt;<span class="key">g</span>:link controller=<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span> action=<span class="string"><span class="delimiter">&quot;</span><span class="content">index</span><span class="delimiter">&quot;</span></span>&gt;My Link&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">g:link&gt;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>As a convenience you can also pass a domain instance to the <code>resource</code> attribute of the <code>link</code> tag:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">&lt;<span class="key">g</span>:link resource=<span class="string"><span class="delimiter">&quot;</span><span class="inline"><span class="inline-delimiter">${</span>book<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>&gt;My Link&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">g:link&gt;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>This will automatically produce the correct link (in this case "/books/1" for an id of "1").</p>
</div>
<div class="paragraph">
<p>The case of nested resources is a little different as they typically required two identifiers (the id of the resource and the one it is nested within). For example given the nested resources:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">'</span><span class="content">book</span><span class="delimiter">'</span></span>) {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/authors</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">author</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you wished to link to the <code>show</code> action of the <code>author</code> controller, you would write:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// Results in /books/1/authors/2</span>
&lt;<span class="key">g</span>:link controller=<span class="string"><span class="delimiter">&quot;</span><span class="content">author</span><span class="delimiter">&quot;</span></span> action=<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span> method=<span class="string"><span class="delimiter">&quot;</span><span class="content">GET</span><span class="delimiter">&quot;</span></span> params=<span class="string"><span class="delimiter">&quot;</span><span class="content">[bookId:1]</span><span class="delimiter">&quot;</span></span> id=<span class="string"><span class="delimiter">&quot;</span><span class="content">2</span><span class="delimiter">&quot;</span></span>&gt;The Author&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">g:link&gt;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>However, to make this more concise there is a <code>resource</code> attribute to the link tag which can be used instead:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// Results in /books/1/authors/2</span>
&lt;<span class="key">g</span>:link resource=<span class="string"><span class="delimiter">&quot;</span><span class="content">book/author</span><span class="delimiter">&quot;</span></span> action=<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span> bookId=<span class="string"><span class="delimiter">&quot;</span><span class="content">1</span><span class="delimiter">&quot;</span></span> id=<span class="string"><span class="delimiter">&quot;</span><span class="content">2</span><span class="delimiter">&quot;</span></span>&gt;My Link&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">g:link&gt;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The resource attribute accepts a path to the resource separated by a slash (in this case "book/author"). The attributes of the tag can be used to specify the necessary <code>bookId</code> parameter.</p>
</div>
</div>
<a name="7.4.2 Redirects In URL Mappings"><!-- Legacy link --></a>
<h2 id="redirectMappings">8.3.3 Redirects In URL Mappings</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/urlmappings/redirectMappings.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Since Grails 2.3, it is possible to define URL mappings which specify a redirect.
When a URL mapping specifies a redirect, any time that mapping matches an incoming
request, a redirect is initiated with information provided by the mapping.</p>
</div>
<div class="paragraph">
<p>When a URL mapping specifies a redirect the mapping must either supply a String
representing a URI to redirect to or must provide a Map representing the target
of the redirect. That Map is structured just like the Map that may be passed
as an argument to the <code>redirect</code> method in a controller.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/viewBooks</span><span class="delimiter">&quot;</span></span>(<span class="key">redirect</span>: [<span class="key">uri</span>: <span class="string"><span class="delimiter">'</span><span class="content">/books/list</span><span class="delimiter">'</span></span>])
<span class="string"><span class="delimiter">&quot;</span><span class="content">/viewAuthors</span><span class="delimiter">&quot;</span></span>(<span class="key">redirect</span>: [<span class="key">controller</span>: <span class="string"><span class="delimiter">'</span><span class="content">author</span><span class="delimiter">'</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">'</span><span class="content">list</span><span class="delimiter">'</span></span>])
<span class="string"><span class="delimiter">&quot;</span><span class="content">/viewPublishers</span><span class="delimiter">&quot;</span></span>(<span class="key">redirect</span>: [<span class="key">controller</span>: <span class="string"><span class="delimiter">'</span><span class="content">publisher</span><span class="delimiter">'</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">'</span><span class="content">list</span><span class="delimiter">'</span></span>, <span class="key">permanent</span>: <span class="predefined-constant">true</span>])</code></pre>
</div>
</div>
<div class="paragraph">
<p>Request parameters that were part of the original request will not be included in the redirect by default. To include
them it is necessary to add the parameter <code>keepParamsWhenRedirect: true</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/viewBooks</span><span class="delimiter">&quot;</span></span>(<span class="key">redirect</span>: [<span class="key">uri</span>: <span class="string"><span class="delimiter">'</span><span class="content">/books/list</span><span class="delimiter">'</span></span>, <span class="key">keepParamsWhenRedirect</span>: <span class="predefined-constant">true</span>])
<span class="string"><span class="delimiter">&quot;</span><span class="content">/viewAuthors</span><span class="delimiter">&quot;</span></span>(<span class="key">redirect</span>: [<span class="key">controller</span>: <span class="string"><span class="delimiter">'</span><span class="content">author</span><span class="delimiter">'</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">'</span><span class="content">list</span><span class="delimiter">'</span></span>, <span class="key">keepParamsWhenRedirect</span>: <span class="predefined-constant">true</span>])
<span class="string"><span class="delimiter">&quot;</span><span class="content">/viewPublishers</span><span class="delimiter">&quot;</span></span>(<span class="key">redirect</span>: [<span class="key">controller</span>: <span class="string"><span class="delimiter">'</span><span class="content">publisher</span><span class="delimiter">'</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">'</span><span class="content">list</span><span class="delimiter">'</span></span>, <span class="key">permanent</span>: <span class="predefined-constant">true</span>, <span class="key">keepParamsWhenRedirect</span>: <span class="predefined-constant">true</span>])</code></pre>
</div>
</div>
<a name="7.4.4 Embedded Variables"><!-- Legacy link --></a>
<h2 id="embeddedVariables">8.3.4 Embedded Variables</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/urlmappings/embeddedVariables.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_simple_variables">Simple Variables</h4>
<div class="paragraph">
<p>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&#8217;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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/product/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">product</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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">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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ProductController</span> {
<span class="keyword">def</span> <span class="function">index</span>() { render params.id }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can of course construct more complex examples of mappings. For example the traditional blog URL format could be mapped as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>blog</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>year</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>month</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>day</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">blog</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above mapping would let you do things like:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>/graemerocher/2007/01/10/my_funky_blog_entry</code></pre>
</div>
</div>
<div class="paragraph">
<p>The individual tokens in the URL would again be mapped into the <a href="../ref/Controllers/params.html">params</a> object with values available for <code>year</code>, <code>month</code>, <code>day</code>, <code>id</code> and so on.</p>
</div>
</div>
<div class="sect3">
<h4 id="_dynamic_controller_and_action_names">Dynamic Controller and Action Names</h4>
<div class="paragraph">
<p>Variables can also be used to dynamically construct the controller and action name. In fact the default Grails URL mappings use this technique:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>controller</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>action</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="content">?</span><span class="delimiter">&quot;</span></span>()
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>You can also resolve the controller name and action name to execute dynamically using a closure:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>controller</span><span class="delimiter">&quot;</span></span> {
action = { params.goHere }
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_optional_variables">Optional Variables</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>blog</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>year</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>month</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>day</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="content">?</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">blog</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>With this mapping all of these URLs would match with only the relevant parameters being populated in the <a href="../ref/Controllers/params.html">params</a> object:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>/graemerocher/2007/01/10/my_funky_blog_entry
/graemerocher/2007/01/10
/graemerocher/2007/01
/graemerocher/2007
/graemerocher</pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_optional_file_extensions">Optional File Extensions</h4>
<div class="paragraph">
<p>If you wish to capture the extension of a particular path, then a special case mapping exists:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>controller</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>action</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="content">?(.</span><span class="inline"><span class="inline-delimiter">$</span>format</span><span class="content">)?</span><span class="delimiter">&quot;</span></span>()</code></pre>
</div>
</div>
<div class="paragraph">
<p>By adding the <code>(.$format)?</code> mapping you can access the file extension using the <code>response.format</code> property in a controller:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">index</span>() {
render <span class="string"><span class="delimiter">&quot;</span><span class="content">extension is </span><span class="inline"><span class="inline-delimiter">${</span>response.format<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_arbitrary_variables">Arbitrary Variables</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/holiday/win</span><span class="delimiter">&quot;</span></span> {
id = <span class="string"><span class="delimiter">&quot;</span><span class="content">Marrakech</span><span class="delimiter">&quot;</span></span>
year = <span class="integer">2007</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This variables will be available within the <a href="../ref/Controllers/params.html">params</a> object passed to the controller.</p>
</div>
</div>
<div class="sect3">
<h4 id="_dynamically_resolved_variables">Dynamically Resolved Variables</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/holiday/win</span><span class="delimiter">&quot;</span></span> {
id = { params.id }
isEligible = { session.user != <span class="predefined-constant">null</span> } <span class="comment">// must be logged in</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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.</p>
</div>
</div>
<a name="7.4.5 Mapping to Views"><!-- Legacy link --></a>
<h2 id="mappingToViews">8.3.5 Mapping to Views</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/urlmappings/mappingToViews.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="delimiter">&quot;</span></span>(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/index</span><span class="delimiter">&quot;</span></span>) <span class="comment">// map the root URL</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Alternatively if you need a view that is specific to a given controller you could use:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/help</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">site</span><span class="delimiter">&quot;</span></span>, <span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">help</span><span class="delimiter">&quot;</span></span>) <span class="comment">// to a view for a controller</span>
}</code></pre>
</div>
</div>
<a name="7.4.6 Mapping to Response Codes"><!-- Legacy link --></a>
<h2 id="mappingToResponseCodes">8.3.6 Mapping to Response Codes</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/urlmappings/mappingToResponseCodes.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
<span class="string"><span class="delimiter">&quot;</span><span class="content">403</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">errors</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">forbidden</span><span class="delimiter">&quot;</span></span>)
<span class="string"><span class="delimiter">&quot;</span><span class="content">404</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">errors</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">notFound</span><span class="delimiter">&quot;</span></span>)
<span class="string"><span class="delimiter">&quot;</span><span class="content">500</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">errors</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">serverError</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or you can specify custom error pages:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
<span class="string"><span class="delimiter">&quot;</span><span class="content">403</span><span class="delimiter">&quot;</span></span>(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/errors/forbidden</span><span class="delimiter">&quot;</span></span>)
<span class="string"><span class="delimiter">&quot;</span><span class="content">404</span><span class="delimiter">&quot;</span></span>(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/errors/notFound</span><span class="delimiter">&quot;</span></span>)
<span class="string"><span class="delimiter">&quot;</span><span class="content">500</span><span class="delimiter">&quot;</span></span>(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/errors/serverError</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="sect3">
<h4 id="_declarative_error_handling">Declarative Error Handling</h4>
<div class="paragraph">
<p>In addition you can configure handlers for individual exceptions:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
<span class="string"><span class="delimiter">&quot;</span><span class="content">403</span><span class="delimiter">&quot;</span></span>(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/errors/forbidden</span><span class="delimiter">&quot;</span></span>)
<span class="string"><span class="delimiter">&quot;</span><span class="content">404</span><span class="delimiter">&quot;</span></span>(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/errors/notFound</span><span class="delimiter">&quot;</span></span>)
<span class="string"><span class="delimiter">&quot;</span><span class="content">500</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">errors</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">illegalArgument</span><span class="delimiter">&quot;</span></span>,
<span class="key">exception</span>: <span class="exception">IllegalArgumentException</span>)
<span class="string"><span class="delimiter">&quot;</span><span class="content">500</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">errors</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">nullPointer</span><span class="delimiter">&quot;</span></span>,
<span class="key">exception</span>: <span class="exception">NullPointerException</span>)
<span class="string"><span class="delimiter">&quot;</span><span class="content">500</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">errors</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">customException</span><span class="delimiter">&quot;</span></span>,
<span class="key">exception</span>: MyException)
<span class="string"><span class="delimiter">&quot;</span><span class="content">500</span><span class="delimiter">&quot;</span></span>(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/errors/serverError</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>You can access the exception from your custom error handing view or controller action using the request&#8217;s <code>exception</code> attribute like so:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ErrorController</span> {
<span class="keyword">def</span> <span class="function">handleError</span>() {
<span class="keyword">def</span> exception = request.exception
<span class="comment">// perform desired processing to handle the exception</span>
}
}</code></pre>
</div>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
If your error-handling controller action throws an exception as well, you&#8217;ll end up with a <code>StackOverflowException</code>.
</td>
</tr>
</table>
</div>
</div>
<a name="7.4.7 Mapping to HTTP methods"><!-- Legacy link --></a>
<h2 id="mappingHTTP">8.3.7 Mapping to HTTP methods</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/urlmappings/mappingHTTP.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>As an example the following mappings provide a RESTful API URL mappings for the <code>ProductController</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/product/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">product</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">update</span><span class="delimiter">&quot;</span></span>, <span class="key">method</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">PUT</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that if you specify a HTTP method other than GET in your URL mapping, you also have to specify it when creating the corresponding link by passing the <code>method</code> argument to <code>g:link</code> or <code>g:createLink</code> to get a link of the desired format.</p>
</div>
<a name="7.4.8 Mapping Wildcards"><!-- Legacy link --></a>
<h2 id="mappingWildcards">8.3.8 Mapping Wildcards</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/urlmappings/mappingWildcards.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails' URL mappings mechanism also supports wildcard mappings. For example consider the following mapping:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/images/*.jpg</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">image</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/images/</span><span class="inline"><span class="inline-delimiter">$</span>name</span><span class="content">.jpg</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">image</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>However, you can also use double wildcards to match more than one level below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/images/**.jpg</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">image</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
<span class="comment">// will match /image/logo.jpg and /image/other/logo.jpg</span>
<span class="string"><span class="delimiter">&quot;</span><span class="content">/images/</span><span class="inline"><span class="inline-delimiter">$</span>name</span><span class="content">**.jpg</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">image</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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">params</a> object:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> name = params.name
println name <span class="comment">// prints &quot;logo&quot; or &quot;other/logo&quot;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">UrlMappings</span> {
<span class="directive">static</span> excludes = [<span class="string"><span class="delimiter">&quot;</span><span class="content">/images/*</span><span class="delimiter">&quot;</span></span>, <span class="string"><span class="delimiter">&quot;</span><span class="content">/css/*</span><span class="delimiter">&quot;</span></span>]
<span class="directive">static</span> mappings = {
...
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this case Grails won&#8217;t attempt to match any URIs that start with <code>/images</code> or <code>/css</code>.</p>
</div>
<a name="7.4.9 Automatic Link Re-Writing"><!-- Legacy link --></a>
<h2 id="automaticLinkRewriting">8.3.9 Automatic Link Re-Writing</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/urlmappings/automaticLinkRewriting.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Another great feature of URL mappings is that they automatically customize the behaviour of the <a href="http://gsp.grails.org/latest/ref/Tags/link.html">link</a> tag so that changing the mappings don&#8217;t require you to go and change all of your links.</p>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>blog</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>year</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>month</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>day</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="content">?</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">blog</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you use the link tag as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:link</span> <span class="attribute-name">controller</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">blog</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">action</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>
<span class="attribute-name">params</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">[blog:'fred', year:2007]</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
My Blog
<span class="tag">&lt;/g:link&gt;</span>
<span class="tag">&lt;g:link</span> <span class="attribute-name">controller</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">blog</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">action</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>
<span class="attribute-name">params</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">[blog:'fred', year:2007, month:10]</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
My Blog - October 2007 Posts
<span class="tag">&lt;/g:link&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Grails will automatically re-write the URL in the correct format:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;a</span> <span class="attribute-name">href</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">/fred/2007</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>My Blog<span class="tag">&lt;/a&gt;</span>
<span class="tag">&lt;a</span> <span class="attribute-name">href</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">/fred/2007/10</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>My Blog - October 2007 Posts<span class="tag">&lt;/a&gt;</span></code></pre>
</div>
</div>
<a name="7.4.10 Applying Constraints"><!-- Legacy link --></a>
<h2 id="applyingConstraints">8.3.10 Applying Constraints</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/urlmappings/applyingConstraints.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>URL Mappings also support Grails' unified <a href="validation.html#constraints">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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>blog</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>year</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>month</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>day</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="content">?</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">blog</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This allows URLs such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>/graemerocher/2007/01/10/my_funky_blog_entry</code></pre>
</div>
</div>
<div class="paragraph">
<p>However, it would also allow:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>/graemerocher/not_a_year/not_a_month/not_a_day/my_funky_blog_entry</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>blog</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>year</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>month</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>day</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="content">?</span><span class="delimiter">&quot;</span></span> {
controller = <span class="string"><span class="delimiter">&quot;</span><span class="content">blog</span><span class="delimiter">&quot;</span></span>
action = <span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>
constraints {
year(<span class="key">matches</span>:<span class="regexp"><span class="delimiter">/</span><span class="char">\\</span><span class="char">\d</span><span class="content">{4}</span><span class="delimiter">/</span></span>)
month(<span class="key">matches</span>:<span class="regexp"><span class="delimiter">/</span><span class="char">\\</span><span class="char">\d</span><span class="content">{2}</span><span class="delimiter">/</span></span>)
day(<span class="key">matches</span>:<span class="regexp"><span class="delimiter">/</span><span class="char">\\</span><span class="char">\d</span><span class="content">{2}</span><span class="delimiter">/</span></span>)
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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.</p>
</div>
<a name="7.4.11 Named URL Mappings"><!-- Legacy link --></a>
<h2 id="namedMappings">8.3.11 Named URL Mappings</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/urlmappings/namedMappings.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>The syntax for defining a named mapping is as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
name &lt;mapping name&gt;: &lt;url pattern&gt; {
<span class="comment">// ...</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
name <span class="key">personList</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/showPeople</span><span class="delimiter">&quot;</span></span> {
controller = <span class="string"><span class="delimiter">'</span><span class="content">person</span><span class="delimiter">'</span></span>
action = <span class="string"><span class="delimiter">'</span><span class="content">list</span><span class="delimiter">'</span></span>
}
name <span class="key">accountDetails</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/details/</span><span class="inline"><span class="inline-delimiter">$</span>acctNumber</span><span class="delimiter">&quot;</span></span> {
controller = <span class="string"><span class="delimiter">'</span><span class="content">product</span><span class="delimiter">'</span></span>
action = <span class="string"><span class="delimiter">'</span><span class="content">accountDetails</span><span class="delimiter">'</span></span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The mapping may be referenced in a link tag in a GSP.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:link</span> <span class="attribute-name">mapping</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">personList</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>List People<span class="tag">&lt;/g:link&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>That would result in:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;a</span> <span class="attribute-name">href</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">/showPeople</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>List People<span class="tag">&lt;/a&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Parameters may be specified using the params attribute.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:link</span> <span class="attribute-name">mapping</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">accountDetails</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">params</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">[acctNumber:'8675309']</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
Show Account
<span class="tag">&lt;/g:link&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>That would result in:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;a</span> <span class="attribute-name">href</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">/details/8675309</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>Show Account<span class="tag">&lt;/a&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Alternatively you may reference a named mapping using the link namespace.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;link:personList&gt;</span>List People<span class="tag">&lt;/link:personList&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>That would result in:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;a</span> <span class="attribute-name">href</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">/showPeople</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>List People<span class="tag">&lt;/a&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The link namespace approach allows parameters to be specified as attributes.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;link:accountDetails</span> <span class="attribute-name">acctNumber</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">8675309</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>Show Account<span class="tag">&lt;/link:accountDetails&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>That would result in:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;a</span> <span class="attribute-name">href</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">/details/8675309</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>Show Account<span class="tag">&lt;/a&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;link:accountDetails</span> <span class="attribute-name">attrs</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">[class: 'fancy']</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">acctNumber</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">8675309</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
Show Account
<span class="tag">&lt;/link:accountDetails&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>That would result in:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;a</span> <span class="attribute-name">href</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">/details/8675309</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">class</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">fancy</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>Show Account<span class="tag">&lt;/a&gt;</span></code></pre>
</div>
</div>
<h2 id="customizingUrlFormat">8.3.12 Customizing URL Formats</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/urlmappings/customizingUrlFormat.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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/application.groovy</code>.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/application.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails.web.url.converter = <span class="string"><span class="delimiter">'</span><span class="content">hyphenated</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Arbitrary strategies may be plugged in by providing a class which implements the <a href="https://grails.apache.org/docs/3.3.7/api/grails/web/UrlConverter.html">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>
</div>
<div class="listingblock">
<div class="title">src/main/groovy/com/myapplication/MyUrlConverterImpl.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.myapplication
<span class="type">class</span> <span class="class">MyUrlConverterImpl</span> <span class="directive">implements</span> grails.web.UrlConverter {
<span class="predefined-type">String</span> toUrlElement(<span class="predefined-type">String</span> propertyOrClassName) {
<span class="comment">// return some representation of a property or class name that should be used in URLs...</span>
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/spring/resources.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">beans = {
<span class="string"><span class="delimiter">&quot;</span><span class="inline"><span class="inline-delimiter">${</span>grails.web.UrlConverter.BEAN_NAME<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>(com.myapplication.MyUrlConverterImpl)
}</code></pre>
</div>
</div>
<h2 id="namespacedControllers">8.3.13 Namespaced Controllers</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/urlmappings/namespacedControllers.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>If an application defines multiple controllers with the same name
in different packages, the controllers must be defined in a
namespace. The way to define a namespace for a controller is to
define a static property named <code>namespace</code> in the controller and
assign a String to the property that represents the namespace.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/com/app/reporting/AdminController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.app.reporting
<span class="type">class</span> <span class="class">AdminController</span> {
<span class="directive">static</span> namespace = <span class="string"><span class="delimiter">'</span><span class="content">reports</span><span class="delimiter">'</span></span>
<span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/com/app/security/AdminController.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.app.security
<span class="type">class</span> <span class="class">AdminController</span> {
<span class="directive">static</span> namespace = <span class="string"><span class="delimiter">'</span><span class="content">users</span><span class="delimiter">'</span></span>
<span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>When defining url mappings which should be associated with a namespaced
controller, the <code>namespace</code> variable needs to be part of the URL mapping.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/controllers/UrlMappings.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">UrlMappings</span> {
<span class="directive">static</span> mappings = {
<span class="string"><span class="delimiter">'</span><span class="content">/userAdmin</span><span class="delimiter">'</span></span> {
controller = <span class="string"><span class="delimiter">'</span><span class="content">admin</span><span class="delimiter">'</span></span>
namespace = <span class="string"><span class="delimiter">'</span><span class="content">users</span><span class="delimiter">'</span></span>
}
<span class="string"><span class="delimiter">'</span><span class="content">/reportAdmin</span><span class="delimiter">'</span></span> {
controller = <span class="string"><span class="delimiter">'</span><span class="content">admin</span><span class="delimiter">'</span></span>
namespace = <span class="string"><span class="delimiter">'</span><span class="content">reports</span><span class="delimiter">'</span></span>
}
<span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>namespace</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>controller</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>action</span><span class="content">?</span><span class="delimiter">&quot;</span></span>()
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Reverse URL mappings also require that the <code>namespace</code> be specified.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">&lt;<span class="key">g</span>:link controller=<span class="string"><span class="delimiter">&quot;</span><span class="content">admin</span><span class="delimiter">&quot;</span></span> namespace=<span class="string"><span class="delimiter">&quot;</span><span class="content">reports</span><span class="delimiter">&quot;</span></span>&gt;Click For Report Admin&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">g:link&gt;</span></span><span class="error">
</span>&lt;<span class="key">g</span>:link controller=<span class="string"><span class="delimiter">&quot;</span><span class="content">admin</span><span class="delimiter">&quot;</span></span> namespace=<span class="string"><span class="delimiter">&quot;</span><span class="content">users</span><span class="delimiter">&quot;</span></span>&gt;Click For User Admin&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">g:link&gt;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>When resolving a URL mapping (forward or reverse) to a namespaced controller,
a mapping will only match if the <code>namespace</code> has been provided. If
the application provides several controllers with the same name in different
packages, at most 1 of them may be defined without a <code>namespace</code> property. If
there are multiple controllers with the same name that do not define a
<code>namespace</code> property, the framework will not know how to distinguish between
them for forward or reverse mapping resolutions.</p>
</div>
<div class="paragraph">
<p>It is allowed for an application to use a plugin which provides a controller
with the same name as a controller provided by the application and for neither
of the controllers to define a <code>namespace</code> property as long as the
controllers are in separate packages. For example, an application
may include a controller named <code>com.accounting.ReportingController</code>
and the application may use a plugin which provides a controller
named <code>com.humanresources.ReportingController</code>. The only issue
with that is the URL mapping for the controller provided by the
plugin needs to be explicit in specifying that the mapping applies
to the <code>ReportingController</code> which is provided by the plugin.</p>
</div>
<div class="paragraph">
<p>See the following example.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/accountingReports</span><span class="delimiter">&quot;</span></span> {
controller = <span class="string"><span class="delimiter">&quot;</span><span class="content">reporting</span><span class="delimiter">&quot;</span></span>
}
<span class="string"><span class="delimiter">&quot;</span><span class="content">/humanResourceReports</span><span class="delimiter">&quot;</span></span> {
controller = <span class="string"><span class="delimiter">&quot;</span><span class="content">reporting</span><span class="delimiter">&quot;</span></span>
plugin = <span class="string"><span class="delimiter">&quot;</span><span class="content">humanResources</span><span class="delimiter">&quot;</span></span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>With that mapping in place, a request to <code>/accountingReports</code> will
be handled by the <code>ReportingController</code> which is defined in the
application. A request to <code>/humanResourceReports</code> will be handled
by the <code>ReportingController</code> which is provided by the <code>humanResources</code>
plugin.</p>
</div>
<div class="paragraph">
<p>There could be any number of <code>ReportingController</code> controllers provided
by any number of plugins but no plugin may provide more than one
<code>ReportingController</code> even if they are defined in separate packages.</p>
</div>
<div class="paragraph">
<p>Assigning a value to the <code>plugin</code> variable in the mapping is only
required if there are multiple controllers with the same name
available at runtime provided by the application and/or plugins.
If the <code>humanResources</code> plugin provides a <code>ReportingController</code> and
there is no other <code>ReportingController</code> available at runtime, the
following mapping would work.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> mappings = {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/humanResourceReports</span><span class="delimiter">&quot;</span></span> {
controller = <span class="string"><span class="delimiter">&quot;</span><span class="content">reporting</span><span class="delimiter">&quot;</span></span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>It is best practice to be explicit about the fact that the controller
is being provided by a plugin.</p>
</div>
<h2 id="cors">8.4 CORS</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/cors.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Spring Boot provides CORS support out of the box, but it is difficult to configure in a Grails application due to the way UrlMappings are used instead of annotations that define URLs. Starting with Grails 3.2.1, we have added a way to configure CORS that makes sense in a Grails application.</p>
</div>
<div class="paragraph">
<p>Once enabled, the default setting is "wide open".</p>
</div>
<div class="listingblock">
<div class="title">application.yml</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">grails</span>:
<span class="key">cors</span>:
<span class="key">enabled</span>: <span class="string"><span class="content">true</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>That will produce a mapping to all urls <code>/**</code> with:</p>
</div>
<table class="tableblock frame-all grid-all" style="width: 40%;">
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">allowedOrigins</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>['*']</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">allowedMethods</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>['*']</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">allowedHeaders</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>['*']</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">exposedHeaders</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>null</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">maxAge</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>1800</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">allowCredentials</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">true</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>Some of these settings come directly from Spring Boot and can change in future versions. See <a href="https://docs.spring.io/spring/docs/current/javadoc-api//org/springframework/web/cors/CorsConfiguration.html#applyPermitDefaultValues">Spring CORS Configuration Documentation</a></p>
</div>
<div class="paragraph">
<p>All of those settings can be easily overridden.</p>
</div>
<div class="listingblock">
<div class="title">application.yml</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">grails</span>:
<span class="key">cors</span>:
<span class="key">enabled</span>: <span class="string"><span class="content">true</span></span>
<span class="key">allowedOrigins</span>:
- <span class="string"><span class="content">http://localhost:5000</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>In the example above, the <code>allowedOrigins</code> setting will replace <code>[*]</code>.</p>
</div>
<div class="paragraph">
<p>You can also configure different URLs.</p>
</div>
<div class="listingblock">
<div class="title">application.yml</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">grails</span>:
<span class="key">cors</span>:
<span class="key">enabled</span>: <span class="string"><span class="content">true</span></span>
<span class="key">allowedHeaders</span>:
- <span class="string"><span class="content">Content-Type</span></span>
<span class="key">mappings</span>:
<span class="error">/api/**</span>:
<span class="key">allowedOrigins</span>:
- <span class="string"><span class="content">http://localhost:5000</span></span>
<span class="comment"># Other configurations not specified default to the global config</span></code></pre>
</div>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
Specifying at least one mapping will disable the creation of the global mapping (<code>/**</code>). If you wish to keep that setting, you should specify it along with your other mappings.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The settings above will produce a single mapping of <code>/api/**</code> with the following settings:</p>
</div>
<table class="tableblock frame-all grid-all" style="width: 40%;">
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">allowedOrigins</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>['http://localhost:5000']</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">allowedMethods</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>['*']</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">allowedHeaders</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>['Content-Type']</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">exposedHeaders</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>null</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">maxAge</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>1800</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">allowCredentials</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">true</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>If you don&#8217;t wish to override any of the default settings, but only want to specify URLs, you can do so like this example:</p>
</div>
<div class="listingblock">
<div class="title">application.yml</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">grails</span>:
<span class="key">cors</span>:
<span class="key">enabled</span>: <span class="string"><span class="content">true</span></span>
<span class="key">mappings</span>:
<span class="error">/api/**</span>: <span class="error">inherit</span></code></pre>
</div>
</div>
<a name="7.1.5 Controller Interceptors"><!-- Legacy link --></a>
<h2 id="interceptors">8.5 Interceptors</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/interceptors.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails provides standalone Interceptors using the <a href="../ref/Command%20Line/create-interceptor.html">create-interceptor</a> command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails create-interceptor MyInterceptor</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above command will create an Interceptor in the <code>grails-app/controllers</code> directory with the following default contents:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">MyInterceptor</span> {
<span class="type">boolean</span> before() { <span class="predefined-constant">true</span> }
<span class="type">boolean</span> after() { <span class="predefined-constant">true</span> }
<span class="type">void</span> afterView() {
<span class="comment">// no-op</span>
}
}</code></pre>
</div>
</div>
<div class="sect3">
<h4 id="_interceptors_vs_filters">Interceptors vs Filters</h4>
<div class="paragraph">
<p>In versions of Grails prior to Grails 3.0, Grails supported the notion of filters. These are still supported for backwards compatibility but are considered deprecated.</p>
</div>
<div class="paragraph">
<p>The new interceptors concept in Grails 3.0 is superior in a number of ways, most significantly interceptors can use Groovy&#8217;s <code>CompileStatic</code> annotation to optimize performance (something which is often critical as interceptors can be executed for every request.)</p>
</div>
</div>
<h2 id="definingInterceptors">8.5.1 Defining Interceptors</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/interceptors/definingInterceptors.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>By default interceptors will match the controllers with the same name. For example if you have an interceptor called <code>BookInterceptor</code> then all requests to the actions of the <code>BookController</code> will trigger the interceptor.</p>
</div>
<div class="paragraph">
<p>An <code>Interceptor</code> implements the <a href="https://grails.apache.org/docs/3.3.7/api/grails/artefact/Interceptor.html">Interceptor</a> trait and provides 3 methods that can be used to intercept requests:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">/**
* Executed before a matched action
*
* @return Whether the action should continue and execute
*/</span>
<span class="type">boolean</span> before() { <span class="predefined-constant">true</span> }
<span class="comment">/**
* Executed after the action executes but prior to view rendering
*
* @return True if view rendering should continue, false otherwise
*/</span>
<span class="type">boolean</span> after() { <span class="predefined-constant">true</span> }
<span class="comment">/**
* Executed after view rendering completes
*/</span>
<span class="type">void</span> afterView() {}</code></pre>
</div>
</div>
<div class="paragraph">
<p>As described above the <code>before</code> method is executed prior to an action and can cancel the execution of the action by returning <code>false</code>.</p>
</div>
<div class="paragraph">
<p>The <code>after</code> method is executed after an action executes and can halt view rendering if it returns false. The <code>after</code> method can also modify the view or model using the <code>view</code> and <code>model</code> properties respectively:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">boolean</span> after() {
model.foo = <span class="string"><span class="delimiter">&quot;</span><span class="content">bar</span><span class="delimiter">&quot;</span></span> <span class="comment">// add a new model attribute called 'foo'</span>
view = <span class="string"><span class="delimiter">'</span><span class="content">alternate</span><span class="delimiter">'</span></span> <span class="comment">// render a different view called 'alternate'</span>
<span class="predefined-constant">true</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>afterView</code> method is executed after view rendering completes. If an exception occurs, the exception is available using the <code>throwable</code> property of the <a href="https://grails.apache.org/docs/3.3.7/api/grails/artefact/Interceptor.html">Interceptor</a> trait.</p>
</div>
<h2 id="interceptorMatching">8.5.2 Matching Requests with Inteceptors</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/interceptors/interceptorMatching.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>As mention in the previous section, by default an interceptor will match only requests to the associated controller by convention. However you can configure the interceptor to match any request using the <code>match</code> or <code>matchAll</code> methods defined in the <a href="https://grails.apache.org/docs/3.3.7/api/grails/artefact/Interceptor.html">Interceptor API</a>.</p>
</div>
<div class="paragraph">
<p>The matching methods return a <a href="https://grails.apache.org/docs/3.3.7/api/grails/interceptors/Matcher.html">Matcher</a> instance which can be used to configure how the interceptor matches the request.</p>
</div>
<div class="paragraph">
<p>For example the following interceptor will match all requests except those to the <code>login</code> controller:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">AuthInterceptor</span> {
AuthInterceptor() {
matchAll()
.excludes(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">login</span><span class="delimiter">&quot;</span></span>)
}
<span class="type">boolean</span> before() {
<span class="comment">// perform authentication</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also perform matching using named argument:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">LoggingInterceptor</span> {
LoggingInterceptor() {
match(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>) <span class="comment">// using strings</span>
match(<span class="key">controller</span>: ~<span class="regexp"><span class="delimiter">/</span><span class="content">(author|publisher)</span><span class="delimiter">/</span></span>) <span class="comment">// using regex</span>
}
<span class="type">boolean</span> before() {
...
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can use any number of matchers defined in your interceptor. They will be executed in the order in which they have been defined. For example the above interceptor will match for all of the following:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>when the <code>show</code> action of <code>BookController</code> is called</p>
</li>
<li>
<p>when <code>AuthorController</code> or <code>PublisherController</code> is called</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>All named arguments except for <code>uri</code> accept either a String or a Regex expression. The <code>uri</code> argument supports a String path that is compatible with Spring&#8217;s <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/AntPathMatcher.html">AntPathMatcher</a>. The possible named arguments are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>namespace</code> - The namespace of the controller</p>
</li>
<li>
<p><code>controller</code> - The name of the controller</p>
</li>
<li>
<p><code>action</code> - The name of the action</p>
</li>
<li>
<p><code>method</code> - The HTTP method</p>
</li>
<li>
<p><code>uri</code> - The URI of the request. If this argument is used then all other arguments will be ignored and only this will be used.</p>
</li>
</ul>
</div>
<h2 id="interceptorOrdering">8.5.3 Ordering Interceptor Execution</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/interceptors/interceptorOrdering.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Interceptors can be ordered by defining an <code>order</code> property that defines a priority.</p>
</div>
<div class="paragraph">
<p>For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">AuthInterceptor</span> {
<span class="type">int</span> order = HIGHEST_PRECEDENCE
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The default value of the <code>order</code> property is 0. Interceptor execution order is determined by sorting the <code>order</code> property in an ascending direction and executing the lowest numerically ordered interceptor first.</p>
</div>
<div class="paragraph">
<p>The values <code>HIGHEST_PRECEDENCE</code> and <code>LOWEST_PRECEDENCE</code> can be used to define filters that should should run first or last respectively.</p>
</div>
<div class="paragraph">
<p>Note that if you write an interceptor that is to be used by others it is better increment or decrement the <code>HIGHEST_PRECEDENCE</code> and <code>LOWEST_PRECEDENCE</code> to allow other interceptors to be inserted before or after the interceptor you are authoring:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">int</span> order = HIGHEST_PRECEDENCE + <span class="integer">50</span>
<span class="comment">// or</span>
<span class="type">int</span> order = LOWEST_PRECEDENCE - <span class="integer">50</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>To find out the computed order of interceptors you can add a debug logger to <code>logback.groovy</code> as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">logger <span class="string"><span class="delimiter">'</span><span class="content">grails.artefact.Interceptor</span><span class="delimiter">'</span></span>, DEBUG, [<span class="string"><span class="delimiter">'</span><span class="content">STDOUT</span><span class="delimiter">'</span></span>], <span class="predefined-constant">false</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>You can override any interceptors default order by using bean override configuration in <code>grails-app/conf/application.yml</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="key">beans</span>:
<span class="key">authInterceptor</span>:
<span class="key">order</span>: <span class="integer">50</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Or in <code>grails-app/conf/application.groovy</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">beans {
authInterceptor {
order = <span class="integer">50</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Thus giving you complete control over interceptor execution order.</p>
</div>
<a name="7.8 Content Negotiation"><!-- Legacy link --></a>
<h2 id="contentNegotiation">8.6 Content Negotiation</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/theWebLayer/contentNegotiation.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails has built in support for <a href="http://en.wikipedia.org/wiki/Content_negotiation">Content negotiation</a> using either the HTTP <code>Accept</code> header, an explicit format request parameter or the extension of a mapped URI.</p>
</div>
<div class="sect3">
<h4 id="_configuring_mime_types">Configuring Mime Types</h4>
<div class="paragraph">
<p>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/application.yml</code> using the <code>grails.mime.types</code> setting:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">grails</span>:
<span class="key">mime</span>:
<span class="key">types</span>:
<span class="key">all</span>: <span class="string"><span class="content">'*/*'</span></span>
<span class="key">atom</span>: <span class="string"><span class="content">application/atom+xml</span></span>
<span class="key">css</span>: <span class="string"><span class="content">text/css</span></span>
<span class="key">csv</span>: <span class="string"><span class="content">text/csv</span></span>
<span class="key">form</span>: <span class="string"><span class="content">application/x-www-form-urlencoded</span></span>
<span class="key">html</span>:
- <span class="string"><span class="content">text/html</span></span>
- <span class="string"><span class="content">application/xhtml+xml</span></span>
<span class="key">js</span>: <span class="string"><span class="content">text/javascript</span></span>
<span class="key">json</span>:
- <span class="string"><span class="content">application/json</span></span>
- <span class="string"><span class="content">text/json</span></span>
<span class="key">multipartForm</span>: <span class="string"><span class="content">multipart/form-data</span></span>
<span class="key">rss</span>: <span class="string"><span class="content">application/rss+xml</span></span>
<span class="key">text</span>: <span class="string"><span class="content">text/plain</span></span>
<span class="key">hal</span>:
- <span class="string"><span class="content">application/hal+json</span></span>
- <span class="string"><span class="content">application/hal+xml</span></span>
<span class="key">xml</span>:
- <span class="string"><span class="content">text/xml</span></span>
- <span class="string"><span class="content">application/xml</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The setting can also be done in <code>grails-app/conf/application.groovy</code> as shown below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails.mime.types = [ <span class="comment">// the first one is the default format</span>
<span class="key">all</span>: <span class="string"><span class="delimiter">'</span><span class="content">*/*</span><span class="delimiter">'</span></span>, <span class="comment">// 'all' maps to '*' or the first available format in withFormat</span>
<span class="key">atom</span>: <span class="string"><span class="delimiter">'</span><span class="content">application/atom+xml</span><span class="delimiter">'</span></span>,
<span class="key">css</span>: <span class="string"><span class="delimiter">'</span><span class="content">text/css</span><span class="delimiter">'</span></span>,
<span class="key">csv</span>: <span class="string"><span class="delimiter">'</span><span class="content">text/csv</span><span class="delimiter">'</span></span>,
<span class="key">form</span>: <span class="string"><span class="delimiter">'</span><span class="content">application/x-www-form-urlencoded</span><span class="delimiter">'</span></span>,
<span class="key">html</span>: [<span class="string"><span class="delimiter">'</span><span class="content">text/html</span><span class="delimiter">'</span></span>,<span class="string"><span class="delimiter">'</span><span class="content">application/xhtml+xml</span><span class="delimiter">'</span></span>],
<span class="key">js</span>: <span class="string"><span class="delimiter">'</span><span class="content">text/javascript</span><span class="delimiter">'</span></span>,
<span class="key">json</span>: [<span class="string"><span class="delimiter">'</span><span class="content">application/json</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">text/json</span><span class="delimiter">'</span></span>],
<span class="key">multipartForm</span>: <span class="string"><span class="delimiter">'</span><span class="content">multipart/form-data</span><span class="delimiter">'</span></span>,
<span class="key">rss</span>: <span class="string"><span class="delimiter">'</span><span class="content">application/rss+xml</span><span class="delimiter">'</span></span>,
<span class="key">text</span>: <span class="string"><span class="delimiter">'</span><span class="content">text/plain</span><span class="delimiter">'</span></span>,
<span class="key">hal</span>: [<span class="string"><span class="delimiter">'</span><span class="content">application/hal+json</span><span class="delimiter">'</span></span>,<span class="string"><span class="delimiter">'</span><span class="content">application/hal+xml</span><span class="delimiter">'</span></span>],
<span class="key">xml</span>: [<span class="string"><span class="delimiter">'</span><span class="content">text/xml</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">application/xml</span><span class="delimiter">'</span></span>]
]</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above bit of configuration allows Grails to detect to format of a request containing either the 'text/xml' or 'application/xml' media types as simply 'xml'. You can add your own types by simply adding new entries into the map.
The first one is the default format.</p>
</div>
</div>
<div class="sect3">
<h4 id="_content_negotiation_using_the_format_request_parameter">Content Negotiation using the format Request Parameter</h4>
<div class="paragraph">
<p>Let&#8217;s say a controller action can return a resource in a variety of formats: HTML, XML, and JSON. What format will the client get? The easiest and most reliable way for the client to control this is through a <code>format</code> URL parameter.</p>
</div>
<div class="paragraph">
<p>So if you, as a browser or some other client, want a resource as XML, you can use a URL like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>http://my.domain.org/books?format=xml</code></pre>
</div>
</div>
<div class="paragraph">
<p>The result of this on the server side is a <code>format</code> property on the <code>response</code> object with the value <code>xml</code> .</p>
</div>
<div class="paragraph">
<p>You can also define this parameter in the <a href="theWebLayer.html#urlmappings">URL Mappings</a> definition:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/book/list</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">list</span><span class="delimiter">&quot;</span></span>) {
format = <span class="string"><span class="delimiter">&quot;</span><span class="content">xml</span><span class="delimiter">&quot;</span></span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You could code your controller action to return XML based on this property, but you can also make use of the controller-specific <code>withFormat()</code> method:</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
This example requires the addition of the <code>org.grails.plugins:grails-plugin-converters</code> plugin
</td>
</tr>
</table>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.converters.JSON</span>
<span class="keyword">import</span> <span class="include">grails.converters.XML</span>
<span class="type">class</span> <span class="class">BookController</span> {
<span class="keyword">def</span> <span class="function">list</span>() {
<span class="keyword">def</span> books = <span class="predefined-type">Book</span>.list()
withFormat {
html <span class="key">bookList</span>: books
json { render books <span class="keyword">as</span> JSON }
xml { render books <span class="keyword">as</span> XML }
<span class="string"><span class="delimiter">'</span><span class="content">*</span><span class="delimiter">'</span></span> { render books <span class="keyword">as</span> JSON }
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this example, Grails will only execute the block inside <code>withFormat()</code> that matches the requested content type. So if the preferred format is <code>html</code> then Grails will execute the <code>html()</code> call only. Each 'block' can either be a map model for the corresponding view (as we are doing for 'html' in the above example) or a closure. The closure can contain any standard action code, for example it can return a model or render content directly.</p>
</div>
<div class="paragraph">
<p>When no format matches explicitly, a <code>*</code> (wildcard) block can be used to handle all other formats.</p>
</div>
<div class="paragraph">
<p>There is a special format, "all", that is handled differently from the explicit formats. If "all" is specified (normally this happens through the Accept header - see below), then the first block of <code>withFormat()</code> is executed when there isn&#8217;t a <code>*</code> (wildcard) block available.</p>
</div>
<div class="paragraph">
<p>You should not add an explicit "all" block. In this example, a format of "all" will trigger the <code>html</code> handler (<code>html</code> is the first block and there is no <code>*</code> block).</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">withFormat {
html <span class="key">bookList</span>: books
json { render books <span class="keyword">as</span> JSON }
xml { render books <span class="keyword">as</span> XML }
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
When using <a href="../ref/Controllers/withFormat.html">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.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_using_the_accept_header">Using the Accept header</h4>
<div class="paragraph">
<p>Every incoming HTTP request has a special <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">Accept</a> header that defines what media types (or mime types) a client can "accept". In older browsers this is typically:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>*/*</code></pre>
</div>
</div>
<div class="paragraph">
<p>which simply means anything. However, newer browsers send more interesting values such as this one sent by Firefox:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, \
text/plain;q=0.8, image/png, */*;q=0.5</code></pre>
</div>
</div>
<div class="paragraph">
<p>This particular accept header is unhelpful because it indicates that XML is the preferred response format whereas the user is really expecting HTML. That&#8217;s why Grails ignores the accept header by default for browsers. However, non-browser clients are typically more specific in their requirements and can send accept headers such as</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">application/json</code></pre>
</div>
</div>
<div class="paragraph">
<p>As mentioned the default configuration in Grails is to ignore the accept header for browsers. This is done by the configuration setting <code>grails.mime.disable.accept.header.userAgents</code>, which is configured to detect the major rendering engines and ignore their ACCEPT headers. This allows Grails' content negotiation to continue to work for non-browser clients:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails.mime.disable.accept.header.userAgents = [<span class="string"><span class="delimiter">'</span><span class="content">Gecko</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">WebKit</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">Presto</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">Trident</span><span class="delimiter">'</span></span>]</code></pre>
</div>
</div>
<div class="paragraph">
<p>For example, if it sees the accept header above ('application/json') it will set <code>format</code> to <code>json</code> as you&#8217;d expect. And of course this works with the <code>withFormat()</code> method in just the same way as when the <code>format</code> URL parameter is set (although the URL parameter takes precedence).</p>
</div>
<div class="paragraph">
<p>An accept header of '*/\*' results in a value of <code>all</code> for the <code>format</code> property.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
If the accept header is used but contains no registered content types, Grails will assume a broken browser is making the request and will set the HTML format - note that this is different from how the other content negotiation modes work as those would activate the "all" format!
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_request_format_vs_response_format">Request format vs. Response format</h4>
<div class="paragraph">
<p>As of Grails 2.0, there is a separate notion of the <em>request</em> format and the <em>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>
</div>
<div class="paragraph">
<p>The <a href="../ref/Controllers/withFormat.html">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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">request.withFormat {
xml {
<span class="comment">// read XML</span>
}
json {
<span class="comment">// read JSON</span>
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_content_negotiation_with_uri_extensions">Content Negotiation with URI Extensions</h4>
<div class="paragraph">
<p>Grails also supports content negotiation using URI extensions. For example given the following URI:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>/book/list.xml</code></pre>
</div>
</div>
<div class="paragraph">
<p>This works as a result of the default URL Mapping definition which is:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>controller</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>action</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="content">?(.</span><span class="inline"><span class="inline-delimiter">$</span>format</span><span class="content">)?</span><span class="delimiter">&quot;</span></span>{</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note the inclusion of the <code>format</code> variable in the path. If you do not wish to use content negotiation via the file extension then simply remove this part of the URL mapping:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>controller</span><span class="content">/</span><span class="inline"><span class="inline-delimiter">$</span>action</span><span class="content">?/</span><span class="inline"><span class="inline-delimiter">$</span>id</span><span class="content">?</span><span class="delimiter">&quot;</span></span>{</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_testing_content_negotiation">Testing Content Negotiation</h4>
<div class="paragraph">
<p>To test content negotiation in a unit or integration test (see the section on <a href="testing.html">Testing</a>) you can either manipulate the incoming request headers:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">void</span> testJavascriptOutput() {
<span class="keyword">def</span> controller = <span class="keyword">new</span> TestController()
controller.request.addHeader <span class="string"><span class="delimiter">&quot;</span><span class="content">Accept</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">text/javascript, text/html, application/xml, text/xml, */*</span><span class="delimiter">&quot;</span></span>
controller.testAction()
assertEquals <span class="string"><span class="delimiter">&quot;</span><span class="content">alert('hello')</span><span class="delimiter">&quot;</span></span>, controller.response.contentAsString
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or you can set the format parameter to achieve a similar effect:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">void</span> testJavascriptOutput() {
<span class="keyword">def</span> controller = <span class="keyword">new</span> TestController()
controller.params.format = <span class="string"><span class="delimiter">'</span><span class="content">js</span><span class="delimiter">'</span></span>
controller.testAction()
assertEquals <span class="string"><span class="delimiter">&quot;</span><span class="content">alert('hello')</span><span class="delimiter">&quot;</span></span>, controller.response.contentAsString
}</code></pre>
</div>
</div>
</div>
<h1 id="traits">9 Traits</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/traits.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect2">
<h3 id="_overview">Overview</h3>
<div class="paragraph">
<p>Grails provides a number of traits which provide access to properties and behavior that may be accessed from various Grails artefacts as well as arbitrary Groovy classes which are part of a Grails project. Many of these traits are automatically added to Grails artefact classes (like controllers and taglibs, for example) and are easy to add to other classes.</p>
</div>
</div>
<h2 id="traitsprovided">9.1 Traits Provided by Grails</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/traits/traitsprovided.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails artefacts are automatically augmented with certain traits at compile time.</p>
</div>
<div class="sect3">
<h4 id="_domain_class_traits">Domain Class Traits</h4>
<div class="ulist">
<ul>
<li>
<p><a href="https://grails.apache.org/docs/3.3.7/api/grails/artefact/DomainClass.html">grails.artefact.DomainClass</a></p>
</li>
<li>
<p><a href="https://grails.apache.org/docs/3.3.7/api/grails/web/databinding/WebDataBinding.html">grails.web.databinding.WebDataBinding</a></p>
</li>
<li>
<p><a href="https://grails.apache.org/docs/latest/api//org/grails/datastore/gorm/GormEntity.html">org.grails.datastore.gorm.GormEntity</a></p>
</li>
<li>
<p><a href="https://grails.apache.org/docs/latest/api//org/grails/datastore/gorm/GormValidateable.html">org.grails.datastore.gorm.GormValidateable</a></p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_controller_traits">Controller Traits</h4>
<div class="ulist">
<ul>
<li>
<p><a href="http://gsp.grails.org/latest/api/grails/artefact/gsp/TagLibraryInvoker.html">grails.artefact.gsp.TagLibraryInvoker</a></p>
</li>
<li>
<p><a href="https://grails.apache.org/docs/latest/api/grails/artefact/AsyncController.html">grails.artefact.AsyncController</a></p>
</li>
<li>
<p><a href="https://grails.apache.org/docs/3.3.7/api/grails/artefact/controller/RestResponder.html">grails.artefact.controller.RestResponder</a></p>
</li>
<li>
<p><a href="https://grails.apache.org/docs/3.3.7/api/grails/artefact/Controller.html">grails.artefact.Controller</a></p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_interceptor_trait">Interceptor Trait</h4>
<div class="ulist">
<ul>
<li>
<p><a href="https://grails.apache.org/docs/3.3.7/api/grails/artefact/Interceptor.html">grails.artefact.Interceptor</a></p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_tag_library_trait">Tag Library Trait</h4>
<div class="ulist">
<ul>
<li>
<p><a href="http://gsp.grails.org/latest/api/grails/artefact/TagLibrary.html">grails.artefact.TagLibrary</a></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Below is a list of other traits provided by the framework. The javadocs provide more detail about methods and properties related to each trait.</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top"><strong>Trait</strong></th>
<th class="tableblock halign-left valign-top"><strong>Brief Description</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/3.3.7/api/grails/web/api/WebAttributes.html">grails.web.api.WebAttributes</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Common Web Attributes</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/3.3.7/api/grails/web/api/ServletAttributes.html">grails.web.api.ServletAttributes</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Servlet API Attributes</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/3.3.7/api/grails/web/databinding/DataBinder.html">grails.web.databinding.DataBinder</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Data Binding API</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/3.3.7/api/grails/artefact/controller/support/RequestForwarder.html">grails.artefact.controller.support.RequestForwarder</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Request Forwarding API</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/3.3.7/api/grails/artefact/controller/support/ResponseRedirector.html">grails.artefact.controller.support.ResponseRedirector</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Response Redirecting API</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/3.3.7/api/grails/artefact/controller/support/ResponseRenderer.html">grails.artefact.controller.support.ResponseRenderer</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Response Rendering API</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="https://grails.apache.org/docs/3.3.7/api/grails/validation/Validateable.html">grails.validation.Validateable</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Validation API</p></td>
</tr>
</tbody>
</table>
</div>
<h2 id="example">9.1.1 WebAttributes Trait Example</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/traits/traitsprovided/example.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p><a href="https://grails.apache.org/docs/3.3.7/api/grails/web/api/WebAttributes.html">WebAttributes</a> is one of the traits provided by the framework. Any Groovy class may implement this trait to inherit all of the properties and behaviors provided by the trait.</p>
</div>
<div class="listingblock">
<div class="title">src/main/groovy/demo/Helper.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> demo
<span class="keyword">import</span> <span class="include">grails.web.api.WebAttributes</span>
<span class="type">class</span> <span class="class">Helper</span> <span class="directive">implements</span> WebAttributes {
<span class="predefined-type">List</span>&lt;<span class="predefined-type">String</span>&gt; getControllerNames() {
<span class="comment">// There is no need to pass grailsApplication as an argument</span>
<span class="comment">// or otherwise inject the grailsApplication property. The</span>
<span class="comment">// WebAttributes trait provides access to grailsApplication.</span>
grailsApplication.getArtefacts(<span class="string"><span class="delimiter">'</span><span class="content">Controller</span><span class="delimiter">'</span></span>)*.name
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The traits are compatible with static compilation&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="title">src/main/groovy/demo/Helper.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> demo
<span class="keyword">import</span> <span class="include">grails.web.api.WebAttributes</span>
<span class="keyword">import</span> <span class="include">groovy.transform.CompileStatic</span>
<span class="annotation">@CompileStatic</span>
<span class="type">class</span> <span class="class">Helper</span> <span class="directive">implements</span> WebAttributes {
<span class="predefined-type">List</span>&lt;<span class="predefined-type">String</span>&gt; getControllerNames() {
<span class="comment">// There is no need to pass grailsApplication as an argument</span>
<span class="comment">// or otherwise inject the grailsApplication property. The</span>
<span class="comment">// WebAttributes trait provides access to grailsApplication.</span>
grailsApplication.getArtefacts(<span class="string"><span class="delimiter">'</span><span class="content">Controller</span><span class="delimiter">'</span></span>)*.name
}
}</code></pre>
</div>
</div>
<a name="8.1 REST"><!-- Legacy link --></a>
<h1 id="REST">10 REST</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>Each HTTP method maps to an action type. For example GET for retrieving data, POST for creating data, PUT for updating and so on.</p>
</div>
<div class="paragraph">
<p>Grails includes flexible features that make it easy to create RESTful APIs. Creating a RESTful resource can be as simple as one line of code, as demonstrated in the next section.</p>
</div>
<h2 id="domainResources">10.1 Domain classes as REST resources</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/domainResources.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>The easiest way to create a RESTful API in Grails is to expose a domain class as a REST resource. This can be done by adding the <code>grails.rest.Resource</code> transformation to any domain class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.rest.*</span>
<span class="annotation">@Resource</span>(uri=<span class="string"><span class="delimiter">'</span><span class="content">/books</span><span class="delimiter">'</span></span>)
<span class="type">class</span> <span class="class">Book</span> {
<span class="predefined-type">String</span> title
<span class="directive">static</span> constraints = {
title <span class="key">blank</span>:<span class="predefined-constant">false</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Simply by adding the <code>Resource</code> transformation and specifying a URI, your domain class will automatically be available as a REST resource in either XML or JSON formats. The transformation will automatically register the necessary <a href="theWebLayer.html#restfulMappings">RESTful URL mapping</a> and create a controller called <code>BookController</code>.</p>
</div>
<div class="paragraph">
<p>You can try it out by adding some test data to <code>BootStrap.groovy</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> init = { servletContext -&gt;
<span class="keyword">new</span> <span class="predefined-type">Book</span>(<span class="key">title</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">The Stand</span><span class="delimiter">&quot;</span></span>).save()
<span class="keyword">new</span> <span class="predefined-type">Book</span>(<span class="key">title</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">The Shining</span><span class="delimiter">&quot;</span></span>).save()
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>And then hitting the URL <a href="http://localhost:8080/books/1" class="bare">http://localhost:8080/books/1</a>, which will render the response like:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="preprocessor">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span>
<span class="tag">&lt;book</span> <span class="attribute-name">id</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">1</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
<span class="tag">&lt;title&gt;</span>The Stand<span class="tag">&lt;/title&gt;</span>
<span class="tag">&lt;/book&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>If you change the URL to <a href="http://localhost:8080/books/1.json" class="bare">http://localhost:8080/books/1.json</a> you will get a JSON response such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="json">{<span class="key"><span class="delimiter">&quot;</span><span class="content">id</span><span class="delimiter">&quot;</span></span>:<span class="integer">1</span>,<span class="key"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">The Stand</span><span class="delimiter">&quot;</span></span>}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you wish to change the default to return JSON instead of XML, you can do this by setting the <code>formats</code> attribute of the <code>Resource</code> transformation:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.rest.*</span>
<span class="annotation">@Resource</span>(uri=<span class="string"><span class="delimiter">'</span><span class="content">/books</span><span class="delimiter">'</span></span>, formats=[<span class="string"><span class="delimiter">'</span><span class="content">json</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">xml</span><span class="delimiter">'</span></span>])
<span class="type">class</span> <span class="class">Book</span> {
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>With the above example JSON will be prioritized. The list that is passed should contain the names of the formats that the resource should expose. The names of formats are defined in the <code>grails.mime.types</code> setting of <code>application.groovy</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails.mime.types = [
...
json: [<span class="string"><span class="delimiter">'</span><span class="content">application/json</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">text/json</span><span class="delimiter">'</span></span>],
...
xml: [<span class="string"><span class="delimiter">'</span><span class="content">text/xml</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">application/xml</span><span class="delimiter">'</span></span>]
]</code></pre>
</div>
</div>
<div class="paragraph">
<p>See the section on <a href="theWebLayer.html#contentNegotiation">Configuring Mime Types</a> in the user guide for more information.</p>
</div>
<div class="paragraph">
<p>Instead of using the file extension in the URI, you can also obtain a JSON response using the ACCEPT header. Here&#8217;s an example using the Unix <code>curl</code> tool:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ curl -i -H &quot;Accept: application/json&quot; localhost:8080/books/1
{&quot;id&quot;:1,&quot;title&quot;:&quot;The Stand&quot;}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This works thanks to Grails' <a href="theWebLayer.html#contentNegotiation">Content Negotiation</a> features.</p>
</div>
<div class="paragraph">
<p>You can create a new resource by issuing a <code>POST</code> request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ curl -i -X POST -H &quot;Content-Type: application/json&quot; -d '{&quot;title&quot;:&quot;Along Came A Spider&quot;}' localhost:8080/books
HTTP/1.1 201 Created
Server: Apache-Coyote/1.1
...</code></pre>
</div>
</div>
<div class="paragraph">
<p>Updating can be done with a <code>PUT</code> request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ curl -i -X PUT -H &quot;Content-Type: application/json&quot; -d '{&quot;title&quot;:&quot;Along Came A Spider&quot;}' localhost:8080/books/1
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
...</code></pre>
</div>
</div>
<div class="paragraph">
<p>Finally a resource can be deleted with <code>DELETE</code> request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ curl -i -X DELETE localhost:8080/books/1
HTTP/1.1 204 No Content
Server: Apache-Coyote/1.1
...</code></pre>
</div>
</div>
<div class="paragraph">
<p>As you can see, the <code>Resource</code> transformation enables all of the HTTP method verbs on the resource. You can enable only read-only capabilities by setting the <code>readOnly</code> attribute to true:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.rest.*</span>
<span class="annotation">@Resource</span>(uri=<span class="string"><span class="delimiter">'</span><span class="content">/books</span><span class="delimiter">'</span></span>, readOnly=<span class="predefined-constant">true</span>)
<span class="type">class</span> <span class="class">Book</span> {
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this case <code>POST</code>, <code>PUT</code> and <code>DELETE</code> requests will be forbidden.</p>
</div>
<h2 id="urlMappings">10.2 Mapping to REST resources</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/urlMappings.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>If you prefer to keep the declaration of the URL mapping in your <code>UrlMappings.groovy</code> file then simply removing the <code>uri</code> attribute of the <code>Resource</code> transformation and adding the following line to <code>UrlMappings.groovy</code> will suffice:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Extending your API to include more end points then becomes trivial:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>) {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/publisher</span><span class="delimiter">&quot;</span></span>(<span class="key">controller</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">publisher</span><span class="delimiter">&quot;</span></span>, <span class="key">method</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">GET</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above example will expose the URI <code>/books/1/publisher</code>.</p>
</div>
<div class="paragraph">
<p>A more detailed explanation on <a href="theWebLayer.html#restfulMappings">creating RESTful URL mappings</a> can be found in the <a href="theWebLayer.html#urlmappings">URL Mappings section</a> of the user guide.</p>
</div>
<h2 id="linkingToResources">10.3 Linking to REST resources from GSP pages</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/linkingToResources.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>The <code>link</code> tag offers an easy way to link to any domain class resource:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:link</span> <span class="attribute-name">resource</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${book}</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>My Link<span class="tag">&lt;/g:link&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>However, currently you cannot use g:link to link to the DELETE action and most browsers do not support sending the DELETE method directly.</p>
</div>
<div class="paragraph">
<p>The best way to accomplish this is to use a form submit:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;form</span> <span class="attribute-name">action</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">/book/2</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">method</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">post</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
<span class="tag">&lt;input</span> <span class="attribute-name">type</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">hidden</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">_method</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">DELETE</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span>
<span class="tag">&lt;/form&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Grails supports overriding the request method via the hidden <code>_method</code> parameter. This is for browser compatibility purposes. This is useful when using restful resource mappings to create powerful web interfaces.
To make a link fire this type of event, perhaps capture all click events for links with a <code>data-method</code> attribute and issue a form submit via JavaScript.</p>
</div>
<h2 id="versioningResources">10.4 Versioning REST resources</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/versioningResources.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>A common requirement with a REST API is to expose different versions at the same time. There are a few ways this can be achieved in Grails.</p>
</div>
<div class="sect3">
<h4 id="_versioning_using_the_uri">Versioning using the URI</h4>
<div class="paragraph">
<p>A common approach is to use the URI to version APIs (although this approach is discouraged in favour of Hypermedia). For example, you can define the following URL mappings:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/books/v1</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">namespace</span>:<span class="string"><span class="delimiter">'</span><span class="content">v1</span><span class="delimiter">'</span></span>)
<span class="string"><span class="delimiter">&quot;</span><span class="content">/books/v2</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">namespace</span>:<span class="string"><span class="delimiter">'</span><span class="content">v2</span><span class="delimiter">'</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>That will match the following controllers:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> myapp.v1
<span class="type">class</span> <span class="class">BookController</span> {
<span class="directive">static</span> namespace = <span class="string"><span class="delimiter">'</span><span class="content">v1</span><span class="delimiter">'</span></span>
}
<span class="keyword">package</span> myapp.v2
<span class="type">class</span> <span class="class">BookController</span> {
<span class="directive">static</span> namespace = <span class="string"><span class="delimiter">'</span><span class="content">v2</span><span class="delimiter">'</span></span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This approach has the disadvantage of requiring two different URI namespaces for your API.</p>
</div>
</div>
<div class="sect3">
<h4 id="_versioning_with_the_accept_version_header">Versioning with the Accept-Version header</h4>
<div class="paragraph">
<p>As an alternative Grails supports the passing of an <code>Accept-Version</code> header from clients. For example you can define the following URL mappings:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">version</span>:<span class="string"><span class="delimiter">'</span><span class="content">1.0</span><span class="delimiter">'</span></span>, <span class="key">resources</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">namespace</span>:<span class="string"><span class="delimiter">'</span><span class="content">v1</span><span class="delimiter">'</span></span>)
<span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">version</span>:<span class="string"><span class="delimiter">'</span><span class="content">2.0</span><span class="delimiter">'</span></span>, <span class="key">resources</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>, <span class="key">namespace</span>:<span class="string"><span class="delimiter">'</span><span class="content">v2</span><span class="delimiter">'</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then in the client simply pass which version you need using the <code>Accept-Version</code> header:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ curl -i -H &quot;Accept-Version: 1.0&quot; -X GET http://localhost:8080/books</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_versioning_using_hypermedia_mime_types">Versioning using Hypermedia / Mime Types</h4>
<div class="paragraph">
<p>Another approach to versioning is to use Mime Type definitions to declare the version of your custom media types (see the section on "Hypermedia as the Engine of Application State" for more information about Hypermedia concepts). For example, in <code>application.groovy</code> you can declare a custom Mime Type for your resource that includes a version parameter (the 'v' parameter):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails.mime.types = [
<span class="key">all</span>: <span class="string"><span class="delimiter">'</span><span class="content">*/*</span><span class="delimiter">'</span></span>,
<span class="key">book</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">application/vnd.books.org.book+json;v=1.0</span><span class="delimiter">&quot;</span></span>,
<span class="key">bookv2</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">application/vnd.books.org.book+json;v=2.0</span><span class="delimiter">&quot;</span></span>,
...
}</code></pre>
</div>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
It is critical that place your new mime types after the 'all' Mime Type because if the Content Type of the request cannot be established then the first entry in the map is used for the response. If you have your new Mime Type at the top then Grails will always try and send back your new Mime Type if the requested Mime Type cannot be established.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Then override the renderer (see the section on "Customizing Response Rendering" for more information on custom renderers) to send back the custom Mime Type in <code>grails-app/conf/spring/resourses.groovy</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.rest.render.json.*</span>
<span class="keyword">import</span> <span class="include">grails.web.mime.*</span>
beans = {
bookRendererV1(JsonRenderer, myapp.v1.Book, <span class="keyword">new</span> MimeType(<span class="string"><span class="delimiter">&quot;</span><span class="content">application/vnd.books.org.book+json</span><span class="delimiter">&quot;</span></span>, [<span class="key">v</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">1.0</span><span class="delimiter">&quot;</span></span>]))
bookRendererV2(JsonRenderer, myapp.v2.Book, <span class="keyword">new</span> MimeType(<span class="string"><span class="delimiter">&quot;</span><span class="content">application/vnd.books.org.book+json</span><span class="delimiter">&quot;</span></span>, [<span class="key">v</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">2.0</span><span class="delimiter">&quot;</span></span>]))
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then update the list of acceptable response formats in your controller:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> <span class="directive">extends</span> RestfulController {
<span class="directive">static</span> responseFormats = [<span class="string"><span class="delimiter">'</span><span class="content">json</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">xml</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">book</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">bookv2</span><span class="delimiter">'</span></span>]
<span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then using the <code>Accept</code> header you can specify which version you need using the Mime Type:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span> curl -i -H <span class="string"><span class="delimiter">&quot;</span><span class="content">Accept: application/vnd.books.org.book+json;v=1.0</span><span class="delimiter">&quot;</span></span> -X GET <span class="key">http</span>:<span class="comment">//localhost:8080/books</span></code></pre>
</div>
</div>
</div>
<h2 id="restfulControllers">10.5 Implementing REST controllers</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/restfulControllers.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>The <code>Resource</code> transformation is a quick way to get started, but typically you&#8217;ll want to customize the controller logic, the rendering of the response or extend the API to include additional actions.</p>
</div>
<h2 id="extendingRestfulController">10.5.1 Extending the RestfulController super class</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/restfulControllers/extendingRestfulController.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>The easiest way to get started doing so is to create a new controller for your resource that extends the <code>grails.rest.RestfulController</code> super class. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> <span class="directive">extends</span> RestfulController&lt;<span class="predefined-type">Book</span>&gt; {
<span class="directive">static</span> responseFormats = [<span class="string"><span class="delimiter">'</span><span class="content">json</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">xml</span><span class="delimiter">'</span></span>]
BookController() {
<span class="local-variable">super</span>(<span class="predefined-type">Book</span>)
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>To customize any logic you can just override the appropriate action. The following table provides the names of the action names and the URIs they map to:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">HTTP Method</th>
<th class="tableblock halign-left valign-top">URI</th>
<th class="tableblock halign-left valign-top">Controller Action</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">index</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/create</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">create</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">POST</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">save</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${id}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">show</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${id}/edit</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">edit</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">PUT</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${id}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">update</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">DELETE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${id}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">delete</p></td>
</tr>
</tbody>
</table>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The <code>create</code> and <code>edit</code> actions are only needed if the controller exposes an HTML interface.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>As an example, if you have a <a href="theWebLayer.html#restfulMappings">nested resource</a> then you would typically want to query both the parent and the child identifiers. For example, given the following URL mapping:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="string"><span class="delimiter">&quot;</span><span class="content">/authors</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">'</span><span class="content">author</span><span class="delimiter">'</span></span>) {
<span class="string"><span class="delimiter">&quot;</span><span class="content">/books</span><span class="delimiter">&quot;</span></span>(<span class="key">resources</span>:<span class="string"><span class="delimiter">'</span><span class="content">book</span><span class="delimiter">'</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You could implement the nested controller as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> <span class="directive">extends</span> RestfulController {
<span class="directive">static</span> responseFormats = [<span class="string"><span class="delimiter">'</span><span class="content">json</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">xml</span><span class="delimiter">'</span></span>]
BookController() {
<span class="local-variable">super</span>(<span class="predefined-type">Book</span>)
}
<span class="annotation">@Override</span>
<span class="directive">protected</span> <span class="predefined-type">Book</span> queryForResource(<span class="predefined-type">Serializable</span> id) {
<span class="predefined-type">Book</span>.where {
id == id &amp;&amp; author.id == params.authorId
}.find()
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The example above subclasses <code>RestfulController</code> and overrides the protected <code>queryForResource</code> method to customize the query for the resource to take into account the parent resource.</p>
</div>
<div class="sect3">
<h4 id="_customizing_data_binding_in_a_restfulcontroller_subclass">Customizing Data Binding In A RestfulController Subclass</h4>
<div class="paragraph">
<p>The RestfulController class contains code which does data binding for actions like <code>save</code> and <code>update</code>. The class defines a <code>getObjectToBind()</code> method which returns a value which will be used as the source for data binding. For example, the update action does something like this&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">RestfulController</span>&lt;T&gt; {
<span class="keyword">def</span> <span class="function">update</span>() {
T instance = <span class="comment">// retrieve instance from the database...</span>
instance.properties = getObjectToBind()
<span class="comment">// ...</span>
}
<span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>By default the <code>getObjectToBind()</code> method returns the <a href="../ref/Controllers/request.html">request</a> object. When the <code>request</code> object is used as the binding source, if the request has a body then the body will be parsed and its contents will be used to do the data binding, otherwise the request parameters will be used to do the data binding. Subclasses of RestfulController may override the <code>getObjectToBind()</code> method and return anything that is a valid binding source, including a <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Map.html">Map</a> or a <a href="https://grails.apache.org/docs/3.3.7/api/grails/databinding/DataBindingSource.html">DataBindingSource</a>. For most use cases binding the request is appropriate but the <code>getObjectToBind()</code> method allows for changing that behavior where desired.</p>
</div>
</div>
<div class="sect3">
<h4 id="_using_custom_subclass_of_restfulcontroller_with_resource_annotation">Using custom subclass of RestfulController with Resource annotation</h4>
<div class="paragraph">
<p>You can also customize the behaviour of the controller that backs the Resource annotation.</p>
</div>
<div class="paragraph">
<p>The class must provide a constructor that takes a domain class as it&#8217;s argument. The second constructor is required for supporting Resource annotation with readOnly=true.</p>
</div>
<div class="paragraph">
<p>This is a template that can be used for subclassed RestfulController classes used in Resource annotations:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">SubclassRestfulController</span>&lt;T&gt; <span class="directive">extends</span> RestfulController&lt;T&gt; {
SubclassRestfulController(<span class="predefined-type">Class</span>&lt;T&gt; domainClass) {
<span class="local-variable">this</span>(domainClass, <span class="predefined-constant">false</span>)
}
SubclassRestfulController(<span class="predefined-type">Class</span>&lt;T&gt; domainClass, <span class="type">boolean</span> readOnly) {
<span class="local-variable">super</span>(domainClass, readOnly)
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can specify the super class of the controller that backs the Resource annotation with the <code>superClass</code> attribute.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.rest.*</span>
<span class="annotation">@Resource</span>(uri=<span class="string"><span class="delimiter">'</span><span class="content">/books</span><span class="delimiter">'</span></span>, superClass=SubclassRestfulController)
<span class="type">class</span> <span class="class">Book</span> {
<span class="predefined-type">String</span> title
<span class="directive">static</span> constraints = {
title <span class="key">blank</span>:<span class="predefined-constant">false</span>
}
}</code></pre>
</div>
</div>
</div>
<h2 id="restControllersStepByStep">10.5.2 Implementing REST Controllers Step by Step</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/restfulControllers/restControllersStepByStep.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>If you don&#8217;t want to take advantage of the features provided by the <code>RestfulController</code> super class, then you can implement each HTTP verb yourself manually. The first step is to create a controller:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span> grails create-controller book</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then add some useful imports and enable readOnly by default:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.gorm.transactions.*</span>
<span class="keyword">import</span> <span class="include">static</span> <span class="include">org.springframework.http.HttpStatus.*</span>
<span class="keyword">import</span> <span class="include">static</span> <span class="include">org.springframework.http.HttpMethod.*</span>
<span class="annotation">@Transactional</span>(readOnly = <span class="predefined-constant">true</span>)
<span class="type">class</span> <span class="class">BookController</span> {
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Recall that each HTTP verb matches a particular Grails action according to the following conventions:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">HTTP Method</th>
<th class="tableblock halign-left valign-top">URI</th>
<th class="tableblock halign-left valign-top">Controller Action</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">index</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${id}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">show</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/create</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">create</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${id}/edit</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">edit</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">POST</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">save</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">PUT</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${id}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">update</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">DELETE</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/books/${id}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">delete</p></td>
</tr>
</tbody>
</table>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The <code>create</code> and <code>edit</code> actions are already required if you plan to implement an HTML interface for the REST resource. They are there in order to render appropriate HTML forms to create and edit a resource. They can be discarded if that is not a requirement.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The key to implementing REST actions is the <a href="../ref/Controllers/respond.html">respond</a> method introduced in Grails 2.3. The <code>respond</code> method tries to produce the most appropriate response for the requested content type (JSON, XML, HTML etc.)</p>
</div>
<div class="sect3">
<h4 id="_implementing_the_index_action">Implementing the 'index' action</h4>
<div class="paragraph">
<p>For example, to implement the <code>index</code> action, simply call the <code>respond</code> method passing the list of objects to respond with:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">index</span>(<span class="predefined-type">Integer</span> max) {
params.max = <span class="predefined-type">Math</span>.min(max ?: <span class="integer">10</span>, <span class="integer">100</span>)
respond <span class="predefined-type">Book</span>.list(params), <span class="key">model</span>:[<span class="key">bookCount</span>: <span class="predefined-type">Book</span>.count()]
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that in the above example we also use the <code>model</code> argument of the <code>respond</code> method to supply the total count. This is only required if you plan to support pagination via some user interface.</p>
</div>
<div class="paragraph">
<p>The <code>respond</code> method will, using <a href="theWebLayer.html#contentNegotiation">Content Negotiation</a>, attempt to reply with the most appropriate response given the content type requested by the client (via the ACCEPT header or file extension).</p>
</div>
<div class="paragraph">
<p>If the content type is established to be HTML then a model will be produced such that the action above would be the equivalent of writing:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">index</span>(<span class="predefined-type">Integer</span> max) {
params.max = <span class="predefined-type">Math</span>.min(max ?: <span class="integer">10</span>, <span class="integer">100</span>)
[<span class="key">bookList</span>: <span class="predefined-type">Book</span>.list(params), <span class="key">bookCount</span>: <span class="predefined-type">Book</span>.count()]
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>By providing an <code>index.gsp</code> file you can render an appropriate view for the given model. If the content type is something other than HTML then the <code>respond</code> method will attempt to lookup an appropriate <code>grails.rest.render.Renderer</code> instance that is capable of rendering the passed object. This is done by inspecting the <code>grails.rest.render.RendererRegistry</code>.</p>
</div>
<div class="paragraph">
<p>By default there are already renderers configured for JSON and XML, to find out how to register a custom renderer see the section on "Customizing Response Rendering".</p>
</div>
</div>
<div class="sect3">
<h4 id="_implementing_the_show_action">Implementing the 'show' action</h4>
<div class="paragraph">
<p>The <code>show</code> action, which is used to display and individual resource by id, can be implemented in one line of Groovy code (excluding the method signature):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">show</span>(<span class="predefined-type">Book</span> book) {
respond book
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>By specifying the domain instance as a parameter to the action Grails will automatically attempt to lookup the domain instance using the <code>id</code> parameter of the request. If the domain instance doesn&#8217;t exist, then <code>null</code> will be passed into the action. The <code>respond</code> method will return a 404 error if null is passed otherwise once again it will attempt to render an appropriate response. If the format is HTML then an appropriate model will produced. The following action is functionally equivalent to the above action:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">show</span>(<span class="predefined-type">Book</span> book) {
<span class="keyword">if</span>(book == <span class="predefined-constant">null</span>) {
render <span class="key">status</span>:<span class="integer">404</span>
}
<span class="keyword">else</span> {
<span class="keyword">return</span> [<span class="key">book</span>: book]
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_implementing_the_save_action">Implementing the 'save' action</h4>
<div class="paragraph">
<p>The <code>save</code> action creates new resource representations. To start off, simply define an action that accepts a resource as the first argument and mark it as <code>Transactional</code> with the <code>grails.gorm.transactions.Transactional</code> transform:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="annotation">@Transactional</span>
<span class="keyword">def</span> <span class="function">save</span>(<span class="predefined-type">Book</span> book) {
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then the first thing to do is check whether the resource has any <a href="validation.html">validation errors</a> and if so respond with the errors:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">if</span>(book.hasErrors()) {
respond book.errors, <span class="key">view</span>:<span class="string"><span class="delimiter">'</span><span class="content">create</span><span class="delimiter">'</span></span>
}
<span class="keyword">else</span> {
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the case of HTML the 'create' view will be rendered again so the user can correct the invalid input. In the case of other formats (JSON, XML etc.), the errors object itself will be rendered in the appropriate format and a status code of 422 (UNPROCESSABLE_ENTITY) returned.</p>
</div>
<div class="paragraph">
<p>If there are no errors then the resource can be saved and an appropriate response sent:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">book.save <span class="key">flush</span>:<span class="predefined-constant">true</span>
withFormat {
html {
flash.message = message(<span class="key">code</span>: <span class="string"><span class="delimiter">'</span><span class="content">default.created.message</span><span class="delimiter">'</span></span>, <span class="key">args</span>: [message(<span class="key">code</span>: <span class="string"><span class="delimiter">'</span><span class="content">book.label</span><span class="delimiter">'</span></span>, <span class="keyword">default</span>: <span class="string"><span class="delimiter">'</span><span class="content">Book</span><span class="delimiter">'</span></span>), book.id])
redirect book
}
<span class="string"><span class="delimiter">'</span><span class="content">*</span><span class="delimiter">'</span></span> { render <span class="key">status</span>: CREATED }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the case of HTML a redirect is issued to the originating resource and for other formats a status code of 201 (CREATED) is returned.</p>
</div>
</div>
<div class="sect3">
<h4 id="_implementing_the_update_action">Implementing the 'update' action</h4>
<div class="paragraph">
<p>The <code>update</code> action updates an existing resource representation and is largely similar to the <code>save</code> action. First define the method signature:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="annotation">@Transactional</span>
<span class="keyword">def</span> <span class="function">update</span>(<span class="predefined-type">Book</span> book) {
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If the resource exists then Grails will load the resource, otherwise null is passed. In the case of null, you should return a 404:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">if</span>(book == <span class="predefined-constant">null</span>) {
render <span class="key">status</span>: NOT_FOUND
}
<span class="keyword">else</span> {
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then once again check for errors <a href="validation.html">validation errors</a> and if so respond with the errors:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">if</span>(book.hasErrors()) {
respond book.errors, <span class="key">view</span>:<span class="string"><span class="delimiter">'</span><span class="content">edit</span><span class="delimiter">'</span></span>
}
<span class="keyword">else</span> {
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the case of HTML the 'edit' view will be rendered again so the user can correct the invalid input. In the case of other formats (JSON, XML etc.) the errors object itself will be rendered in the appropriate format and a status code of 422 (UNPROCESSABLE_ENTITY) returned.</p>
</div>
<div class="paragraph">
<p>If there are no errors then the resource can be saved and an appropriate response sent:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">book.save <span class="key">flush</span>:<span class="predefined-constant">true</span>
withFormat {
html {
flash.message = message(<span class="key">code</span>: <span class="string"><span class="delimiter">'</span><span class="content">default.updated.message</span><span class="delimiter">'</span></span>, <span class="key">args</span>: [message(<span class="key">code</span>: <span class="string"><span class="delimiter">'</span><span class="content">book.label</span><span class="delimiter">'</span></span>, <span class="keyword">default</span>: <span class="string"><span class="delimiter">'</span><span class="content">Book</span><span class="delimiter">'</span></span>), book.id])
redirect book
}
<span class="string"><span class="delimiter">'</span><span class="content">*</span><span class="delimiter">'</span></span> { render <span class="key">status</span>: OK }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the case of HTML a redirect is issued to the originating resource and for other formats a status code of 200 (OK) is returned.</p>
</div>
</div>
<div class="sect3">
<h4 id="_implementing_the_delete_action">Implementing the 'delete' action</h4>
<div class="paragraph">
<p>The <code>delete</code> action deletes an existing resource. The implementation is largely similar to the <code>update</code> action, except the <code>delete()</code> method is called instead:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">book.delete <span class="key">flush</span>:<span class="predefined-constant">true</span>
withFormat {
html {
flash.message = message(<span class="key">code</span>: <span class="string"><span class="delimiter">'</span><span class="content">default.deleted.message</span><span class="delimiter">'</span></span>, <span class="key">args</span>: [message(<span class="key">code</span>: <span class="string"><span class="delimiter">'</span><span class="content">Book.label</span><span class="delimiter">'</span></span>, <span class="keyword">default</span>: <span class="string"><span class="delimiter">'</span><span class="content">Book</span><span class="delimiter">'</span></span>), book.id])
redirect <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">index</span><span class="delimiter">&quot;</span></span>, <span class="key">method</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">GET</span><span class="delimiter">&quot;</span></span>
}
<span class="string"><span class="delimiter">'</span><span class="content">*</span><span class="delimiter">'</span></span>{ render <span class="key">status</span>: NO_CONTENT }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Notice that for an HTML response a redirect is issued back to the <code>index</code> action, whilst for other content types a response code 204 (NO_CONTENT) is returned.</p>
</div>
</div>
<h2 id="generatingRestControllers">10.5.3 Generating a REST controller using scaffolding</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/restfulControllers/generatingRestControllers.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>To see some of these concepts in action and help you get going, the <a href="http://grails.org/plugins.html#plugin/scaffolding">Scaffolding plugin</a>, version 2.0 and above, can generate a REST ready controller for you, simply run the command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails generate-controller &lt;&lt;Domain Class Name&gt;&gt;</code></pre>
</div>
</div>
<h2 id="restProfile">10.6 The REST Profile</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/restProfile.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Since Grails 3.1, Grails supports a tailored profile for creating REST applications that provides a more focused set of dependencies and commands.</p>
</div>
<div class="paragraph">
<p>To get started with the REST profile, create an application specifying <code>rest-api</code> as the name of the profile:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails create-app my-api --profile rest-api</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will create a new REST application that provides the following features:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Default set of commands for creating and generating REST endpoints</p>
</li>
<li>
<p>Defaults to using JSON views for rendering responses (see the next section)</p>
</li>
<li>
<p>Fewer plugins than the default Grails plugin (no GSP, no Asset Pipeline, nothing HTML related)</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>You will notice for example in the <code>grails-app/views</code> directory that there are <code>*.gson</code> files for rendering the default index page and as well as any 404 and 500 errors.</p>
</div>
<div class="paragraph">
<p>If you issue the following set of commands:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails create-domain-class my.api.Book
$ grails generate-all my.api.Book</code></pre>
</div>
</div>
<div class="paragraph">
<p>Instead of CRUD HTML interface a REST endpoint is generated that produces JSON responses. In addition, the generated functional and unit tests by default test the REST endpoint.</p>
</div>
<h2 id="angularJsProfile">10.7 The AngularJS Profile</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/angularJsProfile.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Since Grails 3.1, Grails supports a profile for creating applications with AngularJS that provides a more focused set of dependencies and commands. The angular profile inherits from the REST profile and therefore has all of the commands and properties that the REST profile has.</p>
</div>
<div class="paragraph">
<p>To get started with the AngularJS profile, create an application specifying <code>angularjs</code> as the name of the profile:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails create-app my-api --profile angularjs</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will create a new Grails application that provides the following features:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Default set of commands for creating AngularJS artefacts</p>
</li>
<li>
<p>Gradle plugin to manage client side dependencies</p>
</li>
<li>
<p>Gradle plugin to execute client side unit tests</p>
</li>
<li>
<p>Asset Pipeline plugins to ease development</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>By default the AngularJS profile includes GSP support in order to render the index page. This is necessary because the profile is designed around asset pipeline.</p>
</div>
<div class="paragraph">
<p>The new commands are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>create-ng-component</code></p>
</li>
<li>
<p><code>create-ng-controller</code></p>
</li>
<li>
<p><code>create-ng-directive</code></p>
</li>
<li>
<p><code>create-ng-domain</code></p>
</li>
<li>
<p><code>create-ng-module</code></p>
</li>
<li>
<p><code>create-ng-service</code></p>
</li>
</ul>
</div>
<div class="sect3">
<h4 id="_project_structure">Project structure</h4>
<div class="paragraph">
<p>The AngularJS profile is designed around a specific project structure. The <code>create-ng</code> commands will automatically create modules where they do not exist.</p>
</div>
<div class="paragraph">
<p>Example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails create-ng-controller foo</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will produce a <code>fooController.js</code> file in <code>grails-app/assets/javascripts/${default package name}/controllers</code>.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
By default the angularjs profile will create files in the <code>javascripts</code> directory. You can change that behavior in your configuration with the key <code>grails.codegen.angular.assetDir</code>.
</td>
</tr>
</table>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails create-ng-domain foo.bar</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will produce a <code>Bar.js</code> file in <code>grails-app/assets/javascripts/foo/domains</code>. It will also create the "foo" module if it does not already exist.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails create-ng-module foo.bar</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will produce a <code>foo.bar.js</code> file in <code>grails-app/assets/javascripts/foo/bar</code>. Note the naming convention for modules is different than other artefacts.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails create-ng-service foo.bar --type constant</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will produce a <code>bar.js</code> file in <code>grails-app/assets/javascripts/foo/services</code>. It will also create the "foo" module if it does not already exist. The <code>create-ng-service</code> command accepts a flag <code>-type</code>. The types that can be used are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>service</p>
</li>
<li>
<p>factory <em>default</em></p>
</li>
<li>
<p>value</p>
</li>
<li>
<p>provider</p>
</li>
<li>
<p>constant</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Along with the artefacts themselves, the profile will also produce a skeleton unit test file under <code>src/test/javascripts</code> for each create command.</p>
</div>
</div>
<div class="sect3">
<h4 id="_client_side_dependencies">Client side dependencies</h4>
<div class="paragraph">
<p>The <a href="https://github.com/craigburke/bower-installer-gradle">Gradle Bower Plugin</a> is used to manage dependencies with bower. Visit the plugin documentation to learn how to use the plugin.</p>
</div>
</div>
<div class="sect3">
<h4 id="_unit_testing">Unit Testing</h4>
<div class="paragraph">
<p>The <a href="https://github.com/craigburke/karma-gradle">Gradle Karma Plugin</a> is used to execute client side unit tests. All generated tests are written with Jasmine. Visit the plugin documentation to learn how to use the plugin.</p>
</div>
</div>
<div class="sect3">
<h4 id="_asset_pipeline">Asset Pipeline</h4>
<div class="paragraph">
<p>The AngularJS profile includes several asset pipeline plugins to make development easier.</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://github.com/craigburke/js-closure-wrap-asset-pipeline">JS Closure Wrap Asset Pipeline</a> will wrap your Angular code in immediately invoked function expressions.</p>
</li>
<li>
<p><a href="https://github.com/craigburke/angular-annotate-asset-pipeline">Annotate Asset Pipeline</a> will annotate your dependencies to be safe for minification.</p>
</li>
<li>
<p><a href="https://github.com/craigburke/angular-template-asset-pipeline">Template Asset Pipeline</a> will put your templates into the <code>$templateCache</code> to prevent http requests to retrieve the templates.</p>
</li>
</ul>
</div>
</div>
<h2 id="angularProfile">10.8 The Angular Profile</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/angularProfile.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Since Grails 3.2.1, Grails supports a profile for creating applications with Angular that provides a more future facing setup.</p>
</div>
<div class="paragraph">
<p>The biggest change in this profile is that the profile creates a multi project gradle build. This is the first profile to have done so. The Angular profile relies on the <a href="https://github.com/angular/angular-cli">Angular CLI</a> to manage the client side application. The server side application is the same as an application created with the <code>rest-api</code> profile.</p>
</div>
<div class="paragraph">
<p>To get started with the Angular profile, create an application specifying <code>angular</code> as the name of the profile:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ grails create-app my-app --profile angular</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will create a <code>my-app</code> directory with the following contents:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>client/
gradle/
gradlew
gradlew.bat
server/
settings.gradle</code></pre>
</div>
</div>
<div class="paragraph">
<p>The entire client application lives in the <code>client</code> folder and the entire server application lives in the <code>server</code> folder.</p>
</div>
<div class="sect3">
<h4 id="_prerequisites">Prerequisites</h4>
<div class="paragraph">
<p>To use this profile, you should have Node, NPM, and the Angular CLI installed. Node should be at least version 5 and NPM should be at least version 3.</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://docs.npmjs.com/getting-started/installing-node">Node &amp;&amp; NPM</a></p>
</li>
<li>
<p><a href="https://github.com/angular/angular-cli#installation">Angular CLI</a></p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_project_structure">Project Structure</h4>
<div class="paragraph">
<p>The Angular profile is designed to be used with the <a href="https://github.com/angular/angular-cli">Angular CLI</a>. The CLI was used to create the client application side of the profile to start with. The CLI provides commands to do most of the things you would want to do with the client application, including creating components or services. Because of that, the profile itself provides no commands to do those same things.</p>
</div>
</div>
<div class="sect3">
<h4 id="_running_the_app">Running The App</h4>
<div class="paragraph">
<p>To execute the server side application only, you can execute the <code>bootRun</code> task in the <code>server</code> project:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">./gradlew server:bootRun</code></pre>
</div>
</div>
<div class="paragraph">
<p>The same can be done for the client application:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">./gradlew client:bootRun</code></pre>
</div>
</div>
<div class="paragraph">
<p>To execute both, you must do so in parallel:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">./gradlew bootRun --parallel</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
It is necessary to do so in parallel because by default Gradle executes tasks synchronously, and neither of the <code>bootRun</code> tasks will "finish".
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_testing">Testing</h4>
<div class="paragraph">
<p>The default client application that comes with the profile provides some tests that can be executed. To execute tests in the application:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">./gradlew test</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>test</code> task will execute unit tests with Karma and Jasmine.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">./gradlew integrationTest</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>integrationTest</code> task will execute e2e tests with Protractor.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
You can execute the <code>test</code> and <code>integrationTest</code> tasks on each of the sub-projects the same as you would <code>bootRun</code>.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_cors">CORS</h4>
<div class="paragraph">
<p>Because the client side and server side will be running on separate ports, CORS configuration is required. By default the profile will configure the server side to allow CORS from all hosts via the following config:</p>
</div>
<div class="listingblock">
<div class="title">server/grails-app/conf/application.yml</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">grails</span>:
<span class="key">cors</span>:
<span class="key">enabled</span>: <span class="string"><span class="content">true</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>See the section on <a href="theWebLayer.html#cors">CORS</a> in the user guide for information on configuring this feature for your needs.</p>
</div>
</div>
<h2 id="jsonViews">10.9 JSON Views</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/jsonViews.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>As mentioned in the previous section the REST profile by default uses JSON views to render JSON responses. These play a similar role to GSP, but instead are optimized for outputing JSON responses instead of HTML.</p>
</div>
<div class="paragraph">
<p>You can continue to separate your application in terms of MVC, with the logic of your application residing in controllers and services, whilst view related matters are handled by JSON views.</p>
</div>
<div class="paragraph">
<p>JSON views also provide the flexibility to easily customize the JSON presented to clients without having to resort to relatively complex marshalling libraries like Jackson or Grails' marshaller API.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Since Grails 3.1, JSON views are considered by the Grails team the best way to present JSON output for the client, the section on writing custom marshallers has been removed from the user guide. If you are looking for information on that topic, see <a href="https://grails.apache.org/docs/3.0.x/guide/webServices.html#objectMarshallers">the Grails 3.0.x guide</a>.
</td>
</tr>
</table>
</div>
<h2 id="jsonViewsSetup">10.9.1 Getting Started</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/jsonViews/jsonViewsSetup.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>If you are using the REST or AngularJS profiles then the JSON views plugin will already be included and you can skip the remainder of this section. Otherwise you will need to modify your <code>build.gradle</code> to include the necessary plugin to activate JSON views:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">compile <span class="string"><span class="delimiter">'</span><span class="content">org.grails.plugins:views-json:1.0.0</span><span class="delimiter">'</span></span> <span class="comment">// or whatever is the latest version</span></code></pre>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
The <a href="https://github.com/grails/grails-views">source code repository for JSON views</a> can be found on Github if you are looking for more documentation and contributions
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>In order to compile JSON views for production deployment you should also activate the Gradle plugin by first modifying the <code>buildscript</code> block:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">buildscript {
...
dependencies {
...
classpath <span class="string"><span class="delimiter">&quot;</span><span class="content">org.grails.plugins:views-gradle:1.0.0</span><span class="delimiter">&quot;</span></span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then apply the <code>org.grails.plugins.views-json</code> Gradle plugin after any Grails core gradle plugins:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">...
apply <span class="key">plugin</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">org.grails.grails-web</span><span class="delimiter">&quot;</span></span>
apply <span class="key">plugin</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">org.grails.plugins.views-json</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>This will add a <code>compileGsonViews</code> task to Gradle, which is invoked prior to creating the production JAR or WAR file.</p>
</div>
<h2 id="jsonViewsCreating">10.9.2 Creating JSON Views</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/jsonViews/jsonViewsCreating.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>JSON views go into the <code>grails-app/views</code> directory and end with the <code>.gson</code> suffix. They are regular Groovy scripts and can be opened in any Groovy editor.</p>
</div>
<div class="paragraph">
<p>Example JSON view:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">json.person {
name <span class="string"><span class="delimiter">&quot;</span><span class="content">bob</span><span class="delimiter">&quot;</span></span>
}</code></pre>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
To open them in the Groovy editor in Intellij IDEA, double click on the file and when asked which file to associate it with, choose "Groovy"
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The above JSON view produces:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="json">{<span class="key"><span class="delimiter">&quot;</span><span class="content">person</span><span class="delimiter">&quot;</span></span>:{<span class="key"><span class="delimiter">&quot;</span><span class="content">name</span><span class="delimiter">&quot;</span></span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">bob</span><span class="delimiter">&quot;</span></span>}}</code></pre>
</div>
</div>
<div class="paragraph">
<p>There is an implicit <code>json</code> variable which is an instance of <a href="http://docs.groovy-lang.org/latest/html/api/groovy/json/StreamingJsonBuilder.html">StreamingJsonBuilder</a>.</p>
</div>
<div class="paragraph">
<p>Example usages:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">json(<span class="integer">1</span>,<span class="integer">2</span>,<span class="integer">3</span>) == <span class="string"><span class="delimiter">&quot;</span><span class="content">[1,2,3]</span><span class="delimiter">&quot;</span></span>
json { name <span class="string"><span class="delimiter">&quot;</span><span class="content">Bob</span><span class="delimiter">&quot;</span></span> } == <span class="string"><span class="delimiter">'</span><span class="content">{&quot;name&quot;:&quot;Bob&quot;}</span><span class="delimiter">'</span></span>
json([<span class="integer">1</span>,<span class="integer">2</span>,<span class="integer">3</span>]) { n <span class="local-variable">it</span> } == <span class="string"><span class="delimiter">'</span><span class="content">[{&quot;n&quot;:1},{&quot;n&quot;:2},{&quot;n&quot;:3}]</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Refer to the API documentation on <a href="http://docs.groovy-lang.org/latest/html/api/groovy/json/StreamingJsonBuilder.html">StreamingJsonBuilder</a> for more information about what is possible.</p>
</div>
<h2 id="jsonViewsAndTemplates">10.9.3 JSON View Templates</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/jsonViews/jsonViewsAndTemplates.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>You can define templates starting with underscore <code>_</code>. For example given the following template called <code>_person.gson</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">model {
Person person
}
json {
name person.name
age person.age
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can render it with a view as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">model {
Family family
}
json {
name family.father.name
age family.father.age
oldestChild g.render(<span class="key">template</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">person</span><span class="delimiter">&quot;</span></span>, <span class="key">model</span>:[<span class="key">person</span>: family.children.max { Person p -&gt; p.age } ])
children g.render(<span class="key">template</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">person</span><span class="delimiter">&quot;</span></span>, <span class="key">collection</span>: family.children, <span class="key">var</span>:<span class="string"><span class="delimiter">'</span><span class="content">person</span><span class="delimiter">'</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Alternatively for a more concise way to invoke templates, using the tmpl variable:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">model {
Family family
}
json {
name family.father.name
age family.father.age
oldestChild tmpl.person( family.children.max { Person p -&gt; p.age } ] )
children tmpl.person( family.children )
}</code></pre>
</div>
</div>
<h2 id="jsonViewsAndDomainClasses">10.9.4 Rendering Domain Classes with JSON Views</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/jsonViews/jsonViewsAndDomainClasses.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Typically your model may involve one or many domain instances. JSON views provide a render method for rendering these.</p>
</div>
<div class="paragraph">
<p>For example given the following domain class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Book</span> {
<span class="predefined-type">String</span> title
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>And the following template:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">model {
<span class="predefined-type">Book</span> book
}
json g.render(book)</code></pre>
</div>
</div>
<div class="paragraph">
<p>The resulting output is:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">{<span class="key">id</span>:<span class="integer">1</span>, <span class="key">title</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">The Stand</span><span class="delimiter">&quot;</span></span>}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can customize the rendering by including or excluding properties:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">json g.render(book, [<span class="key">includes</span>:[<span class="string"><span class="delimiter">'</span><span class="content">title</span><span class="delimiter">'</span></span>]])</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or by providing a closure to add additional JSON output:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">json g.render(book) {
pages <span class="integer">1000</span>
}</code></pre>
</div>
</div>
<h2 id="jsonViewsTemplatesAndConventions">10.9.5 JSON Views by Convention</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/jsonViews/jsonViewsTemplatesAndConventions.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>There are a few useful conventions you can follow when creating JSON views. For example if you have a domain class called <code>Book</code>, then creating a template located at <code>grails-app/views/book/_book.gson</code> and using the <a href="../ref/Controllers/respond.html">respond</a> method will result in rendering the template:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">show</span>(<span class="predefined-type">Long</span> id) {
respond <span class="predefined-type">Book</span>.get(id)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In addition if an error occurs during validation by default Grails will try to render a template called <code>grails-app/views/book/_errors.gson</code>, otherwise it will try to render <code>grails-app/views/errors/_errors.gson</code> if the former doesn&#8217;t exist.</p>
</div>
<div class="paragraph">
<p>This is useful because when persisting objects you can <code>respond</code> with validation errors to render these aforementioned templates:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="annotation">@Transactional</span>
<span class="keyword">def</span> <span class="function">save</span>(<span class="predefined-type">Book</span> book) {
<span class="keyword">if</span> (book.hasErrors()) {
transactionStatus.setRollbackOnly()
respond book.errors
}
<span class="keyword">else</span> {
<span class="comment">// valid object</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If a validation error occurs in the above example the <code>grails-app/views/book/_errors.gson</code> template will be rendered.</p>
</div>
<div class="paragraph">
<p>For more information on JSON views (and Markup views), see the <a href="http://views.grails.org/latest/">JSON Views user guide</a>.</p>
</div>
<h2 id="renderers">10.10 Customizing Response Rendering</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/renderers.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>If you are looking for a more low-level API and JSON or Markup views don&#8217;t suite your needs then you may want to consider implementing a custom renderer.</p>
</div>
<h2 id="defaultRenderers">10.10.1 Customizing the Default Renderers</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/renderers/defaultRenderers.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>The default renderers for XML and JSON can be found in the <code>grails.rest.render.xml</code> and <code>grails.rest.render.json</code> packages respectively. These use the Grails converters (<code>grails.converters.XML</code> and <code>grails.converters.JSON</code>) by default for response rendering.</p>
</div>
<div class="paragraph">
<p>You can easily customize response rendering using these default renderers. A common change you may want to make is to include or exclude certain properties from rendering.</p>
</div>
<div class="sect3">
<h4 id="_including_or_excluding_properties_from_rendering">Including or Excluding Properties from Rendering</h4>
<div class="paragraph">
<p>As mentioned previously, Grails maintains a registry of <code>grails.rest.render.Renderer</code> instances. There are some default configured renderers and the ability to register or override renderers for a given domain class or even for a collection of domain classes. To include a particular property from rendering you need to register a custom renderer by defining a bean in <code>grails-app/conf/spring/resources.groovy</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.rest.render.xml.*</span>
beans = {
bookRenderer(XmlRenderer, <span class="predefined-type">Book</span>) {
includes = [<span class="string"><span class="delimiter">'</span><span class="content">title</span><span class="delimiter">'</span></span>]
}
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The bean name is not important (Grails will scan the application context for all registered renderer beans), but for organizational and readability purposes it is recommended you name it something meaningful.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>To exclude a property, the <code>excludes</code> property of the <code>XmlRenderer</code> class can be used:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.rest.render.xml.*</span>
beans = {
bookRenderer(XmlRenderer, <span class="predefined-type">Book</span>) {
excludes = [<span class="string"><span class="delimiter">'</span><span class="content">isbn</span><span class="delimiter">'</span></span>]
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_customizing_the_converters">Customizing the Converters</h4>
<div class="paragraph">
<p>As mentioned previously, the default renders use the <code>grails.converters</code> package under the covers. In other words, under the covers they essentially do the following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.converters.*</span>
...
render book <span class="keyword">as</span> XML
<span class="comment">// or render book as JSON</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Why the separation between converters and renderers? Well a renderer has more flexibility to use whatever rendering technology you chose. When implementing a custom renderer you could use <a href="http://wiki.fasterxml.com/JacksonHome">Jackson</a>, <a href="http://code.google.com/p/google-gson/">Gson</a> or any Java library to implement the renderer. Converters on the other hand are very much tied to Grails' own marshalling implementation.</p>
</div>
</div>
<h2 id="customRenderers">10.10.2 Implementing a Custom Renderer</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/renderers/customRenderers.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>If you want even more control of the rendering or prefer to use your own marshalling techniques then you can implement your own <code>Renderer</code> instance. For example below is a simple implementation that customizes the rendering of the <code>Book</code> class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> myapp
<span class="keyword">import</span> <span class="include">grails.rest.render.*</span>
<span class="keyword">import</span> <span class="include">grails.web.mime.MimeType</span>
<span class="type">class</span> <span class="class">BookXmlRenderer</span> <span class="directive">extends</span> AbstractRenderer&lt;<span class="predefined-type">Book</span>&gt; {
BookXmlRenderer() {
<span class="local-variable">super</span>(<span class="predefined-type">Book</span>, [MimeType.XML,MimeType.TEXT_XML] <span class="keyword">as</span> MimeType<span class="type">[]</span>)
}
<span class="type">void</span> render(<span class="predefined-type">Book</span> object, <span class="predefined-type">RenderContext</span> context) {
context.contentType = MimeType.XML.name
<span class="keyword">def</span> xml = <span class="keyword">new</span> groovy.xml.MarkupBuilder(context.writer)
xml.book(<span class="key">id</span>: object.id, <span class="key">title</span>:object.title)
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>AbstractRenderer</code> super class has a constructor that takes the class that it renders and the <code>MimeType</code>(s) that are accepted (via the ACCEPT header or file extension) for the renderer.</p>
</div>
<div class="paragraph">
<p>To configure this renderer, simply add it is a bean to <code>grails-app/conf/spring/resources.groovy</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">beans = {
bookRenderer(myapp.BookXmlRenderer)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The result will be that all <code>Book</code> instances will be rendered in the following format:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">&lt;book id=<span class="string"><span class="delimiter">&quot;</span><span class="content">1</span><span class="delimiter">&quot;</span></span> title=<span class="string"><span class="delimiter">&quot;</span><span class="content">The Stand</span><span class="delimiter">&quot;</span></span>/&gt;</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
If you change the rendering to a completely different format like the above, then you also need to change the binding if you plan to support POST and PUT requests. Grails will not automatically know how to bind data from a custom XML format to a domain class otherwise. See the section on "Customizing Binding of Resources" for further information.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_container_renderers">Container Renderers</h4>
<div class="paragraph">
<p>A <code>grails.rest.render.ContainerRenderer</code> is a renderer that renders responses for containers of objects (lists, maps, collections etc.). The interface is largely the same as the <code>Renderer</code> interface except for the addition of the <code>getComponentType()</code> method, which should return the "contained" type. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookListRenderer</span> <span class="directive">implements</span> ContainerRenderer&lt;<span class="predefined-type">List</span>, <span class="predefined-type">Book</span>&gt; {
<span class="predefined-type">Class</span>&lt;<span class="predefined-type">List</span>&gt; getTargetType() { <span class="predefined-type">List</span> }
<span class="predefined-type">Class</span>&lt;<span class="predefined-type">Book</span>&gt; getComponentType() { <span class="predefined-type">Book</span> }
MimeType<span class="type">[]</span> getMimeTypes() { [ MimeType.XML] <span class="keyword">as</span> MimeType<span class="type">[]</span> }
<span class="type">void</span> render(<span class="predefined-type">List</span> object, <span class="predefined-type">RenderContext</span> context) {
....
}
}</code></pre>
</div>
</div>
</div>
<h2 id="gspRenderers">10.10.3 Using GSP to Customize Rendering</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/renderers/gspRenderers.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>You can also customize rendering on a per action basis using Groovy Server Pages (GSP). For example given the <code>show</code> action mentioned previously:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">show</span>(<span class="predefined-type">Book</span> book) {
respond book
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You could supply a <code>show.xml.gsp</code> file to customize the rendering of the XML:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">&lt;%<span class="annotation">@page</span> contentType=<span class="string"><span class="delimiter">&quot;</span><span class="content">application/xml</span><span class="delimiter">&quot;</span></span>%&gt;
&lt;book id=<span class="string"><span class="delimiter">&quot;</span><span class="inline"><span class="inline-delimiter">${</span>book.id<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span> title=<span class="string"><span class="delimiter">&quot;</span><span class="inline"><span class="inline-delimiter">${</span>book.title<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>/&gt;</code></pre>
</div>
</div>
<h2 id="hypermedia">10.11 Hypermedia as the Engine of Application State</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/hypermedia.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p><a href="http://en.wikipedia.org/wiki/HATEOAS">HATEOAS</a>, an abbreviation for Hypermedia as the Engine of Application State, is a common pattern applied to REST architectures that uses hypermedia and linking to define the REST API.</p>
</div>
<div class="paragraph">
<p>Hypermedia (also called Mime or Media Types) are used to describe the state of a REST resource, and links tell clients how to transition to the next state. The format of the response is typically JSON or XML, although standard formats such as <a href="http://tools.ietf.org/html/rfc4287">Atom</a> and/or <a href="http://stateless.co/hal_specification.html">HAL</a> are frequently used.</p>
</div>
<h2 id="hal">10.11.1 HAL Support</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/hypermedia/hal.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p><a href="http://stateless.co/hal_specification.html">HAL</a> is a standard exchange format commonly used when developing REST APIs that follow HATEOAS principals. An example HAL document representing a list of orders can be seen below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="javascript">{
<span class="key"><span class="delimiter">&quot;</span><span class="content">_links</span><span class="delimiter">&quot;</span></span>: {
<span class="key"><span class="delimiter">&quot;</span><span class="content">self</span><span class="delimiter">&quot;</span></span>: { <span class="key"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/orders</span><span class="delimiter">&quot;</span></span> },
<span class="key"><span class="delimiter">&quot;</span><span class="content">next</span><span class="delimiter">&quot;</span></span>: { <span class="key"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/orders?page=2</span><span class="delimiter">&quot;</span></span> },
<span class="key"><span class="delimiter">&quot;</span><span class="content">find</span><span class="delimiter">&quot;</span></span>: {
<span class="key"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/orders{?id}</span><span class="delimiter">&quot;</span></span>,
<span class="key"><span class="delimiter">&quot;</span><span class="content">templated</span><span class="delimiter">&quot;</span></span>: <span class="predefined-constant">true</span>
},
<span class="key"><span class="delimiter">&quot;</span><span class="content">admin</span><span class="delimiter">&quot;</span></span>: [{
<span class="key"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/admins/2</span><span class="delimiter">&quot;</span></span>,
<span class="key"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">Fred</span><span class="delimiter">&quot;</span></span>
}, {
<span class="key"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/admins/5</span><span class="delimiter">&quot;</span></span>,
<span class="key"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">Kate</span><span class="delimiter">&quot;</span></span>
}]
},
<span class="key"><span class="delimiter">&quot;</span><span class="content">currentlyProcessing</span><span class="delimiter">&quot;</span></span>: <span class="integer">14</span>,
<span class="key"><span class="delimiter">&quot;</span><span class="content">shippedToday</span><span class="delimiter">&quot;</span></span>: <span class="integer">20</span>,
<span class="key"><span class="delimiter">&quot;</span><span class="content">_embedded</span><span class="delimiter">&quot;</span></span>: {
<span class="key"><span class="delimiter">&quot;</span><span class="content">order</span><span class="delimiter">&quot;</span></span>: [{
<span class="key"><span class="delimiter">&quot;</span><span class="content">_links</span><span class="delimiter">&quot;</span></span>: {
<span class="key"><span class="delimiter">&quot;</span><span class="content">self</span><span class="delimiter">&quot;</span></span>: { <span class="key"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/orders/123</span><span class="delimiter">&quot;</span></span> },
<span class="key"><span class="delimiter">&quot;</span><span class="content">basket</span><span class="delimiter">&quot;</span></span>: { <span class="key"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/baskets/98712</span><span class="delimiter">&quot;</span></span> },
<span class="key"><span class="delimiter">&quot;</span><span class="content">customer</span><span class="delimiter">&quot;</span></span>: { <span class="key"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/customers/7809</span><span class="delimiter">&quot;</span></span> }
},
<span class="key"><span class="delimiter">&quot;</span><span class="content">total</span><span class="delimiter">&quot;</span></span>: <span class="float">30.00</span>,
<span class="key"><span class="delimiter">&quot;</span><span class="content">currency</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">USD</span><span class="delimiter">&quot;</span></span>,
<span class="key"><span class="delimiter">&quot;</span><span class="content">status</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">shipped</span><span class="delimiter">&quot;</span></span>
}, {
<span class="key"><span class="delimiter">&quot;</span><span class="content">_links</span><span class="delimiter">&quot;</span></span>: {
<span class="key"><span class="delimiter">&quot;</span><span class="content">self</span><span class="delimiter">&quot;</span></span>: { <span class="key"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/orders/124</span><span class="delimiter">&quot;</span></span> },
<span class="key"><span class="delimiter">&quot;</span><span class="content">basket</span><span class="delimiter">&quot;</span></span>: { <span class="key"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/baskets/97213</span><span class="delimiter">&quot;</span></span> },
<span class="key"><span class="delimiter">&quot;</span><span class="content">customer</span><span class="delimiter">&quot;</span></span>: { <span class="key"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">/customers/12369</span><span class="delimiter">&quot;</span></span> }
},
<span class="key"><span class="delimiter">&quot;</span><span class="content">total</span><span class="delimiter">&quot;</span></span>: <span class="float">20.00</span>,
<span class="key"><span class="delimiter">&quot;</span><span class="content">currency</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">USD</span><span class="delimiter">&quot;</span></span>,
<span class="key"><span class="delimiter">&quot;</span><span class="content">status</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">processing</span><span class="delimiter">&quot;</span></span>
}]
}
}</code></pre>
</div>
</div>
<div class="sect3">
<h4 id="_exposing_resources_using_hal">Exposing Resources Using HAL</h4>
<div class="paragraph">
<p>To return HAL instead of regular JSON for a resource you can simply override the renderer in <code>grails-app/conf/spring/resources.groovy</code> with an instance of <code>grails.rest.render.hal.HalJsonRenderer</code> (or <code>HalXmlRenderer</code> for the XML variation):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.rest.render.hal.*</span>
beans = {
halBookRenderer(HalJsonRenderer, rest.test.Book)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You will also need to update the acceptable response formats for the resource so that the HAL format is included. Not doing so will result in a 406 - Not Acceptable response being returned from the server.</p>
</div>
<div class="paragraph">
<p>This can be done by setting the <code>formats</code> attribute of the <code>Resource</code> transformation:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.rest.*</span>
<span class="annotation">@Resource</span>(uri=<span class="string"><span class="delimiter">'</span><span class="content">/books</span><span class="delimiter">'</span></span>, formats=[<span class="string"><span class="delimiter">'</span><span class="content">json</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">xml</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">hal</span><span class="delimiter">'</span></span>])
<span class="type">class</span> <span class="class">Book</span> {
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or by updating the <code>responseFormats</code> in the controller:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> <span class="directive">extends</span> RestfulController {
<span class="directive">static</span> responseFormats = [<span class="string"><span class="delimiter">'</span><span class="content">json</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">xml</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">hal</span><span class="delimiter">'</span></span>]
<span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>With the bean in place requesting the HAL content type will return HAL:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span> curl -i -H <span class="string"><span class="delimiter">&quot;</span><span class="content">Accept: application/hal+json</span><span class="delimiter">&quot;</span></span> <span class="key">http</span>:<span class="comment">//localhost:8080/books/1</span>
HTTP/<span class="float">1.1</span> <span class="integer">200</span> OK
<span class="key">Server</span>: Apache-Coyote/<span class="float">1.1</span>
Content-<span class="predefined-type">Type</span>: application/hal+json;charset=ISO-<span class="integer">8859</span>-<span class="integer">1</span>
{
<span class="string"><span class="delimiter">&quot;</span><span class="content">_links</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">self</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">http://localhost:8080/books/1</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">hreflang</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">en</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">type</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">application/hal+json</span><span class="delimiter">&quot;</span></span>
}
},
<span class="string"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="char">\&quot;</span><span class="content">The Stand</span><span class="char">\&quot;</span><span class="delimiter">&quot;</span></span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>To use HAL XML format simply change the renderer:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.rest.render.hal.*</span>
beans = {
halBookRenderer(HalXmlRenderer, rest.test.Book)
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_rendering_collections_using_hal">Rendering Collections Using HAL</h4>
<div class="paragraph">
<p>To return HAL instead of regular JSON for a list of resources you can simply override the renderer in <code>grails-app/conf/spring/resources.groovy</code> with an instance of <code>grails.rest.render.hal.HalJsonCollectionRenderer</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.rest.render.hal.*</span>
beans = {
halBookCollectionRenderer(HalJsonCollectionRenderer, rest.test.Book)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>With the bean in place requesting the HAL content type will return HAL:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span> curl -i -H <span class="string"><span class="delimiter">&quot;</span><span class="content">Accept: application/hal+json</span><span class="delimiter">&quot;</span></span> <span class="key">http</span>:<span class="comment">//localhost:8080/books</span>
HTTP/<span class="float">1.1</span> <span class="integer">200</span> OK
<span class="key">Server</span>: Apache-Coyote/<span class="float">1.1</span>
Content-<span class="predefined-type">Type</span>: application/hal+json;charset=UTF-<span class="integer">8</span>
Transfer-<span class="key">Encoding</span>: chunked
<span class="predefined-type">Date</span>: Thu, <span class="integer">17</span> Oct <span class="integer">2013</span> <span class="octal">02</span>:<span class="integer">34</span>:<span class="integer">14</span> GMT
{
<span class="string"><span class="delimiter">&quot;</span><span class="content">_links</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">self</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">http://localhost:8080/books</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">hreflang</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">en</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">type</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">application/hal+json</span><span class="delimiter">&quot;</span></span>
}
},
<span class="string"><span class="delimiter">&quot;</span><span class="content">_embedded</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">book</span><span class="delimiter">&quot;</span></span>: [
{
<span class="string"><span class="delimiter">&quot;</span><span class="content">_links</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">self</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">http://localhost:8080/books/1</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">hreflang</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">en</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">type</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">application/hal+json</span><span class="delimiter">&quot;</span></span>
}
},
<span class="string"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">The Stand</span><span class="delimiter">&quot;</span></span>
},
{
<span class="string"><span class="delimiter">&quot;</span><span class="content">_links</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">self</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">http://localhost:8080/books/2</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">hreflang</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">en</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">type</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">application/hal+json</span><span class="delimiter">&quot;</span></span>
}
},
<span class="string"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">Infinite Jest</span><span class="delimiter">&quot;</span></span>
},
{
<span class="string"><span class="delimiter">&quot;</span><span class="content">_links</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">self</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">http://localhost:8080/books/3</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">hreflang</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">en</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">type</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">application/hal+json</span><span class="delimiter">&quot;</span></span>
}
},
<span class="string"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">Walden</span><span class="delimiter">&quot;</span></span>
}
]
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Notice that the key associated with the list of <code>Book</code> objects in the rendered JSON is <code>book</code> which is derived from the type of objects in the collection, namely <code>Book</code>. In order to customize the value of this key assign a value to the <code>collectionName</code> property on the <code>HalJsonCollectionRenderer</code> bean as shown below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.rest.render.hal.*</span>
beans = {
halBookCollectionRenderer(HalCollectionJsonRenderer, rest.test.Book) {
collectionName = <span class="string"><span class="delimiter">'</span><span class="content">publications</span><span class="delimiter">'</span></span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>With that in place the rendered HAL will look like the following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span> curl -i -H <span class="string"><span class="delimiter">&quot;</span><span class="content">Accept: application/hal+json</span><span class="delimiter">&quot;</span></span> <span class="key">http</span>:<span class="comment">//localhost:8080/books</span>
HTTP/<span class="float">1.1</span> <span class="integer">200</span> OK
<span class="key">Server</span>: Apache-Coyote/<span class="float">1.1</span>
Content-<span class="predefined-type">Type</span>: application/hal+json;charset=UTF-<span class="integer">8</span>
Transfer-<span class="key">Encoding</span>: chunked
<span class="predefined-type">Date</span>: Thu, <span class="integer">17</span> Oct <span class="integer">2013</span> <span class="octal">02</span>:<span class="integer">34</span>:<span class="integer">14</span> GMT
{
<span class="string"><span class="delimiter">&quot;</span><span class="content">_links</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">self</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">http://localhost:8080/books</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">hreflang</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">en</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">type</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">application/hal+json</span><span class="delimiter">&quot;</span></span>
}
},
<span class="string"><span class="delimiter">&quot;</span><span class="content">_embedded</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">publications</span><span class="delimiter">&quot;</span></span>: [
{
<span class="string"><span class="delimiter">&quot;</span><span class="content">_links</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">self</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">http://localhost:8080/books/1</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">hreflang</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">en</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">type</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">application/hal+json</span><span class="delimiter">&quot;</span></span>
}
},
<span class="string"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">The Stand</span><span class="delimiter">&quot;</span></span>
},
{
<span class="string"><span class="delimiter">&quot;</span><span class="content">_links</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">self</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">http://localhost:8080/books/2</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">hreflang</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">en</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">type</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">application/hal+json</span><span class="delimiter">&quot;</span></span>
}
},
<span class="string"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">Infinite Jest</span><span class="delimiter">&quot;</span></span>
},
{
<span class="string"><span class="delimiter">&quot;</span><span class="content">_links</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">self</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">http://localhost:8080/books/3</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">hreflang</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">en</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">type</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">application/hal+json</span><span class="delimiter">&quot;</span></span>
}
},
<span class="string"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">Walden</span><span class="delimiter">&quot;</span></span>
}
]
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_using_custom_media_mime_types">Using Custom Media / Mime Types</h4>
<div class="paragraph">
<p>If you wish to use a custom Mime Type then you first need to declare the Mime Types in <code>grails-app/conf/application.groovy</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails.mime.types = [
<span class="key">all</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">*/*</span><span class="delimiter">&quot;</span></span>,
<span class="key">book</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">application/vnd.books.org.book+json</span><span class="delimiter">&quot;</span></span>,
<span class="key">bookList</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">application/vnd.books.org.booklist+json</span><span class="delimiter">&quot;</span></span>,
...
]</code></pre>
</div>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
It is critical that place your new mime types after the 'all' Mime Type because if the Content Type of the request cannot be established then the first entry in the map is used for the response. If you have your new Mime Type at the top then Grails will always try and send back your new Mime Type if the requested Mime Type cannot be established.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Then override the renderer to return HAL using the custom Mime Types:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.rest.render.hal.*</span>
<span class="keyword">import</span> <span class="include">grails.web.mime.*</span>
beans = {
halBookRenderer(HalJsonRenderer, rest.test.Book, <span class="keyword">new</span> MimeType(<span class="string"><span class="delimiter">&quot;</span><span class="content">application/vnd.books.org.book+json</span><span class="delimiter">&quot;</span></span>, [<span class="key">v</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">1.0</span><span class="delimiter">&quot;</span></span>]))
halBookListRenderer(HalJsonCollectionRenderer, rest.test.Book, <span class="keyword">new</span> MimeType(<span class="string"><span class="delimiter">&quot;</span><span class="content">application/vnd.books.org.booklist+json</span><span class="delimiter">&quot;</span></span>, [<span class="key">v</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">1.0</span><span class="delimiter">&quot;</span></span>]))
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the above example the first bean defines a HAL renderer for a single book instance that returns a Mime Type of <code>application/vnd.books.org.book+json</code>. The second bean defines the Mime Type used to render a collection of books (in this case <code>application/vnd.books.org.booklist+json</code>).</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<code>application/vnd.books.org.booklist+json</code> is an example of a media-range (<a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html" class="bare">http://www.w3.org/Protocols/rfc2616/rfc2616.html</a> - Header Field Definitions). This example uses entity (book) and operation (list) to form the media-range values but in reality, it may not be necessary to create a separate Mime type for each operation. Further, it may not be necessary to create Mime types at the entity level. See the section on "Versioning REST resources" for further information about how to define your own Mime types.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>With this in place issuing a request for the new Mime Type returns the necessary HAL:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ curl -i -H &quot;Accept: application/vnd.books.org.book+json&quot; http://localhost:8080/books/1
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/vnd.books.org.book+json;charset=ISO-8859-1
{
&quot;_links&quot;: {
&quot;self&quot;: {
&quot;href&quot;: &quot;http://localhost:8080/books/1&quot;,
&quot;hreflang&quot;: &quot;en&quot;,
&quot;type&quot;: &quot;application/vnd.books.org.book+json&quot;
}
},
&quot;title&quot;: &quot;\&quot;The Stand\&quot;&quot;
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_customizing_link_rendering">Customizing Link Rendering</h4>
<div class="paragraph">
<p>An important aspect of HATEOAS is the usage of links that describe the transitions the client can use to interact with the REST API. By default the <code>HalJsonRenderer</code> will automatically create links for you for associations and to the resource itself (using the "self" relationship).</p>
</div>
<div class="paragraph">
<p>However you can customize link rendering using the <code>link</code> method that is added to all domain classes annotated with <code>grails.rest.Resource</code> or any class annotated with <code>grails.rest.Linkable</code>. For example, the <code>show</code> action can be modified as follows to provide a new link in the resulting output:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">show</span>(<span class="predefined-type">Book</span> book) {
book.link <span class="key">rel</span>:<span class="string"><span class="delimiter">'</span><span class="content">publisher</span><span class="delimiter">'</span></span>, <span class="key">href</span>: g.createLink(<span class="key">absolute</span>: <span class="predefined-constant">true</span>, <span class="key">resource</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">publisher</span><span class="delimiter">&quot;</span></span>, <span class="key">params</span>:[<span class="key">bookId</span>: book.id])
respond book
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Which will result in output such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="javascript">{
<span class="key"><span class="delimiter">&quot;</span><span class="content">_links</span><span class="delimiter">&quot;</span></span>: {
<span class="key"><span class="delimiter">&quot;</span><span class="content">self</span><span class="delimiter">&quot;</span></span>: {
<span class="key"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">http://localhost:8080/books/1</span><span class="delimiter">&quot;</span></span>,
<span class="key"><span class="delimiter">&quot;</span><span class="content">hreflang</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">en</span><span class="delimiter">&quot;</span></span>,
<span class="key"><span class="delimiter">&quot;</span><span class="content">type</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">application/vnd.books.org.book+json</span><span class="delimiter">&quot;</span></span>
}
<span class="string"><span class="delimiter">&quot;</span><span class="content">publisher</span><span class="delimiter">&quot;</span></span>: {
<span class="key"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">http://localhost:8080/books/1/publisher</span><span class="delimiter">&quot;</span></span>,
<span class="key"><span class="delimiter">&quot;</span><span class="content">hreflang</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">en</span><span class="delimiter">&quot;</span></span>
}
},
<span class="key"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="char">\&quot;</span><span class="content">The Stand</span><span class="char">\&quot;</span><span class="delimiter">&quot;</span></span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>link</code> method can be passed named arguments that match the properties of the <code>grails.rest.Link</code> class.</p>
</div>
</div>
<h2 id="atom">10.11.2 Atom Support</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/hypermedia/atom.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p><a href="http://tools.ietf.org/html/rfc4287">Atom</a> is another standard interchange format used to implement REST APIs. An example of Atom output can be seen below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="preprocessor">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;</span>
<span class="tag">&lt;feed</span> <span class="attribute-name">xmlns</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">http://www.w3.org/2005/Atom</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
<span class="tag">&lt;title&gt;</span>Example Feed<span class="tag">&lt;/title&gt;</span>
<span class="tag">&lt;link</span> <span class="attribute-name">href</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">http://example.org/</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span>
<span class="tag">&lt;updated&gt;</span>2003-12-13T18:30:02Z<span class="tag">&lt;/updated&gt;</span>
<span class="tag">&lt;author&gt;</span>
<span class="tag">&lt;name&gt;</span>John Doe<span class="tag">&lt;/name&gt;</span>
<span class="tag">&lt;/author&gt;</span>
<span class="tag">&lt;id&gt;</span>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6<span class="tag">&lt;/id&gt;</span>
<span class="tag">&lt;entry&gt;</span>
<span class="tag">&lt;title&gt;</span>Atom-Powered Robots Run Amok<span class="tag">&lt;/title&gt;</span>
<span class="tag">&lt;link</span> <span class="attribute-name">href</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">http://example.org/2003/12/13/atom03</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span>
<span class="tag">&lt;id&gt;</span>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a<span class="tag">&lt;/id&gt;</span>
<span class="tag">&lt;updated&gt;</span>2003-12-13T18:30:02Z<span class="tag">&lt;/updated&gt;</span>
<span class="tag">&lt;summary&gt;</span>Some text.<span class="tag">&lt;/summary&gt;</span>
<span class="tag">&lt;/entry&gt;</span>
<span class="tag">&lt;/feed&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>To use Atom rendering again simply define a custom renderer:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.rest.render.atom.*</span>
beans = {
halBookRenderer(AtomRenderer, rest.test.Book)
halBookListRenderer(AtomCollectionRenderer, rest.test.Book)
}</code></pre>
</div>
</div>
<h2 id="vndError">10.11.3 Vnd.Error Support</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/hypermedia/vndError.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p><a href="https://github.com/blongden/vnd.error">Vnd.Error</a> is a standardised way of expressing an error response.</p>
</div>
<div class="paragraph">
<p>By default when a validation error occurs when attempting to POST new resources then the errors object will be sent back allow with a 422 respond code:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span> curl -i -H <span class="string"><span class="delimiter">&quot;</span><span class="content">Accept: application/json</span><span class="delimiter">&quot;</span></span> -H <span class="string"><span class="delimiter">&quot;</span><span class="content">Content-Type: application/json</span><span class="delimiter">&quot;</span></span> -X POST -d <span class="string"><span class="delimiter">&quot;</span><span class="delimiter">&quot;</span></span> <span class="key">http</span>:<span class="comment">//localhost:8080/books</span>
HTTP/<span class="float">1.1</span> <span class="integer">422</span> Unprocessable <span class="predefined-type">Entity</span>
<span class="key">Server</span>: Apache-Coyote/<span class="float">1.1</span>
Content-<span class="predefined-type">Type</span>: application/json;charset=ISO-<span class="integer">8859</span>-<span class="integer">1</span>
{
<span class="string"><span class="delimiter">&quot;</span><span class="content">errors</span><span class="delimiter">&quot;</span></span>: [
{
<span class="string"><span class="delimiter">&quot;</span><span class="content">object</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">rest.test.Book</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">field</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">title</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">rejected-value</span><span class="delimiter">&quot;</span></span>: <span class="predefined-constant">null</span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">message</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">Property [title] of class [class rest.test.Book] cannot be null</span><span class="delimiter">&quot;</span></span>
}
]
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you wish to change the format to Vnd.Error then simply register <code>grails.rest.render.errors.VndErrorJsonRenderer</code> bean in <code>grails-app/conf/spring/resources.groovy</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">beans = {
vndJsonErrorRenderer(grails.rest.render.errors.VndErrorJsonRenderer)
<span class="comment">// for Vnd.Error XML format</span>
vndXmlErrorRenderer(grails.rest.render.errors.VndErrorXmlRenderer)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then if you alter the client request to accept Vnd.Error you get an appropriate response:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span> curl -i -H <span class="string"><span class="delimiter">&quot;</span><span class="content">Accept: application/vnd.error+json,application/json</span><span class="delimiter">&quot;</span></span> -H <span class="string"><span class="delimiter">&quot;</span><span class="content">Content-Type: application/json</span><span class="delimiter">&quot;</span></span> -X POST -d <span class="string"><span class="delimiter">&quot;</span><span class="delimiter">&quot;</span></span> <span class="key">http</span>:<span class="comment">//localhost:8080/books</span>
HTTP/<span class="float">1.1</span> <span class="integer">200</span> OK
<span class="key">Server</span>: Apache-Coyote/<span class="float">1.1</span>
Content-<span class="predefined-type">Type</span>: application/vnd.error+json;charset=ISO-<span class="integer">8859</span>-<span class="integer">1</span>
[
{
<span class="string"><span class="delimiter">&quot;</span><span class="content">logref</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">book.nullable,</span></span><span class="error">
</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">message</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">Property [title] of class [class rest.test.Book] cannot be null</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">_links</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">resource</span><span class="delimiter">&quot;</span></span>: {
<span class="string"><span class="delimiter">&quot;</span><span class="content">href</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">http://localhost:8080/rest-test/books</span><span class="delimiter">&quot;</span></span>
}
}
}
]</code></pre>
</div>
</div>
<h2 id="binding">10.12 Customizing Binding of Resources</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/binding.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>The framework provides a sophisticated but simple mechanism for binding REST requests to domain objects and command objects. One way to take advantage of this is to bind the <code>request</code> property in a controller the <code>properties</code> of a domain class. Given the following XML as the body of the request, the <code>createBook</code> action will create a new <code>Book</code> and assign "The Stand" to the <code>title</code> property and "Stephen King" to the <code>authorName</code> property.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">&lt;?xml version=<span class="string"><span class="delimiter">&quot;</span><span class="content">1.0</span><span class="delimiter">&quot;</span></span> encoding=<span class="string"><span class="delimiter">&quot;</span><span class="content">UTF-8</span><span class="delimiter">&quot;</span></span>?&gt;
&lt;book&gt;
&lt;title&gt;The Stand&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">title&gt;</span></span><span class="error">
</span> &lt;authorName&gt;Stephen King&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">authorName&gt;</span></span><span class="error">
</span>&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">book&gt;</span></span></code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> {
<span class="keyword">def</span> <span class="function">createBook</span>() {
<span class="keyword">def</span> book = <span class="keyword">new</span> <span class="predefined-type">Book</span>()
book.properties = request
<span class="comment">// ...</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Command objects will automatically be bound with the body of the request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> {
<span class="keyword">def</span> <span class="function">createBook</span>(BookCommand book) {
<span class="comment">// ...</span>
}
}
<span class="type">class</span> <span class="class">BookCommand</span> {
<span class="predefined-type">String</span> title
<span class="predefined-type">String</span> authorName
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If the command object type is a domain class and the root element of the XML document contains an <code>id</code> attribute, the <code>id</code> value will be used to retrieve the corresponding persistent instance from the database and then the rest of the document will be bound to the instance. If no corresponding record is found in the database, the command object reference will be null.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">&lt;?xml version=<span class="string"><span class="delimiter">&quot;</span><span class="content">1.0</span><span class="delimiter">&quot;</span></span> encoding=<span class="string"><span class="delimiter">&quot;</span><span class="content">UTF-8</span><span class="delimiter">&quot;</span></span>?&gt;
&lt;book id=<span class="string"><span class="delimiter">&quot;</span><span class="content">42</span><span class="delimiter">&quot;</span></span>&gt;
&lt;title&gt;Walden&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">title&gt;</span></span><span class="error">
</span> &lt;authorName&gt;Henry David Thoreau&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">authorName&gt;</span></span><span class="error">
</span>&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">book&gt;</span></span></code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> {
<span class="keyword">def</span> <span class="function">updateBook</span>(<span class="predefined-type">Book</span> book) {
<span class="comment">// The book will have been retrieved from the database and updated</span>
<span class="comment">// by doing something like this:</span>
<span class="comment">//</span>
<span class="comment">// book == Book.get('42')</span>
<span class="comment">// if(book != null) {</span>
<span class="comment">// book.properties = request</span>
<span class="comment">// }</span>
<span class="comment">//</span>
<span class="comment">// the code above represents what the framework will</span>
<span class="comment">// have done. There is no need to write that code.</span>
<span class="comment">// ...</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The data binding depends on an instance of the <a href="https://grails.apache.org/docs/3.3.7/api/grails/databinding/DataBindingSource.html">DataBindingSource</a> interface created by an instance of the <a href="https://grails.apache.org/docs/3.3.7/api/org/grails/databinding/bindingsource/DataBindingSourceCreator.html">DataBindingSourceCreator</a> interface. The specific implementation of <code>DataBindingSourceCreator</code> will be selected based on the <code>contentType</code> of the request. Several implementations are provided to handle common content types. The default implementations will be fine for most use cases. The following table lists the content types which are supported by the core framework and which <code>DataBindingSourceCreator</code> implementations are used for each. All of the implementation classes are in the <code>org.grails.databinding.bindingsource</code> package.</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">Content Type(s)</th>
<th class="tableblock halign-left valign-top">Bean Name</th>
<th class="tableblock halign-left valign-top">DataBindingSourceCreator Impl.</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">application/xml, text/xml</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">xmlDataBindingSourceCreator</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">XmlDataBindingSourceCreator</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">application/json, text/json</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">jsonDataBindingSourceCreator</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">JsonDataBindingSourceCreator</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">application/hal+json</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">halJsonDataBindingSourceCreator</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">HalJsonDataBindingSourceCreator</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">application/hal+xml</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">halXmlDataBindingSourceCreator</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">HalXmlDataBindingSourceCreator</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>In order to provide your own <code>DataBindingSourceCreator</code> for any of those content types, write a class which implements
<code>DataBindingSourceCreator</code> and register an instance of that class in the Spring application context. If you
are replacing one of the existing helpers, use the corresponding bean name from above. If you are providing a
helper for a content type other than those accounted for by the core framework, the bean name may be anything that
you like but you should take care not to conflict with one of the bean names above.</p>
</div>
<div class="paragraph">
<p>The <code>DataBindingSourceCreator</code> interface defines just 2 methods:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> org.grails.databinding.bindingsource
<span class="keyword">import</span> <span class="include">grails.web.mime.MimeType</span>
<span class="keyword">import</span> <span class="include">grails.databinding.DataBindingSource</span>
<span class="comment">/**
* A factory for DataBindingSource instances
*
* @since 2.3
* @see DataBindingSourceRegistry
* @see DataBindingSource
*
*/</span>
<span class="type">interface</span> DataBindingSourceCreator {
<span class="comment">/**
* `return All of the {`link MimeType} supported by this helper
*/</span>
MimeType<span class="type">[]</span> getMimeTypes()
<span class="comment">/**
* Creates a DataBindingSource suitable for binding bindingSource to bindingTarget
*
* @param mimeType a mime type
* @param bindingTarget the target of the data binding
* @param bindingSource the value being bound
* @return a DataBindingSource
*/</span>
DataBindingSource createDataBindingSource(MimeType mimeType, <span class="predefined-type">Object</span> bindingTarget, <span class="predefined-type">Object</span> bindingSource)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><a href="https://grails.apache.org/docs/3.3.7/api/org/grails/web/databinding/bindingsource/AbstractRequestBodyDataBindingSourceCreator.html">AbstractRequestBodyDataBindingSourceCreator</a>
is an abstract class designed to be extended to simplify writing custom <code>DataBindingSourceCreator</code> classes. Classes which
extend <code>AbstractRequestbodyDatabindingSourceCreator</code> need to implement a method named <code>createBindingSource</code>
which accepts an <code>InputStream</code> as an argument and returns a <code>DataBindingSource</code> as well as implementing the <code>getMimeTypes</code>
method described in the <code>DataBindingSourceCreator</code> interface above. The <code>InputStream</code> argument to <code>createBindingSource</code>
provides access to the body of the request.</p>
</div>
<div class="paragraph">
<p>The code below shows a simple implementation.</p>
</div>
<div class="listingblock">
<div class="title">src/main/groovy/com/demo/myapp/databinding/MyCustomDataBindingSourceCreator.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.demo.myapp.databinding
<span class="keyword">import</span> <span class="include">grails.web.mime.MimeType</span>
<span class="keyword">import</span> <span class="include">grails.databinding.DataBindingSource</span>
<span class="keyword">import</span> <span class="include">org</span>...<span class="include">databinding.SimpleMapDataBindingSource</span>
<span class="keyword">import</span> <span class="include">org</span>...<span class="include">databinding.bindingsource.AbstractRequestBodyDataBindingSourceCreator</span>
<span class="comment">/**
* A custom DataBindingSourceCreator capable of parsing key value pairs out of
* a request body containing a comma separated list of key:value pairs like:
*
* name:Herman,age:99,town:STL
*
*/</span>
<span class="type">class</span> <span class="class">MyCustomDataBindingSourceCreator</span> <span class="directive">extends</span> AbstractRequestBodyDataBindingSourceCreator {
<span class="annotation">@Override</span>
<span class="directive">public</span> MimeType<span class="type">[]</span> getMimeTypes() {
[<span class="keyword">new</span> MimeType(<span class="string"><span class="delimiter">'</span><span class="content">text/custom+demo+csv</span><span class="delimiter">'</span></span>)] <span class="keyword">as</span> MimeType<span class="type">[]</span>
}
<span class="annotation">@Override</span>
<span class="directive">protected</span> DataBindingSource createBindingSource(<span class="predefined-type">InputStream</span> inputStream) {
<span class="keyword">def</span> map = [:]
<span class="keyword">def</span> reader = <span class="keyword">new</span> <span class="predefined-type">InputStreamReader</span>(inputStream)
<span class="comment">// this is an obviously naive parser and is intended</span>
<span class="comment">// for demonstration purposes only.</span>
reader.eachLine { line -&gt;
<span class="keyword">def</span> keyValuePairs = line.split(<span class="string"><span class="delimiter">'</span><span class="content">,</span><span class="delimiter">'</span></span>)
keyValuePairs.each { keyValuePair -&gt;
<span class="keyword">if</span>(keyValuePair?.trim()) {
<span class="keyword">def</span> keyValuePieces = keyValuePair.split(<span class="string"><span class="delimiter">'</span><span class="content">:</span><span class="delimiter">'</span></span>)
<span class="keyword">def</span> key = keyValuePieces[<span class="integer">0</span>].trim()
<span class="keyword">def</span> value = keyValuePieces[<span class="integer">1</span>].trim()
map&lt;&lt;key&gt;&gt; = value
}
}
}
<span class="comment">// create and return a DataBindingSource which contains the parsed data</span>
<span class="keyword">new</span> SimpleMapDataBindingSource(map)
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>An instance of <code>MyCustomDataSourceCreator</code> needs to be registered in the spring application context.</p>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/spring/resources.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">beans = {
myCustomCreator com.demo.myapp.databinding.MyCustomDataBindingSourceCreator
<span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>With that in place the framework will use the <code>myCustomCreator</code> bean any time a <code>DataBindingSourceCreator</code> is needed
to deal with a request which has a <code>contentType</code> of "text/custom+demo+csv".</p>
</div>
<a name="8.3 RSS and Atom"><!-- Legacy link --></a>
<h2 id="RSSAndAtom">10.13 RSS and Atom</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/REST/RSSAndAtom.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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">render</a> method&#8217;s XML capability.</p>
</div>
<a name="8 Asynchronous Programming"><!-- Legacy link --></a>
<h1 id="async">11 Asynchronous Programming</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/async.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>With modern hardware featuring multiple cores, many programming languages have been adding asynchronous, parallel programming APIs, Groovy being no exception.</p>
</div>
<div class="paragraph">
<p>Popular asynchronous libraries include:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>RxJava - <a href="http://reactivex.io" class="bare">http://reactivex.io</a></p>
</li>
<li>
<p>GPars - <a href="http://gpars.org" class="bare">http://gpars.org</a></p>
</li>
<li>
<p>Reactor - <a href="https://projectreactor.io" class="bare">https://projectreactor.io</a></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>By building ontop of these various libraries the The <a href="https://grails.apache.org/docs/latest/guide/async.html">Async features of Grails</a> aim to simplify concurrent programming within the framework and include the concept of Promises and a unified event model.</p>
</div>
<div class="paragraph">
<p>In general since the Reactive programming model is an evolving space Grails tries to provide generic support for integrating a range of asynchronous libraries and doesn&#8217;t recommend any single library as they all have various advantages and disadvantages.</p>
</div>
<div class="paragraph">
<p>For more information on Asynchronous programming with Grails see the user guide for the <a href="https://grails.apache.org/docs/latest/guide/async.html">Grails Asynchronous Framework</a>.</p>
</div>
<a name="10. Validation"><!-- Legacy link --></a>
<h1 id="validation">12 Validation</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/validation.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails validation capability is built on <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/package-summary.html">Spring&#8217;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>
</div>
<div class="paragraph">
<p>Constraints in Grails are a way to declaratively specify validation rules. Most commonly they are applied to <a href="GORM.html">domain classes</a>, however <a href="theWebLayer.html#urlmappings">URL Mappings</a> and <a href="theWebLayer.html#commandObjects">Command Objects</a> also support constraints.</p>
</div>
<a name="10.1 Declaring Constraints"><!-- Legacy link --></a>
<h2 id="constraints">12.1 Declaring Constraints</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/validation/constraints.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Within a domain class <a href="../ref/Domain%20Classes/constraints.html">constraints</a> are defined with the constraints property that is assigned a code block:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">User</span> {
<span class="predefined-type">String</span> login
<span class="predefined-type">String</span> password
<span class="predefined-type">String</span> email
<span class="predefined-type">Integer</span> age
<span class="directive">static</span> constraints = {
...
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You then use method calls that match the property name for which the constraint applies in combination with named parameters to specify constraints:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">User</span> {
...
static constraints = {
login <span class="key">size</span>: <span class="integer">5</span>..<span class="integer">15</span>, <span class="key">blank</span>: <span class="predefined-constant">false</span>, <span class="key">unique</span>: <span class="predefined-constant">true</span>
password <span class="key">size</span>: <span class="integer">5</span>..<span class="integer">15</span>, <span class="key">blank</span>: <span class="predefined-constant">false</span>
email <span class="key">email</span>: <span class="predefined-constant">true</span>, <span class="key">blank</span>: <span class="predefined-constant">false</span>
age <span class="key">min</span>: <span class="integer">18</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this example we&#8217;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&#8217;ve also applied other constraints to the <code>password</code>, <code>email</code> and <code>age</code> properties.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
By default, all domain class properties are not nullable (i.e. they have an implicit <code>nullable: false</code> constraint).
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>A complete reference for the available constraints can be found in the Quick Reference section under the Constraints heading.</p>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">User</span> {
...
static constraints = {
<span class="comment">// this Date object is created when the constraints are evaluated, not</span>
<span class="comment">// each time an instance of the User class is validated.</span>
birthDate <span class="key">max</span>: <span class="keyword">new</span> <span class="predefined-type">Date</span>()
}
}</code></pre>
</div>
</div>
<div class="sect2">
<h3 id="_a_word_of_warning_referencing_domain_class_properties_from_constraints">A word of warning - referencing domain class properties from constraints</h3>
<div class="paragraph">
<p>It&#8217;s very easy to attempt to reference instance variables from the static constraints block, but this isn&#8217;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</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Response</span> {
Survey survey
Answer answer
<span class="directive">static</span> constraints = {
survey <span class="key">blank</span>: <span class="predefined-constant">false</span>
answer <span class="key">blank</span>: <span class="predefined-constant">false</span>, <span class="key">inList</span>: survey.answers
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>See how the <code>inList</code> constraint references the instance property <code>survey</code>? That won&#8217;t work. Instead, use a custom <a href="../ref/Constraints/validator.html">validator</a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Response</span> {
...
static constraints = {
survey <span class="key">blank</span>: <span class="predefined-constant">false</span>
answer <span class="key">blank</span>: <span class="predefined-constant">false</span>, <span class="key">validator</span>: { val, obj -&gt; val <span class="keyword">in</span> obj.survey.answers }
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this example, the <code>obj</code> argument to the custom validator is the domain <em>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.</p>
</div>
</div>
<a name="10.2 Validating Constraints"><!-- Legacy link --></a>
<h2 id="validatingConstraints">12.2 Validating Constraints</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/validation/validatingConstraints.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_validation_basics">Validation Basics</h4>
<div class="paragraph">
<p>Call the <a href="../ref/Domain%20Classes/validate.html">validate</a> method to validate a domain class instance:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> user = <span class="keyword">new</span> User(params)
<span class="keyword">if</span> (user.validate()) {
<span class="comment">// do something with user</span>
}
<span class="keyword">else</span> {
user.errors.allErrors.each {
println <span class="local-variable">it</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>errors</code> property on domain classes is an instance of the Spring <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/Errors.html">Errors</a> interface. The <code>Errors</code> interface provides methods to navigate the validation errors and also retrieve the original values.</p>
</div>
</div>
<div class="sect3">
<h4 id="_validation_phases">Validation Phases</h4>
<div class="paragraph">
<p>Within Grails there are two phases of validation, the first one being <a href="theWebLayer.html#dataBinding">data binding</a> which occurs when you bind request parameters onto an instance such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> user = <span class="keyword">new</span> User(params)</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">if</span> (user.hasErrors()) {
<span class="keyword">if</span> (user.errors.hasFieldErrors(<span class="string"><span class="delimiter">&quot;</span><span class="content">login</span><span class="delimiter">&quot;</span></span>)) {
println user.errors.getFieldError(<span class="string"><span class="delimiter">&quot;</span><span class="content">login</span><span class="delimiter">&quot;</span></span>).rejectedValue
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The second phase of validation happens when you call <a href="../ref/Domain%20Classes/validate.html">validate</a> or <a href="../ref/Domain%20Classes/save.html">save</a>. This is when Grails will validate the bound values against the <a href="../ref/Domain%20Classes/constraints.html">constraints</a> you defined. For example, by default the <a href="../ref/Domain%20Classes/save.html">save</a> method calls <code>validate</code> before executing, allowing you to write code like:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">if</span> (user.save()) {
<span class="keyword">return</span> user
}
<span class="keyword">else</span> {
user.errors.allErrors.each {
println <span class="local-variable">it</span>
}
}</code></pre>
</div>
</div>
</div>
<h2 id="sharingConstraints">12.3 Sharing Constraints Between Classes</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/validation/sharingConstraints.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>A common pattern in Grails is to use <a href="theWebLayer.html#commandObjects">Command Objects</a> for validating user-submitted data and then copy the properties of the command object to the relevant domain classes. This often means that your command objects and domain classes share properties and their constraints. You could manually copy and paste the constraints between the two, but that&#8217;s a very error-prone approach. Instead, make use of Grails' global constraints and import mechanism.</p>
</div>
<div class="sect2">
<h3 id="_global_constraints">Global Constraints</h3>
<div class="paragraph">
<p>In addition to defining constraints in domain classes, command objects and <a href="#validationNonDomainAndCommandObjectClasses">other validateable classes</a>, you can also define them in <code>grails-app/conf/application.groovy</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails.gorm.default.constraints = {
<span class="string"><span class="delimiter">'</span><span class="content">*</span><span class="delimiter">'</span></span>(<span class="key">nullable</span>: <span class="predefined-constant">true</span>, <span class="key">size</span>: <span class="integer">1</span>..<span class="integer">20</span>)
myShared(<span class="key">nullable</span>: <span class="predefined-constant">false</span>, <span class="key">blank</span>: <span class="predefined-constant">false</span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>These constraints are not attached to any particular classes, but they can be easily referenced from any validateable class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">User</span> {
...
static constraints = {
login <span class="key">shared</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">myShared</span><span class="delimiter">&quot;</span></span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note the use of the <code>shared</code> argument, whose value is the name of one of the constraints defined in <code>grails.gorm.default.constraints</code>. Despite the name of the configuration setting, you can reference these shared constraints from any validateable class, such as command objects.</p>
</div>
<div class="paragraph">
<p>The '*' constraint is a special case: it means that the associated constraints ('nullable' and 'size' in the above example) will be applied to all properties in all validateable classes. These defaults can be overridden by the constraints declared in a validateable class.</p>
</div>
</div>
<div class="sect2">
<h3 id="_importing_constraints">Importing Constraints</h3>
<div class="paragraph">
<p>Grails 2 introduced an alternative approach to sharing constraints that allows you to import a set of constraints from one class into another.</p>
</div>
<div class="paragraph">
<p>Let&#8217;s say you have a domain class like so:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">User</span> {
<span class="predefined-type">String</span> firstName
<span class="predefined-type">String</span> lastName
<span class="predefined-type">String</span> passwordHash
<span class="directive">static</span> constraints = {
firstName <span class="key">blank</span>: <span class="predefined-constant">false</span>, <span class="key">nullable</span>: <span class="predefined-constant">false</span>
lastName <span class="key">blank</span>: <span class="predefined-constant">false</span>, <span class="key">nullable</span>: <span class="predefined-constant">false</span>
passwordHash <span class="key">blank</span>: <span class="predefined-constant">false</span>, <span class="key">nullable</span>: <span class="predefined-constant">false</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You then want to create a command object, <code>UserCommand</code>, that shares some of the properties of the domain class and the corresponding constraints. You do this with the <code>importFrom()</code> method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">UserCommand</span> {
<span class="predefined-type">String</span> firstName
<span class="predefined-type">String</span> lastName
<span class="predefined-type">String</span> password
<span class="predefined-type">String</span> confirmPassword
<span class="directive">static</span> constraints = {
importFrom User
password <span class="key">blank</span>: <span class="predefined-constant">false</span>, <span class="key">nullable</span>: <span class="predefined-constant">false</span>
confirmPassword <span class="key">blank</span>: <span class="predefined-constant">false</span>, <span class="key">nullable</span>: <span class="predefined-constant">false</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will import all the constraints from the <code>User</code> domain class and apply them to <code>UserCommand</code>. The import will ignore any constraints in the source class (<code>User</code>) that don&#8217;t have corresponding properties in the importing class (<code>UserCommand</code>). In the above example, only the 'firstName' and 'lastName' constraints will be imported into <code>UserCommand</code> because those are the only properties shared by the two classes.</p>
</div>
<div class="paragraph">
<p>If you want more control over which constraints are imported, use the <code>include</code> and <code>exclude</code> arguments. Both of these accept a list of simple or regular expression strings that are matched against the property names in the source constraints. So for example, if you only wanted to import the 'lastName' constraint you would use:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">...
static constraints = {
importFrom User, <span class="key">include</span>: [<span class="string"><span class="delimiter">&quot;</span><span class="content">lastName</span><span class="delimiter">&quot;</span></span>]
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>or if you wanted all constraints that ended with 'Name':</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">...
static constraints = {
importFrom User, <span class="key">include</span>: [<span class="regexp"><span class="delimiter">/</span><span class="content">.*Name</span><span class="delimiter">/</span></span>]
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Of course, <code>exclude</code> does the reverse, specifying which constraints should <em>not</em> be imported.</p>
</div>
</div>
<a name="10.3 Validation on the Client"><!-- Legacy link --></a>
<h2 id="validationOnTheClient">12.4 Validation on the Client</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/validation/validationOnTheClient.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_displaying_errors">Displaying Errors</h4>
<div class="paragraph">
<p>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="http://gsp.grails.org/latest/ref/Tags/renderErrors.html">renderErrors</a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:renderErrors</span> <span class="attribute-name">bean</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${user}</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>If you need more control you can use <a href="http://gsp.grails.org/latest/ref/Tags/hasErrors.html">hasErrors</a> and <a href="http://gsp.grails.org/latest/ref/Tags/eachError.html">eachError</a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:hasErrors</span> <span class="attribute-name">bean</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${user}</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
<span class="tag">&lt;ul&gt;</span>
<span class="tag">&lt;g:eachError</span> <span class="attribute-name">var</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">err</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">bean</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${user}</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
<span class="tag">&lt;li&gt;</span>${err}<span class="tag">&lt;/li&gt;</span>
<span class="tag">&lt;/g:eachError&gt;</span>
<span class="tag">&lt;/ul&gt;</span>
<span class="tag">&lt;/g:hasErrors&gt;</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_highlighting_errors">Highlighting Errors</h4>
<div class="paragraph">
<p>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="http://gsp.grails.org/latest/ref/Tags/hasErrors.html">hasErrors</a> by invoking it as a method. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;div</span> <span class="attribute-name">class</span>=<span class="string"><span class="delimiter">'</span><span class="content">value ${hasErrors(bean:user,field:</span><span class="delimiter">'</span></span><span class="attribute-name">login</span><span class="error">'</span><span class="error">,</span><span class="error">'</span><span class="attribute-name">errors</span><span class="error">'</span><span class="error">)</span><span class="error">}</span><span class="error">'</span><span class="tag">&gt;</span>
<span class="tag">&lt;input</span> <span class="attribute-name">type</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">text</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">login</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${fieldValue(bean:user,field:'login')}</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span>
<span class="tag">&lt;/div&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
</div>
<div class="sect3">
<h4 id="_retrieving_input_values">Retrieving Input Values</h4>
<div class="paragraph">
<p>Each error is actually an instance of the <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/FieldError.html">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">fieldValue</a> tag:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;input</span> <span class="attribute-name">type</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">text</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">login</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${fieldValue(bean:user,field:'login')}</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>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.</p>
</div>
</div>
<a name="10.4 Validation and Internationalization"><!-- Legacy link --></a>
<h2 id="validationAndInternationalization">12.5 Validation and Internationalization</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/validation/validationAndInternationalization.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Another important thing to note about errors in Grails is that error messages are not hard coded anywhere. The <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/FieldError.html">FieldError</a> class in Spring resolves messages from message bundles using Grails' <a href="i18n.html">i18n</a> support.</p>
</div>
<div class="sect3">
<h4 id="_constraints_and_message_codes">Constraints and Message Codes</h4>
<div class="paragraph">
<p>The codes themselves are dictated by a convention. For example consider the constraints we looked at earlier:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.mycompany.myapp
<span class="type">class</span> <span class="class">User</span> {
...
static constraints = {
login <span class="key">size</span>: <span class="integer">5</span>..<span class="integer">15</span>, <span class="key">blank</span>: <span class="predefined-constant">false</span>, <span class="key">unique</span>: <span class="predefined-constant">true</span>
password <span class="key">size</span>: <span class="integer">5</span>..<span class="integer">15</span>, <span class="key">blank</span>: <span class="predefined-constant">false</span>
email <span class="key">email</span>: <span class="predefined-constant">true</span>, <span class="key">blank</span>: <span class="predefined-constant">false</span>
age <span class="key">min</span>: <span class="integer">18</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If a constraint is violated, Grails looks by convention for a message code:</p>
</div>
<table class="tableblock frame-all grid-all spread">
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">Constraint</th>
<th class="tableblock halign-left valign-top">Error Code</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="../ref/Constraints/blank.html">blank</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>className.propertyName.blank</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="../ref/Constraints/creditCard.html">creditCard</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>className.propertyName.creditCard.invalid</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="../ref/Constraints/email.html">email</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>className.propertyName.email.invalid</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="../ref/Constraints/inList.html">inList</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>className.propertyName.not.inList</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="../ref/Constraints/matches.html">matches</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>className.propertyName.matches.invalid</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="../ref/Constraints/max.html">max</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>className.propertyName.max.exceeded</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="../ref/Constraints/maxSize.html">maxSize</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>className.propertyName.maxSize.exceeded</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="../ref/Constraints/min.html">min</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>className.propertyName.min.notmet</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="../ref/Constraints/minSize.html">minSize</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>className.propertyName.minSize.notmet</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="../ref/Constraints/notEqual.html">notEqual</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>className.propertyName.notEqual</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="../ref/Constraints/nullable.html">nullable</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>className.propertyName.nullable</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="../ref/Constraints/range.html">range</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>className.propertyName.range.toosmall</code> or <code>className.propertyName.range.toobig</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="../ref/Constraints/size.html">size</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>className.propertyName.size.toosmall</code> or <code>className.propertyName.size.toobig</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="../ref/Constraints/unique.html">unique</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>className.propertyName.unique</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="../ref/Constraints/url.html">url</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>className.propertyName.url.invalid</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="../ref/Constraints/validator.html">validator</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>classname.propertyName.</code> + String returned by Closure</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">user.login.blank=Your login name must be specified!</code></pre>
</div>
</div>
<div class="paragraph">
<p>The class name is looked for both with and without a package, with the packaged version taking precedence. So for example, <code>com.mycompany.myapp.User.login.blank</code> will be used before <code>user.login.blank</code>. This allows for cases where your domain class message codes clash with a plugin&#8217;s.</p>
</div>
<div class="paragraph">
<p>For a reference on what codes are for which constraints refer to the reference guide for each constraint (e.g. <a href="../ref/Constraints/blank.html">blank</a>).</p>
</div>
</div>
<div class="sect3">
<h4 id="_displaying_messages">Displaying Messages</h4>
<div class="paragraph">
<p>The <a href="http://gsp.grails.org/latest/ref/Tags/renderErrors.html">renderErrors</a> tag will automatically look up messages for you using the <a href="http://gsp.grails.org/latest/ref/Tags/message.html">message</a> tag. If you need more control of rendering you can handle this yourself:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:hasErrors</span> <span class="attribute-name">bean</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${user}</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
<span class="tag">&lt;ul&gt;</span>
<span class="tag">&lt;g:eachError</span> <span class="attribute-name">var</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">err</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">bean</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${user}</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
<span class="tag">&lt;li&gt;</span><span class="tag">&lt;g:message</span> <span class="attribute-name">error</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${err}</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span><span class="tag">&lt;/li&gt;</span>
<span class="tag">&lt;/g:eachError&gt;</span>
<span class="tag">&lt;/ul&gt;</span>
<span class="tag">&lt;/g:hasErrors&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>In this example within the body of the <a href="http://gsp.grails.org/latest/ref/Tags/eachError.html">eachError</a> tag we use the <a href="http://gsp.grails.org/latest/ref/Tags/message.html">message</a> tag in combination with its <code>error</code> argument to read the message for the given error.</p>
</div>
</div>
<a name="10.5 Validation Non Domain and Command Object Classes"><!-- Legacy link --></a>
<h2 id="validationNonDomainAndCommandObjectClasses">12.6 Applying Validation to Other Classes</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/validation/validationNonDomainAndCommandObjectClasses.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p><a href="GORM.html">Domain classes</a> and <a href="theWebLayer.html#commandObjects">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>
</div>
<div class="sect3">
<h4 id="_the_validateable_trait">The Validateable Trait</h4>
<div class="paragraph">
<p>Classes which define the static <code>constraints</code> property and implement the <a href="https://grails.apache.org/docs/3.3.7/api/grails/validation/Validateable.html">Validateable</a> trait will be validateable. Consider this example:</p>
</div>
<div class="listingblock">
<div class="title">src/main/groovy/com/mycompany/myapp/User.groovy</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> com.mycompany.myapp
<span class="keyword">import</span> <span class="include">grails.validation.Validateable</span>
<span class="type">class</span> <span class="class">User</span> <span class="directive">implements</span> Validateable {
...
static constraints = {
login <span class="key">size</span>: <span class="integer">5</span>..<span class="integer">15</span>, <span class="key">blank</span>: <span class="predefined-constant">false</span>, <span class="key">unique</span>: <span class="predefined-constant">true</span>
password <span class="key">size</span>: <span class="integer">5</span>..<span class="integer">15</span>, <span class="key">blank</span>: <span class="predefined-constant">false</span>
email <span class="key">email</span>: <span class="predefined-constant">true</span>, <span class="key">blank</span>: <span class="predefined-constant">false</span>
age <span class="key">min</span>: <span class="integer">18</span>
}
}</code></pre>
</div>
</div>
<div class="sect4">
<h5 id="_programmatic_access">Programmatic access</h5>
<div class="paragraph">
<p>Accessing the constraints on a validateable object is slightly different. You can access a command object&#8217;s constraints programmatically in another context by accessing the <code>constraintsMap</code> static property of the class. That property is an instance of <code>Map&lt;String, <a href="https://grails.apache.org/docs/3.3.7/api/grails/validation/ConstrainedProperty.html">ConstrainedProperty</a>&gt;</code></p>
</div>
<div class="paragraph">
<p>In the example above, accessing <code>User.constraintsMap.login.blank</code> would yield <code>false</code>, while
<code>User.constraintsMap.login.unique</code> would yield <code>true</code>.</p>
</div>
</div>
</div>
<a name="11. The Service Layer"><!-- Legacy link --></a>
<h1 id="services">13 The Service Layer</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/services.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="sect3">
<h4 id="_creating_a_service">Creating a Service</h4>
<div class="paragraph">
<p>You can create a Grails service by running the <a href="../ref/Command%20Line/create-service.html">create-service</a> command from the root of your project in a terminal window:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails create-service helloworld.simple</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
If no package is specified with the create-service script, Grails automatically uses the <code>grails.defaultPackage</code> defined in <code>grails-app/conf/application.yml</code> as the package name.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The above example will create a service at the location <code>grails-app/services/helloworld/SimpleService.groovy</code>. A service&#8217;s name ends with the convention <code>Service</code>, other than that a service is a plain Groovy class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> helloworld
<span class="type">class</span> <span class="class">SimpleService</span> {
}</code></pre>
</div>
</div>
</div>
<a name="11.1 Declarative Transactions"><!-- Legacy link --></a>
<h2 id="declarativeTransactions">13.1 Declarative Transactions</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/services/declarativeTransactions.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect2">
<h3 id="_declarative_transactions">Declarative Transactions</h3>
<div class="paragraph">
<p>Services are typically involved with coordinating logic between <a href="GORM.html">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%20Classes/withTransaction.html">withTransaction</a> method, however this is repetitive and doesn&#8217;t fully leverage the power of Spring&#8217;s underlying transaction abstraction.</p>
</div>
<div class="paragraph">
<p>Services enable transaction demarcation, which is a declarative way of defining which methods are to be made transactional. To enable transactions on a service use the <code>Transactional</code> transform:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.gorm.transactions.*</span>
<span class="annotation">@Transactional</span>
<span class="type">class</span> <span class="class">CountryService</span> {
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The result is that all methods are wrapped in a transaction and automatic rollback occurs if a method throws an exception (both Checked or Runtime exceptions) or an Error. The propagation level of the transaction is by default set to <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/transaction/TransactionDefinition.html#PROPAGATION_REQUIRED">PROPAGATION_REQUIRED</a>.</p>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
Version Grails 3.2.0 was the first version to use GORM 6 by default. Checked exceptions did not roll back transactions before GORM 6. Only a method which threw a runtime exception (i.e. one that extends RuntimeException) rollbacked a transaction.
</td>
</tr>
</table>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
Warning: <a href="#dependencyInjectionServices">dependency injection</a> is the <strong>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>
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_the_transactional_annotation_vs_the_transactional_property">The Transactional annotation vs the transactional property</h4>
<div class="paragraph">
<p>In versions of Grails prior to Grails 3.1, Grails created Spring proxies and used the <code>transactional</code> property to enable and disable proxy creation. These proxies are disabled by default in applications created with Grails 3.1 and above in favor of the <code>@Transactional</code> transformation.</p>
</div>
<div class="paragraph">
<p>For versions of Grails 3.1.x and 3.2.x, if you wish to renable this feature (not recommended) then you must set <code>grails.spring.transactionManagement</code> to true or remove the configuration in <code>grails-app/conf/application.yml</code> or <code>grails-app/conf/application.groovy</code>.</p>
</div>
<div class="paragraph">
<p>In Grails 3.3.x Spring proxies for transaction management has been dropped completely, and you must use Grails' AST transforms. In Grails 3.3.x, if you wish to continue to use Spring proxies for transaction management you will have to configure them manually, using the appropriate Spring configuration.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
In addition, prior to Grails 3.1 services were transactional by default, as of Grails 3.1 they are only transactional if the <code>@Transactional</code> transformation is applied.
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_custom_transaction_configuration">Custom Transaction Configuration</h3>
<div class="paragraph">
<p>Grails also provides <code>@Transactional</code> and <code>@NotTransactional</code> annotations for cases where you need more fine-grained control over transactions at a per-method level or need to specify an alternative propagation level. For example, the <code>@NotTransactional</code> annotation can be used to mark a particular method to be skipped when a class is annotated with <code>@Transactional</code>.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
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.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.gorm.transactions.Transactional</span>
<span class="type">class</span> <span class="class">BookService</span> {
<span class="annotation">@Transactional</span>(readOnly = <span class="predefined-constant">true</span>)
<span class="keyword">def</span> <span class="function">listBooks</span>() {
<span class="predefined-type">Book</span>.list()
}
<span class="annotation">@Transactional</span>
<span class="keyword">def</span> <span class="function">updateBook</span>() {
<span class="comment">// ...</span>
}
<span class="keyword">def</span> <span class="function">deleteBook</span>() {
<span class="comment">// ...</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also annotate the class to define the default transaction behavior for the whole service, and then override that default per-method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.gorm.transactions.Transactional</span>
<span class="annotation">@Transactional</span>
<span class="type">class</span> <span class="class">BookService</span> {
<span class="keyword">def</span> <span class="function">listBooks</span>() {
<span class="predefined-type">Book</span>.list()
}
<span class="keyword">def</span> <span class="function">updateBook</span>() {
<span class="comment">// ...</span>
}
<span class="keyword">def</span> <span class="function">deleteBook</span>() {
<span class="comment">// ...</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.gorm.transactions.Transactional</span>
<span class="annotation">@Transactional</span>
<span class="type">class</span> <span class="class">BookService</span> {
<span class="annotation">@Transactional</span>(readOnly = <span class="predefined-constant">true</span>)
<span class="keyword">def</span> <span class="function">listBooks</span>() {
<span class="predefined-type">Book</span>.list()
}
<span class="keyword">def</span> <span class="function">updateBook</span>() {
<span class="comment">// ...</span>
}
<span class="keyword">def</span> <span class="function">deleteBook</span>() {
<span class="comment">// ...</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Although <code>updateBook</code> and <code>deleteBook</code> aren&#8217;t annotated in this example, they inherit the configuration from the class-level annotation.</p>
</div>
<div class="paragraph">
<p>For more information refer to the section of the Spring user guide on <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html#transaction-declarative-annotations">Using @Transactional</a>.</p>
</div>
<div class="paragraph">
<p>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.</p>
</div>
<div class="sect3">
<h4 id="_transaction_status">Transaction status</h4>
<div class="paragraph">
<p>An instance of <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/transaction/TransactionStatus.html">TransactionStatus</a> is available by default in Grails transactional service methods.</p>
</div>
<div class="paragraph">
<p>Example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.gorm.transactions.Transactional</span>
<span class="annotation">@Transactional</span>
<span class="type">class</span> <span class="class">BookService</span> {
<span class="keyword">def</span> <span class="function">deleteBook</span>() {
transactionStatus.setRollbackOnly()
}
}</code></pre>
</div>
</div>
</div>
</div>
<a name="11.1.1 Transactions Multi-DataSource"><!-- Legacy link --></a>
<h2 id="transactionsMultiDataSource">13.1.1 Transactions and Multi-DataSources</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/services/declarativeTransactions/transactionsMultiDataSource.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Given two domain classes such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Movie</span> {
<span class="predefined-type">String</span> title
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Book</span> {
<span class="predefined-type">String</span> title
<span class="directive">static</span> mapping = {
datasource <span class="string"><span class="delimiter">'</span><span class="content">books</span><span class="delimiter">'</span></span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can supply the desired data source to <code>@Transactional</code> or <code>@ReadOnly</code> annotations.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.gorm.transactions.ReadOnly</span>
<span class="keyword">import</span> <span class="include">grails.gorm.transactions.Transactional</span>
<span class="keyword">import</span> <span class="include">groovy.transform.CompileStatic</span>
<span class="annotation">@CompileStatic</span>
<span class="type">class</span> <span class="class">BookService</span> {
<span class="annotation">@ReadOnly</span>(<span class="string"><span class="delimiter">'</span><span class="content">books</span><span class="delimiter">'</span></span>)
<span class="predefined-type">List</span>&lt;<span class="predefined-type">Book</span>&gt; findAll() {
<span class="predefined-type">Book</span>.where {}.findAll()
}
<span class="annotation">@Transactional</span>(<span class="string"><span class="delimiter">'</span><span class="content">books</span><span class="delimiter">'</span></span>)
<span class="type">void</span> save(<span class="predefined-type">String</span> title) {
<span class="predefined-type">Book</span> book = <span class="keyword">new</span> <span class="predefined-type">Book</span>(<span class="key">title</span>: title)
book.save()
book
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="annotation">@CompileStatic</span>
<span class="type">class</span> <span class="class">MovieService</span> {
<span class="annotation">@ReadOnly</span>
<span class="predefined-type">List</span>&lt;Movie&gt; findAll() {
Movie.where {}.findAll()
}
}</code></pre>
</div>
</div>
<a name="11.1.1 Transactions Rollback and the Session"><!-- Legacy link --></a>
<h2 id="transactionsRollbackAndTheSession">13.1.2 Transactions Rollback and the Session</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/services/declarativeTransactions/transactionsRollbackAndTheSession.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect2">
<h3 id="_understanding_transactions_and_the_hibernate_session">Understanding Transactions and the Hibernate Session</h3>
<div class="paragraph">
<p>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 a <code>LazyInitializationException</code>.</p>
</div>
<div class="paragraph">
<p>To understand why it is important that the Hibernate session is cleared. Consider the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Author</span> {
<span class="predefined-type">String</span> name
<span class="predefined-type">Integer</span> age
<span class="directive">static</span> hasMany = [<span class="key">books</span>: <span class="predefined-type">Book</span>]
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you were to save two authors using consecutive transactions as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">Author.withTransaction { status -&gt;
<span class="keyword">new</span> Author(<span class="key">name</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">Stephen King</span><span class="delimiter">&quot;</span></span>, <span class="key">age</span>: <span class="integer">40</span>).save()
status.setRollbackOnly()
}
Author.withTransaction { status -&gt;
<span class="keyword">new</span> Author(<span class="key">name</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">Stephen King</span><span class="delimiter">&quot;</span></span>, <span class="key">age</span>: <span class="integer">40</span>).save()
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>It can, however, be frustrating to get a <code>LazyInitializationException</code> due to the session being cleared.</p>
</div>
<div class="paragraph">
<p>For example, consider the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">AuthorService</span> {
<span class="type">void</span> updateAge(id, <span class="type">int</span> age) {
<span class="keyword">def</span> author = Author.get(id)
author.age = age
<span class="keyword">if</span> (author.isTooOld()) {
<span class="keyword">throw</span> <span class="keyword">new</span> AuthorException(<span class="string"><span class="delimiter">&quot;</span><span class="content">too old</span><span class="delimiter">&quot;</span></span>, author)
}
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">AuthorController</span> {
<span class="keyword">def</span> authorService
<span class="keyword">def</span> <span class="function">updateAge</span>() {
<span class="keyword">try</span> {
authorService.updateAge(params.id, params.int(<span class="string"><span class="delimiter">&quot;</span><span class="content">age</span><span class="delimiter">&quot;</span></span>))
}
<span class="keyword">catch</span>(e) {
render <span class="string"><span class="delimiter">&quot;</span><span class="content">Author books </span><span class="inline"><span class="inline-delimiter">${</span>e.author.books<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the above example the transaction will be rolled back if the age of the <code>Author</code> 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>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">AuthorService</span> {
...
void updateAge(id, <span class="type">int</span> age) {
<span class="keyword">def</span> author = Author.findById(id, [<span class="key">fetch</span>:[<span class="key">books</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">eager</span><span class="delimiter">&quot;</span></span>]])
...</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this example the <code>books</code> association will be queried when retrieving the <code>Author</code>.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
This is the optimal solution as it requires fewer queries then the following suggested solutions.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Another solution is to redirect the request after a transaction rollback:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">AuthorController</span> {
AuthorService authorService
<span class="keyword">def</span> <span class="function">updateAge</span>() {
<span class="keyword">try</span> {
authorService.updateAge(params.id, params.int(<span class="string"><span class="delimiter">&quot;</span><span class="content">age</span><span class="delimiter">&quot;</span></span>))
}
<span class="keyword">catch</span>(e) {
flash.message = <span class="string"><span class="delimiter">&quot;</span><span class="content">Can't update age</span><span class="delimiter">&quot;</span></span>
redirect <span class="key">action</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">show</span><span class="delimiter">&quot;</span></span>, <span class="key">id</span>:params.id
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">AuthorController</span> {
<span class="keyword">def</span> authorService
<span class="keyword">def</span> <span class="function">updateAge</span>() {
<span class="keyword">try</span> {
authorService.updateAge(params.id, params.int(<span class="string"><span class="delimiter">&quot;</span><span class="content">age</span><span class="delimiter">&quot;</span></span>))
}
<span class="keyword">catch</span>(e) {
<span class="keyword">def</span> author = Author.read(params.id)
render <span class="string"><span class="delimiter">&quot;</span><span class="content">Author books </span><span class="inline"><span class="inline-delimiter">${</span>author.books<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>
}
}
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_validation_errors_and_rollback">Validation Errors and Rollback</h3>
<div class="paragraph">
<p>A common use case is to rollback a transaction if there are validation errors. For example consider this service:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.validation.ValidationException</span>
<span class="type">class</span> <span class="class">AuthorService</span> {
<span class="type">void</span> updateAge(id, <span class="type">int</span> age) {
<span class="keyword">def</span> author = Author.get(id)
author.age = age
<span class="keyword">if</span> (!author.validate()) {
<span class="keyword">throw</span> <span class="keyword">new</span> ValidationException(<span class="string"><span class="delimiter">&quot;</span><span class="content">Author is not valid</span><span class="delimiter">&quot;</span></span>, author.errors)
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.validation.ValidationException</span>
<span class="type">class</span> <span class="class">AuthorController</span> {
<span class="keyword">def</span> authorService
<span class="keyword">def</span> <span class="function">updateAge</span>() {
<span class="keyword">try</span> {
authorService.updateAge(params.id, params.int(<span class="string"><span class="delimiter">&quot;</span><span class="content">age</span><span class="delimiter">&quot;</span></span>))
}
<span class="keyword">catch</span> (ValidationException e) {
<span class="keyword">def</span> author = Author.read(params.id)
author.errors = e.errors
render <span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">edit</span><span class="delimiter">&quot;</span></span>, <span class="key">model</span>: [<span class="key">author</span>:author]
}
}
}</code></pre>
</div>
</div>
</div>
<a name="11.2 Scoped Services"><!-- Legacy link --></a>
<h2 id="scopedServices">13.2 Scoped Services</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/services/scopedServices.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>You can change this behaviour by placing a service in a particular scope. The supported scopes are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>prototype</code> - A new service is created every time it is injected into another class</p>
</li>
<li>
<p><code>request</code> - A new service will be created per request</p>
</li>
<li>
<p><code>flash</code> - A new service will be created for the current and next request only</p>
</li>
<li>
<p><code>flow</code> - In web flows the service will exist for the scope of the flow</p>
</li>
<li>
<p><code>conversation</code> - In web flows the service will exist for the scope of the conversation. ie a root flow and its sub flows</p>
</li>
<li>
<p><code>session</code> - A service is created for the scope of a user session</p>
</li>
<li>
<p><code>singleton</code> (default) - Only one instance of the service ever exists</p>
</li>
</ul>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
If your service is <code>flash</code>, <code>flow</code> or <code>conversation</code> scoped it must implement <code>java.io.Serializable</code> and can only be used in the context of a Web Flow.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>To enable one of the scopes, add a static scope property to your class whose value is one of the above, for example</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> scope = <span class="string"><span class="delimiter">&quot;</span><span class="content">flow</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="title">Upgrading</div>
<div class="paragraph">
<p>Starting with Grails 2.3, new applications are generated with configuration that defaults the scope of controllers to <code>singleton</code>.
If <code>singleton</code> controllers interact with <code>prototype</code> scoped services, the services effectively behave as per-controller singletons.
If non-singleton services are required, controller scope should be changed as well.</p>
</div>
<div class="paragraph">
<p>See <a href="theWebLayer.html#controllersAndScopes">Controllers and Scopes</a> in the user guide for more information.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_lazy_initialization">Lazy initialization</h4>
<div class="paragraph">
<p>You can also configure whether the service is lazily initialized. By default, this is set to <code>true</code>, but you can disable this and make initialization eager with the <code>lazyInit</code> property:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> lazyInit = <span class="predefined-constant">false</span></code></pre>
</div>
</div>
</div>
<a name="11.3 Dependency Injection and Services"><!-- Legacy link --></a>
<h2 id="dependencyInjectionServices">13.3 Dependency Injection and Services</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/services/dependencyInjectionServices.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_dependency_injection_basics">Dependency Injection Basics</h4>
<div class="paragraph">
<p>A key aspect of Grails services is the ability to use <a href="http://www.springframework.org/">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>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> {
<span class="keyword">def</span> bookService
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">AuthorService</span> {
BookService bookService
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
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>.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>See section 8.8 of the JavaBean specification for more information on de-capitalization rules.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Only the top level object is subjected to injection as traversing all nested objects to perform injection would be a performance issue.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Be careful when injecting the non-default datasources. For example, using this config:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="key">dataSources</span>:
<span class="key">dataSource</span>:
<span class="key">pooled</span>: <span class="predefined-constant">true</span>
<span class="key">jmxExport</span>: <span class="predefined-constant">true</span>
.....
secondary:
<span class="key">pooled</span>: <span class="predefined-constant">true</span>
<span class="key">jmxExport</span>: <span class="predefined-constant">true</span>
.....</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can inject the primary <code>dataSource</code> like you would expect:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="java"><span class="type">class</span> <span class="class">BookSqlService</span> {
def dataSource
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>But to inject the <code>secondary</code> datasource, you have to use Spring&#8217;s <code>Autowired</code> injection or <code>resources.groovy</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="java"><span class="type">class</span> <span class="class">BookSqlSecondaryService</span> {
<span class="annotation">@Autowired</span>
<span class="annotation">@Qualifier</span>(<span class="string"><span class="delimiter">'</span><span class="content">dataSource_secondary</span><span class="delimiter">'</span></span>)
def dataSource2
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_dependency_injection_and_services">Dependency Injection and Services</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">AuthorService</span> {
<span class="keyword">def</span> bookService
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_dependency_injection_and_domain_classes_tag_libraries">Dependency Injection and Domain Classes / Tag Libraries</h4>
<div class="paragraph">
<p>You can even inject services into domain classes and tag libraries, which can aid in the development of rich domain models and views:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Book</span> {
...
def bookService
<span class="keyword">def</span> <span class="function">buyBook</span>() {
bookService.buyBook(<span class="local-variable">this</span>)
}
}</code></pre>
</div>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
Since Grails 3.2.8 this is not enabled by default. If you want to enable it again, take a look at <a href="https://grails.apache.org/docs/latest/ref/Domain%20Classes/Usage.html#_spring_autowiring_of_domain_instances">Spring Autowiring of Domain Instance</a>
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_service_bean_names">Service Bean Names</h4>
<div class="paragraph">
<p>The default bean name which is associated with a service can be problematic if there are multiple services with the same name defined in different packages. For example consider the situation where an application defines a service class named <code>com.demo.ReportingService</code> and the application uses a plugin named <code>ReportingUtilities</code> and that plugin provides a service class named <code>com.reporting.util.ReportingService</code>.</p>
</div>
<div class="paragraph">
<p>The default bean name for each of those would be <code>reportingService</code> so they would conflict with each other. Grails manages this by changing the default bean name for services provided by plugins by prefixing the bean name with the plugin name.</p>
</div>
<div class="paragraph">
<p>In the scenario described above the <code>reportingService</code> bean would be an instance of the <code>com.demo.ReportingService</code> class defined in the application and the <code>reportingUtilitiesReportingService</code> bean would be an instance of the <code>com.reporting.util.ReportingService</code> class provided by the <code>ReportingUtilities</code> plugin.</p>
</div>
<div class="paragraph">
<p>For all service beans provided by plugins, if there are no other services with the same name within the application or other plugins in the application then a bean alias will be created which does not include the plugin name and that alias points to the bean referred to by the name that does include the plugin name prefix.</p>
</div>
<div class="paragraph">
<p>For example, if the <code>ReportingUtilities</code> plugin provides a service named <code>com.reporting.util.AuthorService</code> and there is no other <code>AuthorService</code> in the application or in any of the plugins that the application is using then there will be a bean named <code>reportingUtilitiesAuthorService</code> which is an instance of this <code>com.reporting.util.AuthorService</code> class and there will be a bean alias defined in the context named <code>authorService</code> which points to that same bean.</p>
</div>
</div>
<h1 id="staticTypeCheckingAndCompilation">14 Static Type Checking And Compilation</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/staticTypeCheckingAndCompilation.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Groovy is a dynamic language and by default Groovy uses a dynamic dispatch mechanism to carry out method calls and property access. This dynamic dispatch mechanism provides a lot of flexibility and power to the language. For example, it is possible to dynamically add methods to classes at runtime and it is possible to dynamically replace existing methods at runtime. Features like these are important and provide a lot of power to the language. However, there are times when you may want to disable this dynamic dispatch in favor of a more static dispatch mechanism and Groovy provides a way to do that. The way to tell the Groovy compiler that a particular class should compiled statically is to mark the class with the <a href="http://docs.groovy-lang.org/docs/latest/html/api/groovy/transform/CompileStatic.html">groovy.transform.CompileStatic</a> annotation as shown below.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">groovy.transform.CompileStatic</span>
<span class="annotation">@CompileStatic</span>
<span class="type">class</span> <span class="class">MyClass</span> {
<span class="comment">// this class will be statically compiled...</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>See <a href="http://docs.groovy-lang.org/latest/html/documentation/#_static_compilation">these notes on Groovy static compilation</a> for more details on how <code>CompileStatic</code> works and why you might want to use it.</p>
</div>
<div class="paragraph">
<p>One limitation of using <code>CompileStatic</code> is that when you use it you give up access to the power and flexibility offered by dynamic dispatch. For example, in Grails you would not be able to invoke a GORM dynamic finder from a class that is marked with <code>CompileStatic</code> because the compiler cannot verify that the dynamic finder method exists, because it doesn&#8217;t exist at compile time. It may be that you want to take advantage of Groovy&#8217;s static compilation benefits without giving up access to dynamic dispatch for Grails specific things like dynamic finders and this is where <a href="https://grails.apache.org/docs/3.3.7/api/grails/compiler/GrailsCompileStatic.html">grails.compiler.GrailsCompileStatic</a> comes in. <code>GrailsCompileStatic</code> behaves just like <code>CompileStatic</code> but is aware of certain Grails features and allows access to those specific features to be accessed dynamically.</p>
</div>
<h2 id="grailsCompileStatic">14.1 The GrailsCompileStatic Annotation</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/staticTypeCheckingAndCompilation/grailsCompileStatic.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_grailscompilestatic">GrailsCompileStatic</h4>
<div class="paragraph">
<p>The <code>GrailsCompileStatic</code> annotation may be applied to a class or methods within a class.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.compiler.GrailsCompileStatic</span>
<span class="annotation">@GrailsCompileStatic</span>
<span class="type">class</span> <span class="class">SomeClass</span> {
<span class="comment">// all of the code in this class will be statically compiled</span>
<span class="keyword">def</span> <span class="function">methodOne</span>() {
<span class="comment">// ...</span>
}
<span class="keyword">def</span> <span class="function">methodTwo</span>() {
<span class="comment">// ...</span>
}
<span class="keyword">def</span> <span class="function">methodThree</span>() {
<span class="comment">// ...</span>
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.compiler.GrailsCompileStatic</span>
<span class="type">class</span> <span class="class">SomeClass</span> {
<span class="comment">// methodOne and methodThree will be statically compiled</span>
<span class="comment">// methodTwo will be dynamically compiled</span>
<span class="annotation">@GrailsCompileStatic</span>
<span class="keyword">def</span> <span class="function">methodOne</span>() {
<span class="comment">// ...</span>
}
<span class="keyword">def</span> <span class="function">methodTwo</span>() {
<span class="comment">// ...</span>
}
<span class="annotation">@GrailsCompileStatic</span>
<span class="keyword">def</span> <span class="function">methodThree</span>() {
<span class="comment">// ...</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>It is possible to mark a class with <code>GrailsCompileStatic</code> and exclude specific methods by marking them with <code>GrailsCompileStatic</code> and specifying that the type checking should be skipped for that particular method as shown below.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.compiler.GrailsCompileStatic</span>
<span class="keyword">import</span> <span class="include">groovy.transform.TypeCheckingMode</span>
<span class="annotation">@GrailsCompileStatic</span>
<span class="type">class</span> <span class="class">SomeClass</span> {
<span class="comment">// methodOne and methodThree will be statically compiled</span>
<span class="comment">// methodTwo will be dynamically compiled</span>
<span class="keyword">def</span> <span class="function">methodOne</span>() {
<span class="comment">// ...</span>
}
<span class="annotation">@GrailsCompileStatic</span>(TypeCheckingMode.SKIP)
<span class="keyword">def</span> <span class="function">methodTwo</span>() {
<span class="comment">// ...</span>
}
<span class="keyword">def</span> <span class="function">methodThree</span>() {
<span class="comment">// ...</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Code that is marked with <code>GrailsCompileStatic</code> will all be statically compiled except for Grails specific interactions that cannot be statically compiled but that <code>GrailsCompileStatic</code> can identify as permissible for dynamic dispatch. These include things like invoking dynamic finders and DSL code in configuration blocks like constraints and mapping closures in domain classes.</p>
</div>
<div class="paragraph">
<p>Care must be taken when deciding to statically compile code. There are benefits associated with static compilation but in order to take advantage of those benefits you are giving up the power and flexibility of dynamic dispatch. For example if code is statically compiled it cannot take advantage of runtime metaprogramming enhancements which may be provided by plugins.</p>
</div>
</div>
<h2 id="grailsTypeChecked">14.2 The GrailsTypeChecked Annotation</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/staticTypeCheckingAndCompilation/grailsTypeChecked.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_grailstypechecked">GrailsTypeChecked</h4>
<div class="paragraph">
<p>The <a href="https://grails.apache.org/docs/3.3.7/api/grails/compiler/GrailsTypeChecked.html">grails.compiler.GrailsTypeChecked</a> annotation works a lot like the <code>GrailsCompileStatic</code> annotation except that it only enables static type checking, not static compilation. This affords compile time feedback for expressions which cannot be validated statically at compile time while still leaving dynamic dispatch in place for the class.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.compiler.GrailsTypeChecked</span>
<span class="annotation">@GrailsTypeChecked</span>
<span class="type">class</span> <span class="class">SomeClass</span> {
<span class="comment">// all of the code in this class will be statically type</span>
<span class="comment">// checked and will be dynamically dispatched at runtime</span>
<span class="keyword">def</span> <span class="function">methodOne</span>() {
<span class="comment">// ...</span>
}
<span class="keyword">def</span> <span class="function">methodTwo</span>() {
<span class="comment">// ...</span>
}
<span class="keyword">def</span> <span class="function">methodThree</span>() {
<span class="comment">// ...</span>
}
}</code></pre>
</div>
</div>
</div>
<a name="12. Testing"><!-- Legacy link --></a>
<h1 id="testing">15 Testing</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/testing.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>The first thing to be aware of is that all of the <code>create-*</code> and <code>generate-\*</code> commands create <code>unit</code> or <code>integration</code> tests automatically. For example if you run the <a href="../ref/Command%20Line/create-controller.html">create-controller</a> command as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails create-controller com.acme.app.simple</code></pre>
</div>
</div>
<div class="paragraph">
<p>Grails will create a controller at <code>grails-app/controllers/com/acme/app/SimpleController.groovy</code>, and also a unit test at <code>src/test/groovy/com/acme/app/SimpleControllerSpec.groovy</code>. What Grails won&#8217;t do however is populate the logic inside the test! That is left up to you.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
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.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_running_tests">Running Tests</h4>
<div class="paragraph">
<p>Tests are run with the <a href="../ref/Command%20Line/test-app.html">test-app</a> command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app</code></pre>
</div>
</div>
<div class="paragraph">
<p>The command will produce output such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">-------------------------------------------------------
Running Unit Tests...
Running test FooTests...FAILURE
Unit Tests Completed <span class="keyword">in</span> <span class="integer">464</span>ms ...
-------------------------------------------------------
Tests <span class="key">failed</span>: <span class="integer">0</span> errors, <span class="integer">1</span> failures</code></pre>
</div>
</div>
<div class="paragraph">
<p>whilst showing the reason for each test failure.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
You can force a clean before running tests by passing <code>-clean</code> to the <code>test-app</code> command.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>Using Grails' <a href="commandLine.html#interactiveMode">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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">open test-report</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also run your unit tests from within most IDEs.</p>
</div>
</div>
<div class="sect3">
<h4 id="_targeting_tests">Targeting Tests</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app SimpleController</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will run any tests for the class named <code>SimpleController</code>. Wildcards can be used&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app *Controller</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will test all classes ending in <code>Controller</code>. Package names can optionally be specified&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app some.org.*Controller</code></pre>
</div>
</div>
<div class="paragraph">
<p>or to run all tests in a package&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app some.org.*</code></pre>
</div>
</div>
<div class="paragraph">
<p>or to run all tests in a package including subpackages&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app some.org.**.*</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also target particular test methods&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app SimpleController.testLogin</code></pre>
</div>
</div>
<div class="paragraph">
<p>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&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app some.org.* SimpleController.testLogin BookController</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
In Grails 2.x, adding <code>-rerun</code> as an argument would only run those tests which failed in the previous test-app run. This argument is no longer supported.
</td>
</tr>
</table>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
In Grails 3.x, you might need to specify the package name before the class name, as well as append "Spec" to the end. For example, if you want to run the test for the ProductController, you should use <code>grails test-app *.ProductControllerSpec</code>. Note that the star can be used if you don&#8217;t want to type the whole package hierarchy.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_debugging">Debugging</h4>
<div class="paragraph">
<p>In order to debug your tests via a remote debugger, you can add <code>--debug-jvm</code> after <code>grails</code> in any commands, like so:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails --debug-jvm test-app</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will open the default Java remote debugging port, 5005, for you to attach a remote debugger from your editor / IDE of choice.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
This differs from Grails 2.3 and previous, where the <code>grails-debug</code> command existed.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_targeting_test_phases">Targeting Test Phases</h4>
<div class="paragraph">
<p>In addition to targeting certain tests, you can also target test <em>phases.</em> By default Grails has two testing phases <code>unit</code> and <code>integration.</code></p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Grails 2.x uses <code>phase:type</code> syntax. In Grails 3.0 it was removed, because it made no sense in Gradle context.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>To execute <code>unit</code> tests you can run:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app -unit</code></pre>
</div>
</div>
<div class="paragraph">
<p>To run <code>integration</code> tests you would run&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app -integration</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_targeting_tests_when_using_phases">Targeting Tests When Using Phases</h4>
<div class="paragraph">
<p>Test and phase targeting can be applied at the same time:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails test-app some.org.**.* -unit</code></pre>
</div>
</div>
<div class="paragraph">
<p>This would run all tests in the <code>unit</code> phase that are in the package <code>some.org</code> or a subpackage.</p>
</div>
</div>
<a name="12.1 Unit Testing"><!-- Legacy link --></a>
<h2 id="unitTesting">15.1 Unit Testing</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/testing/unitTesting.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>Since Grails 3.3, the <a href="https://testing.grails.org">Grails Testing Support Framework</a> is used for all unit tests. This support provides a set of traits. An example hello world test can be seen below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">spock.lang.Specification</span>
<span class="keyword">import</span> <span class="include">grails.testing.web.controllers.ControllerUnitTest</span>
<span class="type">class</span> <span class="class">HelloControllerTests</span> <span class="directive">extends</span> Specification <span class="directive">implements</span> ControllerUnitTest&lt;HelloController&gt; {
<span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">Test message action</span><span class="delimiter">&quot;</span></span>() {
<span class="key">when</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">The message action is invoked</span><span class="delimiter">&quot;</span></span>
controller.message()
<span class="key">then</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">Hello is returned</span><span class="delimiter">&quot;</span></span>
response.text == <span class="string"><span class="delimiter">'</span><span class="content">Hello</span><span class="delimiter">'</span></span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>For more information on writing tests with Grails Testing Support see the <a href="https://testing.grails.org">dedicated documentation</a>.</p>
</div>
<div class="paragraph">
<p>Versions of Grails below 3.2 used the <a href="https://grails-plugins.github.io/grails-test-mixin-plugin/latest/guide/index.html">Grails Test Mixin Framework</a> which was based on the <code>@TestMixin</code> AST transformation. This library has been superceded by the simpler and more IDE friendly trait based implementation. However you can still use it by adding the following dependency to your Grails application:</p>
</div>
<div class="listingblock">
<div class="title">build.gradle</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">testCompile <span class="string"><span class="delimiter">&quot;</span><span class="content">org.grails:grails-test-mixins:3.3.0.RC1</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>This may be useful if you are, for example, upgrading an existing application to Grails 3.3.x.</p>
</div>
<a name="12.2 Integration Testing"><!-- Legacy link --></a>
<h2 id="integrationTesting">15.2 Integration Testing</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/testing/integrationTesting.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Integration tests differ from unit tests in that you have full access to the Grails environment within the test. You can create an integration test using the <a href="../ref/Command%20Line/create-integration-test.html">create-integration-test</a> command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span> grails create-integration-test Example</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above command will create a new integration test at the location <code>src/integration-test/groovy/&lt;PACKAGE&gt;/ExampleSpec.groovy</code>.</p>
</div>
<div class="paragraph">
<p>Grails uses the test environment for integration tests and loads the application prior to the first test run. All tests use the same application state.</p>
</div>
<div class="sect3">
<h4 id="_transactions">Transactions</h4>
<div class="paragraph">
<p>Integration test methods run inside their own database transaction by default, which is rolled back at the end of each test method. This means that data saved during a test is not persisted to the database (which is shared across all tests). The default generated integration test template includes the <a href="https://grails.apache.org/docs/3.3.7/api/grails/transaction/Rollback.html">Rollback</a> annotation:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.testing.mixin.integration.Integration</span>
<span class="keyword">import</span> <span class="include">grails.gorm.transactions.*</span>
<span class="keyword">import</span> <span class="include">spock.lang.*</span>
<span class="annotation">@Integration</span>
<span class="annotation">@Rollback</span>
<span class="type">class</span> <span class="class">ExampleSpec</span> <span class="directive">extends</span> Specification {
...
void <span class="string"><span class="delimiter">&quot;</span><span class="content">test something</span><span class="delimiter">&quot;</span></span>() {
<span class="key">expect</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">fix me</span><span class="delimiter">&quot;</span></span>
<span class="predefined-constant">true</span> == <span class="predefined-constant">false</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>Rollback</code> annotation ensures that each test method runs in a transaction that is rolled back. Generally this is desirable because you do not want your tests depending on order or application state.</p>
</div>
<div class="paragraph">
<p>In Grails 3.0 tests rely on <code>grails.gorm.transactions.Rollback</code> annotation to bind the session in integration tests. Though each test method transaction is rolled back, the <code>setup()</code> method uses a separate transaction that is not rolled back.
Data will persist to the database and will need to be cleaned up manually if <code>setup()</code> sets up data and persists them as shown in the below sample:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.testing.mixin.integration.Integration</span>
<span class="keyword">import</span> <span class="include">grails.gorm.transactions.*</span>
<span class="keyword">import</span> <span class="include">spock.lang.*</span>
<span class="annotation">@Integration</span>
<span class="annotation">@Rollback</span>
<span class="type">class</span> <span class="class">BookSpec</span> <span class="directive">extends</span> Specification {
<span class="type">void</span> setup() {
<span class="comment">// Below line would persist and not roll back</span>
<span class="keyword">new</span> <span class="predefined-type">Book</span>(<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Grails in Action</span><span class="delimiter">'</span></span>).save(<span class="key">flush</span>: <span class="predefined-constant">true</span>)
}
<span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test something</span><span class="delimiter">&quot;</span></span>() {
<span class="key">expect</span>:
<span class="predefined-type">Book</span>.count() == <span class="integer">1</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>To automatically roll back setup logic, any persistence operations need to be called from the test method itself so that they are run within the test method&#8217;s rolled back transaction. Similar to usage of the <code>setupData()</code> method shown below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.testing.mixin.integration.Integration</span>
<span class="keyword">import</span> <span class="include">grails.gorm.transactions.*</span>
<span class="keyword">import</span> <span class="include">spock.lang.*</span>
<span class="annotation">@Integration</span>
<span class="annotation">@Rollback</span>
<span class="type">class</span> <span class="class">BookSpec</span> <span class="directive">extends</span> Specification {
<span class="type">void</span> setupData() {
<span class="comment">// Below line would roll back</span>
<span class="keyword">new</span> <span class="predefined-type">Book</span>(<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Grails in Action</span><span class="delimiter">'</span></span>).save(<span class="key">flush</span>: <span class="predefined-constant">true</span>)
}
<span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test something</span><span class="delimiter">&quot;</span></span>() {
<span class="key">given</span>:
setupData()
<span class="key">expect</span>:
<span class="predefined-type">Book</span>.count() == <span class="integer">1</span>
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_using_spring_s_rollback_annotation">Using Spring&#8217;s Rollback annotation</h4>
<div class="paragraph">
<p>Another transactional approach could be to use Spring&#8217;s <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/annotation/Rollback.html">@Rollback</a> instead.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.testing.mixin.integration.Integration</span>
<span class="keyword">import</span> <span class="include">org.springframework.test.annotation.Rollback</span>
<span class="keyword">import</span> <span class="include">spock.lang.*</span>
<span class="annotation">@Integration</span>
<span class="annotation">@Rollback</span>
<span class="type">class</span> <span class="class">BookSpec</span> <span class="directive">extends</span> Specification {
<span class="type">void</span> setup() {
<span class="keyword">new</span> <span class="predefined-type">Book</span>(<span class="key">name</span>: <span class="string"><span class="delimiter">'</span><span class="content">Grails in Action</span><span class="delimiter">'</span></span>).save(<span class="key">flush</span>: <span class="predefined-constant">true</span>)
}
<span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">test something</span><span class="delimiter">&quot;</span></span>() {
<span class="key">expect</span>:
<span class="predefined-type">Book</span>.count() == <span class="integer">1</span>
}
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
It isn&#8217;t possible to make <code>grails.gorm.transactions.Rollback</code> behave the same way as Spring&#8217;s Rollback annotation because <code>grails.gorm.transactions.Rollback</code> transforms the byte code of the class, eliminating the need for a proxy (which Spring&#8217;s version requires).
This has the downside that you cannot implement it differently for different cases (as Spring does for testing).
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_dirtiescontext">DirtiesContext</h4>
<div class="paragraph">
<p>If you do have a series of tests that will share state you can remove the <code>Rollback</code> and the last test in the suite should feature the <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/annotation/DirtiesContext.html">DirtiesContext</a> annotation which will shutdown the environment and restart it fresh (note that this will have an impact on test run times).</p>
</div>
</div>
<div class="sect3">
<h4 id="_autowiring">Autowiring</h4>
<div class="paragraph">
<p>To obtain a reference to a bean you can use the <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Autowired.html">Autowired</a> annotation. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">...
import org.springframework.beans.factory.annotation.*
<span class="annotation">@Integration</span>
<span class="annotation">@Rollback</span>
<span class="type">class</span> <span class="class">ExampleServiceSpec</span> <span class="directive">extends</span> Specification {
<span class="annotation">@Autowired</span>
ExampleService exampleService
...
void <span class="string"><span class="delimiter">&quot;</span><span class="content">Test example service</span><span class="delimiter">&quot;</span></span>() {
<span class="key">expect</span>:
exampleService.countExamples() == <span class="integer">0</span>
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_testing_controllers">Testing Controllers</h4>
<div class="paragraph">
<p>To integration test controllers it is recommended you use <a href="../ref/Command%20Line/create-functional-test.html">create-functional-test</a> command to create a Geb functional test. See the following section on functional testing for more information.</p>
</div>
</div>
<a name="12.3 Functional Testing"><!-- Legacy link --></a>
<h2 id="functionalTesting">15.3 Functional Testing</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/testing/functionalTesting.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Functional tests involve making HTTP requests against the running application and verifying the resultant behaviour. This is useful for end-to-end testing scenarios, such as making REST calls against a JSON API.</p>
</div>
<div class="paragraph">
<p>Grails by default ships with support for writing functional tests using the <a href="http://www.gebish.org">Geb framework</a>. To create a functional test you can use the <code>create-functional-test</code> command which will create a new functional test:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span> grails create-functional-test MyFunctional</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above command will create a new Spock spec called <code>MyFunctionalSpec.groovy</code> in the <code>src/integration-test/groovy</code> directory. The test is annotated with the <a href="https://grails.apache.org/docs/3.3.7/api/grails/test/mixin/integration/Integration.html">Integration</a> annotation to indicate it is an integration test and extends the <code>GebSpec</code> super class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="annotation">@Integration</span>
<span class="type">class</span> <span class="class">HomeSpec</span> <span class="directive">extends</span> GebSpec {
<span class="keyword">def</span> <span class="function">setup</span>() {
}
<span class="keyword">def</span> <span class="function">cleanup</span>() {
}
<span class="type">void</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">Test the home page renders correctly</span><span class="delimiter">&quot;</span></span>() {
<span class="key">when</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">The home page is visited</span><span class="delimiter">&quot;</span></span>
go <span class="string"><span class="delimiter">'</span><span class="content">/</span><span class="delimiter">'</span></span>
<span class="key">then</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">The title is correct</span><span class="delimiter">&quot;</span></span>
<span class="error">$</span>(<span class="string"><span class="delimiter">'</span><span class="content">title</span><span class="delimiter">'</span></span>).text() == <span class="string"><span class="delimiter">&quot;</span><span class="content">Welcome to Grails</span><span class="delimiter">&quot;</span></span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>When the test is run the application container will be loaded up in the background and you can send requests to the running application using the Geb API.</p>
</div>
<div class="paragraph">
<p>Note that the application is only loaded once for the entire test run, so functional tests share the state of the application across the whole suite.</p>
</div>
<div class="paragraph">
<p>In addition the application is loaded in the JVM as the test, this means that the test has full access to the application state and can interact directly with data services such as GORM to setup and cleanup test data.</p>
</div>
<div class="paragraph">
<p>The <code>Integration</code> annotation supports an optional <code>applicationClass</code> attribute which may be used to specify the application class to use for the functional test. The class must extend <a href="https://grails.apache.org/docs/3.3.7/api/grails/boot/config/GrailsAutoConfiguration.html">GrailsAutoConfiguration</a>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="annotation">@Integration</span>(applicationClass=com.demo.Application)
<span class="type">class</span> <span class="class">HomeSpec</span> <span class="directive">extends</span> GebSpec {
<span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If the <code>applicationClass</code> is not specified then the test runtime environment will attempt to locate the application class dynamically which can be problematic in multiproject builds where multiple application classes may be present.</p>
</div>
<div class="paragraph">
<p>When running the server port by default will be randomly assigned. The <code>Integration</code> annotation adds a property of <code>serverPort</code> to the test class that you can use if you want to know what port the application is running on this isn&#8217;t needed if you are extending the <code>GebSpec</code> as shown above but can be useful information.</p>
</div>
<div class="paragraph">
<p>If you want to run the tests on a fixed port (defined by the <code>server.port</code> configuration property), you need to manually annotate your test with <code>@SpringBootTest</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.testing.mixin.integration.Integration</span>
<span class="keyword">import</span> <span class="include">org.springframework.boot.test.context.SpringBootTest</span>
<span class="keyword">import</span> <span class="include">spock.lang.Specification</span>
<span class="annotation">@Integration</span>
<span class="annotation">@SpringBootTest</span>(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
<span class="type">class</span> <span class="class">MySpec</span> <span class="directive">extends</span> Specification {
<span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<a name="13. Internationalization"><!-- Legacy link --></a>
<h1 id="i18n">16 Internationalization</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/i18n.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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&#8217;s Locale. To quote the javadoc for the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html">Locale</a> class:</p>
</div>
<div class="quoteblock">
<blockquote>
<div class="paragraph">
<p>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&#8212;&#8203;the number should be formatted according to the customs/conventions of the user&#8217;s native country, region, or culture.</p>
</div>
</blockquote>
</div>
<div class="paragraph">
<p>A Locale is made up of a <a href="http://www.loc.gov/standards/iso639-2/php/English_list.php">language code</a> and a <a href="http://www.iso.org/iso/country_codes/iso_3166_code_lists/country_names_and_code_elements.htm">country code</a>. For example "en_US" is the code for US English, whilst "en_GB" is the code for British English.</p>
</div>
<a name="13.1 Understanding Message Bundles"><!-- Legacy link --></a>
<h2 id="understandingMessageBundles">16.1 Understanding Message Bundles</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/i18n/understandingMessageBundles.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>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:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>messages.properties</p>
</li>
<li>
<p>messages_da.properties</p>
</li>
<li>
<p>messages_de.properties</p>
</li>
<li>
<p>messages_es.properties</p>
</li>
<li>
<p>messages_fr.properties</p>
</li>
<li>
<p>&#8230;&#8203;</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>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 in. For example <code>messages_en_GB.properties</code> for British English.</p>
</div>
<a name="13.2 Changing Locales"><!-- Legacy link --></a>
<h2 id="changingLocales">16.2 Changing Locales</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/i18n/changingLocales.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="regexp"><span class="delimiter">/</span><span class="content">book</span><span class="delimiter">/</span></span>list?lang=es</code></pre>
</div>
</div>
<div class="paragraph">
<p>Grails will automatically switch the user&#8217;s locale and store it in a cookie so subsequent requests will have the new header.</p>
</div>
<a name="13.3 Reading Messages"><!-- Legacy link --></a>
<h2 id="readingMessages">16.3 Reading Messages</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/i18n/readingMessages.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_reading_messages_in_the_view">Reading Messages in the View</h4>
<div class="paragraph">
<p>The most common place that you need messages is inside the view. Use the <a href="http://gsp.grails.org/latest/ref/Tags/message.html">message</a> tag for this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:message</span> <span class="attribute-name">code</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">my.localized.content</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">my.localized.content=Hola, me llamo John. Hoy es domingo.</code></pre>
</div>
</div>
<div class="paragraph">
<p>Messages can also include arguments, for example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;g:message</span> <span class="attribute-name">code</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">my.localized.content</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">args</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">${ ['Juan', 'lunes'] }</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The message declaration specifies positional parameters which are dynamically specified:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">my.localized.content=Hola, me llamo {<span class="integer">0</span>}. Hoy es {<span class="integer">1</span>}.</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_reading_messages_in_grails_artifacts_with_messagesource">Reading Messages in Grails Artifacts with MessageSource</h4>
<div class="paragraph">
<p>In a Grails artifact, you can inject <code>messageSource</code> and use the method <code>getMessage</code> with the arguments: message code, message arguments, default message and locale to retrieve a message.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">org.springframework.context.MessageSource</span>
<span class="type">class</span> <span class="class">MyappController</span> {
MessageSource messageSource
<span class="keyword">def</span> <span class="function">show</span>() {
<span class="keyword">def</span> msg = messageSource.getMessage(<span class="string"><span class="delimiter">'</span><span class="content">my.localized.content</span><span class="delimiter">'</span></span>, [<span class="string"><span class="delimiter">'</span><span class="content">Juan</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">lunes</span><span class="delimiter">'</span></span>] <span class="keyword">as</span> <span class="predefined-type">Object</span><span class="type">[]</span>, <span class="string"><span class="delimiter">'</span><span class="content">Default Message</span><span class="delimiter">'</span></span>, request.locale)
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_reading_messages_in_controllers_and_tag_libraries_with_the_message_tag">Reading Messages in Controllers and Tag Libraries with the Message Tag</h4>
<div class="paragraph">
<p>Additionally, you can read a message inside Controllers and Tag Libraries with the <a href="http://gsp.grails.org/latest/ref/Tags/message.html">Message Tag</a>. However, using the message tag relies on GSP support which a Grails application may not necessarily have; e.g. a rest application.</p>
</div>
<div class="paragraph">
<p>In a controller, you can invoke tags as methods.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">show</span>() {
<span class="keyword">def</span> msg = message(<span class="key">code</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">my.localized.content</span><span class="delimiter">&quot;</span></span>, <span class="key">args</span>: [<span class="string"><span class="delimiter">'</span><span class="content">Juan</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">lunes</span><span class="delimiter">'</span></span>])
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The same technique can be used in <a href="theWebLayer.html#taglibs">tag libraries</a>, but if your tag library uses a custom <a href="theWebLayer.html#namespaces">namespace</a> then you must prefix the call with <code>g.</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> myTag = { attrs, body -&gt;
<span class="keyword">def</span> msg = g.message(<span class="key">code</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">my.localized.content</span><span class="delimiter">&quot;</span></span>, <span class="key">args</span>: [<span class="string"><span class="delimiter">'</span><span class="content">Juan</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">lunes</span><span class="delimiter">'</span></span>])
}</code></pre>
</div>
</div>
</div>
<a name="13.4 Scaffolding and i18n"><!-- Legacy link --></a>
<h2 id="scaffoldingAndI18n">16.4 Scaffolding and i18n</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/i18n/scaffoldingAndI18n.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails <a href="scaffolding.html">scaffolding</a> templates for controllers and views are fully i18n-aware. The GSPs use the <a href="http://gsp.grails.org/latest/ref/Tags/message.html">message</a> tag for labels, buttons etc. and controller <code>flash</code> messages use i18n to resolve locale-specific messages.</p>
</div>
<div class="paragraph">
<p>The scaffolding includes locale specific labels for domain classes and domain fields. For example, if you have a <code>Book</code> domain class with a <code>title</code> field:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Book</span> {
<span class="predefined-type">String</span> title
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The scaffolding will use labels with the following keys:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">book.label = Libro
book.title.label = T<span class="error">í</span>tulo del libro</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can use this property pattern if you&#8217;d like or come up with one of your own. There is nothing special about the use of the word <code>label</code> as part of the key other than it&#8217;s the convention used by the scaffolding.</p>
</div>
<a name="14. Security"><!-- Legacy link --></a>
<h1 id="security">17 Security</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/security.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="sect3">
<h4 id="_what_grails_automatically_does">What Grails Automatically Does</h4>
<div class="paragraph">
<p>Grails has a few built in safety mechanisms by default.</p>
</div>
<div class="ulist">
<ul>
<li>
<p>All standard database access via <a href="GORM.html">GORM</a> domain objects is automatically SQL escaped to prevent SQL injection attacks</p>
</li>
<li>
<p>The default <a href="scaffolding.html">scaffolding</a> templates HTML escape all data fields when displayed</p>
</li>
<li>
<p>Grails link creating tags (<a href="http://gsp.grails.org/latest/ref/Tags/link.html">link</a>, <a href="http://gsp.grails.org/latest/ref/Tags/form.html">form</a>, <a href="http://gsp.grails.org/latest/ref/Tags/createLink.html">createLink</a>, <a href="http://gsp.grails.org/latest/ref/Tags/createLinkTo.html">createLinkTo</a> and others) all use appropriate escaping mechanisms to prevent code injection</p>
</li>
<li>
<p>Grails provides <a href="#codecs">codecs</a> to let you trivially escape data when rendered as HTML, JavaScript and URLs to prevent injection attacks here.</p>
</li>
</ul>
</div>
</div>
<a name="14.1 Securing Against Attacks"><!-- Legacy link --></a>
<h2 id="securingAgainstAttacks">17.1 Securing Against Attacks</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/security/securingAgainstAttacks.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_sql_injection">SQL injection</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">vulnerable</span>() {
<span class="keyword">def</span> books = <span class="predefined-type">Book</span>.find(<span class="string"><span class="delimiter">&quot;</span><span class="content">from Book as b where b.title ='</span><span class="delimiter">&quot;</span></span> + params.title + <span class="string"><span class="delimiter">&quot;</span><span class="content">'</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>or the analogous call using a GString:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">vulnerable</span>() {
<span class="keyword">def</span> books = <span class="predefined-type">Book</span>.find(<span class="string"><span class="delimiter">&quot;</span><span class="content">from Book as b where b.title ='</span><span class="inline"><span class="inline-delimiter">${</span>params.title<span class="inline-delimiter">}</span></span><span class="content">'</span><span class="delimiter">&quot;</span></span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Do <strong>not</strong> do this. Use named or positional parameters instead to pass in parameters:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">safe</span>() {
<span class="keyword">def</span> books = <span class="predefined-type">Book</span>.find(<span class="string"><span class="delimiter">&quot;</span><span class="content">from Book as b where b.title = ?</span><span class="delimiter">&quot;</span></span>,
[params.title])
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>or</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">safe</span>() {
<span class="keyword">def</span> books = <span class="predefined-type">Book</span>.find(<span class="string"><span class="delimiter">&quot;</span><span class="content">from Book as b where b.title = :title</span><span class="delimiter">&quot;</span></span>,
[<span class="key">title</span>: params.title])
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_phishing">Phishing</h4>
<div class="paragraph">
<p>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>
</div>
</div>
<div class="sect3">
<h4 id="_xss_cross_site_scripting_injection">XSS - cross-site scripting injection</h4>
<div class="paragraph">
<p>It is important that your application verifies as much as possible that incoming requests were originated from your application and not from another site. It is also important to ensure that all data values rendered into views are escaped correctly. For example when rendering to HTML or XHTML you must ensure that people cannot maliciously inject JavaScript or other HTML into data or tags viewed by others.</p>
</div>
<div class="paragraph">
<p>Grails 2.3 and above include special support for automatically encoded data placed into GSP pages. See the documentation on <a href="#xssPrevention">Cross Site Scripting (XSS) prevention</a> for further information.</p>
</div>
<div class="paragraph">
<p>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>
</div>
</div>
<div class="sect3">
<h4 id="_cross_site_request_forgery">Cross-site request forgery</h4>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>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="theWebLayer.html#formtokens">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>
</div>
</div>
<div class="sect3">
<h4 id="_html_url_injection">HTML/URL injection</h4>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>HTML/URL injection is easily handled with the <a href="#codecs">codecs</a> supplied by Grails, and the tag libraries supplied by Grails all use <a href="#codecs">encodeAsURL</a> where appropriate. If you create your own tags that generate URLs you will need to be mindful of doing this too.</p>
</div>
</div>
<div class="sect3">
<h4 id="_denial_of_service">Denial of service</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">int</span> limit = <span class="integer">100</span>
<span class="keyword">def</span> safeMax = <span class="predefined-type">Math</span>.min(params.max?.toInteger() ?: limit, limit) <span class="comment">// limit to 100 results</span>
<span class="keyword">return</span> <span class="predefined-type">Book</span>.list(<span class="key">max</span>:safeMax)</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_guessable_ids">Guessable IDs</h4>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>Not doing this is "security through obscurity" which is inevitably breached, just like having a default password of "letmein" and so on.</p>
</div>
<div class="paragraph">
<p>You must assume that every unprotected URL is publicly accessible one way or another.</p>
</div>
</div>
<a name="13.2 Cross Site Scripting (XSS) Prevention"><!-- Legacy link --></a>
<h2 id="xssPrevention">17.2 Cross Site Scripting (XSS) Prevention</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/security/xssPrevention.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Cross Site Scripting (XSS) attacks are a common attack vector for web applications. They typically involve submitting HTML or Javascript code in a form such that when that code is displayed, the browser does something nasty. It could be as simple as popping up an alert box, or it could be much worse like for example one could <a href="https://blog.codinghorror.com/protecting-your-cookies-httponly/">access other users session cookies.</a></p>
</div>
<div class="paragraph">
<p>The solution is to escape all untrusted user input when it is displayed in a page. For example,</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">&lt;script&gt;alert(<span class="string"><span class="delimiter">'</span><span class="content">Got ya!</span><span class="delimiter">'</span></span>);&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">script&gt;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>will become</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">&amp;lt;script&amp;gt;alert(<span class="string"><span class="delimiter">'</span><span class="content">Got ya!</span><span class="delimiter">'</span></span>);&amp;lt;<span class="regexp"><span class="delimiter">/</span><span class="content">script&amp;gt;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>when rendered, nullifying the effects of the malicious input.</p>
</div>
<div class="paragraph">
<p>By default, Grails plays it safe and escapes all content in <code>${}</code> expressions in GSPs. All the standard GSP tags are also safe by default, escaping any relevant attribute values.</p>
</div>
<div class="paragraph">
<p>So what happens when you want to stop Grails from escaping some content? There are valid use cases for putting HTML into the database and rendering it as-is, as long as that content is <strong>trusted</strong>. In such cases, you can tell Grails that the content is safe as should be rendered raw, i.e. without any escaping:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">&lt;section&gt;<span class="error">$</span>{raw(page.content)}&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">section&gt;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>raw()</code> method you see here is available from controllers, tag libraries and GSP pages.</p>
</div>
<div class="paragraph">
<p><strong>XSS prevention is hard and requires a lot of developer attention</strong></p>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
Although Grails plays it safe by default, that is no guarantee that your application will be invulnerable to an XSS-style attack. Such an attack is less likely to succeed than would otherwise be the case, but developers should always be conscious of potential attack vectors and attempt to uncover vulnerabilities in the application during testing. It&#8217;s also easy to switch to an unsafe default, thereby increasing the risk of a vulnerability being introduced.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>There are more details about the XSS in <a href="https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet#XSS_Prevention_Rules">OWASP - XSS prevention rules</a> and <a href="https://www.owasp.org/index.php/Types_of_Cross-Site_Scripting">OWASP - Types of Cross-Site Scripting</a>. Types of XSS are: <a href="https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)#Stored_XSS_Attacks">Stored XSS</a>, <a href="https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)#Reflected_XSS_Attacks">Reflected XSS</a> and <a href="https://www.owasp.org/index.php/DOM_Based_XSS">DOM based XSS</a>. <a href="https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet">DOM based XSS prevention</a> is coming more important because of the popularity of Javascript client side templating and Single Page Apps.</p>
</div>
<div class="paragraph">
<p>Grails codecs are mainly for preventing stored and reflected XSS type of attacks. Grails 2.4 includes HTMLJS codec that assists in preventing some DOM based XSS attacks.</p>
</div>
<div class="paragraph">
<p>It&#8217;s difficult to make a solution that works for everyone, and so Grails provides a lot of flexibility with regard to fine-tuning how escaping works, allowing you to keep most of your application safe while switching off default escaping or changing the codec used for pages, tags, page fragments, and more.</p>
</div>
<div class="sect3">
<h4 id="_configuration">Configuration</h4>
<div class="paragraph">
<p>It is recommended that you review the configuration of a newly created Grails application to garner an understanding of XSS prevention works in Grails.</p>
</div>
<div class="paragraph">
<p>When you tag a cookie with the HttpOnly flag, it tells the browser that this particular cookie should only be accessed by the server. Any attempt to access the cookie from client script is strictly forbidden. This can be configured in the <code>application.yml</code> configuration file as seen below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="key">server</span>:
<span class="key">session</span>:
<span class="key">cookie</span>:
<span class="key">domain</span>: example.org
http-<span class="key">only</span>: <span class="predefined-constant">true</span>
<span class="key">path</span>: <span class="regexp"><span class="delimiter">/</span></span><span class="error">
</span> <span class="key">secure</span>: <span class="predefined-constant">true</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>GSP features the ability to automatically HTML encode GSP expressions, and as of Grails 2.3 this is the default configuration. The default configuration (found in <code>application.yml</code>) for a newly created Grails application can be seen below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="key">grails</span>:
<span class="key">views</span>:
<span class="key">gsp</span>:
<span class="key">encoding</span>: UTF-<span class="integer">8</span>
<span class="key">htmlcodec</span>: xml <span class="error">#</span> use xml escaping instead of HTML4 escaping
<span class="key">codecs</span>:
<span class="key">expression</span>: html <span class="error">#</span> escapes values inside <span class="error">$</span>{}
<span class="key">scriptlets</span>: html <span class="error">#</span> escapes output from scriptlets <span class="keyword">in</span> GSPs
<span class="key">taglib</span>: none <span class="error">#</span> escapes output from taglibs
<span class="key">staticparts</span>: none <span class="error">#</span> escapes output from <span class="directive">static</span> template parts</code></pre>
</div>
</div>
<div class="paragraph">
<p>GSP features several codecs that it uses when writing the page to the response. The codecs are configured in the <code>codecs</code> block and are described below:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>expression</code> - The expression codec is used to encode any code found within ${..} expressions. The default for newly created application is <code>html</code> encoding.</p>
</li>
<li>
<p><code>scriptlet</code> - Used for output from GSP scriplets (&lt;% %&gt;, &lt;%= %&gt; blocks). The default for newly created applications is <code>html</code> encoding</p>
</li>
<li>
<p><code>taglib</code> - Used to encode output from GSP tag libraries. The default is <code>none</code> for new applications, as typically it is the responsibility of the tag author to define the encoding of a given tag and by specifying <code>none</code> Grails remains backwards compatible with older tag libraries.</p>
</li>
<li>
<p><code>staticparts</code> - Used to encode the raw markup output by a GSP page. The default is <code>none</code>.</p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_double_encoding_prevention">Double Encoding Prevention</h4>
<div class="paragraph">
<p>Versions of Grails prior to 2.3, included the ability to set the default codec to <code>html</code>, however enabling this setting sometimes proved problematic when using existing plugins due to encoding being applied twice (once by the <code>html</code> codec and then again if the plugin manually called <code>encodeAsHTML</code>).</p>
</div>
<div class="paragraph">
<p>Grails 2.3 includes double encoding prevention so that when an expression is evaluated, it will not encode if the data has already been encoded (Example <code>${foo.encodeAsHTML()}</code>).</p>
</div>
</div>
<div class="sect3">
<h4 id="_raw_output">Raw Output</h4>
<div class="paragraph">
<p>If you are 100% sure that the value you wish to present on the page has not been received from user input, and you do not wish the value to be encoded then you can use the <code>raw</code> method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span>{raw(book.title)}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The 'raw' method is available in tag libraries, controllers and GSP pages.</p>
</div>
</div>
<div class="sect3">
<h4 id="_per_plugin_encoding">Per Plugin Encoding</h4>
<div class="paragraph">
<p>Grails also features the ability to control the codecs used on a per plugin basis. For example if you have a plugin named <code>foo</code> installed, then placing the following configuration in your <code>application.groovy</code> will disable encoding for only the <code>foo</code> plugin</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">foo.grails.views.gsp.codecs.expression = <span class="string"><span class="delimiter">&quot;</span><span class="content">none</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_per_page_encoding">Per Page Encoding</h4>
<div class="paragraph">
<p>You can also control the various codecs used to render a GSP page on a per page basis, using a page directive:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">&lt;%<span class="annotation">@page</span> expressionCodec=<span class="string"><span class="delimiter">&quot;</span><span class="content">none</span><span class="delimiter">&quot;</span></span> %&gt;</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_per_tag_library_encoding">Per Tag Library Encoding</h4>
<div class="paragraph">
<p>Each tag library created has the opportunity to specify a default codec used to encode output from the tag library using the "defaultEncodeAs" property:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> defaultEncodeAs = <span class="string"><span class="delimiter">'</span><span class="content">html</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Encoding can also be specified on a per tag basis using "encodeAsForTags":</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="directive">static</span> encodeAsForTags = [<span class="key">tagName</span>: <span class="string"><span class="delimiter">'</span><span class="content">raw</span><span class="delimiter">'</span></span>]</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_context_sensitive_encoding_switching">Context Sensitive Encoding Switching</h4>
<div class="paragraph">
<p>Certain tags require certain encodings and Grails features the ability to enable a codec only a certain part of a tag&#8217;s execution using the "withCodec" method. Consider for example the "&lt;g:javascript&gt;"" tag which allows you to embed JavaScript code in the page. This tag requires JavaScript encoding, not HTML coding for the execution of the body of the tag (but not for the markup that is output):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">out.println <span class="string"><span class="delimiter">'</span><span class="content">&lt;script type=&quot;text/javascript&quot;&gt;</span><span class="delimiter">'</span></span>
withCodec(<span class="string"><span class="delimiter">&quot;</span><span class="content">JavaScript</span><span class="delimiter">&quot;</span></span>) {
out &lt;&lt; body()
}
out.println()
out.println <span class="string"><span class="delimiter">'</span><span class="content">&lt;/script&gt;</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_forced_encoding_for_tags">Forced Encoding for Tags</h4>
<div class="paragraph">
<p>If a tag specifies a default encoding that differs from your requirements you can force the encoding for any tag by passing the optional 'encodeAs' attribute:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">&lt;<span class="key">g</span>:message code=<span class="string"><span class="delimiter">&quot;</span><span class="content">foo.bar</span><span class="delimiter">&quot;</span></span> encodeAs=<span class="string"><span class="delimiter">&quot;</span><span class="content">JavaScript</span><span class="delimiter">&quot;</span></span> /&gt;</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_default_encoding_for_all_output">Default Encoding for All Output</h4>
<div class="paragraph">
<p>The default configuration for new applications is fine for most use cases, and backwards compatible with existing plugins and tag libraries. However, you can also make your application even more secure by configuring Grails to always encode all output at the end of a response. This is done using the <code>filteringCodecForContentType</code> configuration in <code>application.groovy</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails.views.gsp.filteringCodecForContentType.<span class="string"><span class="delimiter">'</span><span class="content">text/html</span><span class="delimiter">'</span></span> = <span class="string"><span class="delimiter">'</span><span class="content">html</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that, if activated, the <code>staticparts</code> codec typically needs to be set to <code>raw</code> so that static markup is not encoded:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">codecs {
expression = <span class="string"><span class="delimiter">'</span><span class="content">html</span><span class="delimiter">'</span></span> <span class="comment">// escapes values inside ${}</span>
scriptlet = <span class="string"><span class="delimiter">'</span><span class="content">html</span><span class="delimiter">'</span></span> <span class="comment">// escapes output from scriptlets in GSPs</span>
taglib = <span class="string"><span class="delimiter">'</span><span class="content">none</span><span class="delimiter">'</span></span> <span class="comment">// escapes output from taglibs</span>
staticparts = <span class="string"><span class="delimiter">'</span><span class="content">raw</span><span class="delimiter">'</span></span> <span class="comment">// escapes output from static template parts</span>
}</code></pre>
</div>
</div>
</div>
<a name="14.2 Encoding and Decoding Objects"><!-- Legacy link --></a>
<h2 id="codecs">17.3 Encoding and Decoding Objects</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/security/codecs.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="sect3">
<h4 id="_codec_classes">Codec Classes</h4>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span>{report.description.encodeAsHTML()}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Decoding is performed using <code>value.decodeHTML()</code> syntax.</p>
</div>
</div>
<div class="sect3">
<h4 id="_encoder_and_decoder_interfaces_for_staticly_compiled_code">Encoder and Decoder interfaces for staticly compiled code</h4>
<div class="paragraph">
<p>A preferred way to use codecs is to use the codecLookup bean to get hold of <code>Encoder</code> and <code>Decoder</code> instances .</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> org.grails.encoder;
<span class="directive">public</span> <span class="type">interface</span> CodecLookup {
<span class="directive">public</span> <span class="predefined-type">Encoder</span> lookupEncoder(<span class="predefined-type">String</span> codecName);
<span class="directive">public</span> Decoder lookupDecoder(<span class="predefined-type">String</span> codecName);
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>example of using <code>CodecLookup</code> and <code>Encoder</code> interface</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">org.grails.encoder.CodecLookup</span>
<span class="type">class</span> <span class="class">CustomTagLib</span> {
CodecLookup codecLookup
<span class="keyword">def</span> myTag = { <span class="predefined-type">Map</span> attrs, body -&gt;
out &lt;&lt; codecLookup.lookupEncoder(<span class="string"><span class="delimiter">'</span><span class="content">HTML</span><span class="delimiter">'</span></span>).encode(attrs.something)
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_standard_codecs">Standard Codecs</h4>
<div class="paragraph">
<p><strong>HTMLCodec</strong></p>
</div>
<div class="paragraph">
<p>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&#8217;t you know that 2 &gt; 1?" you wouldn&#8217;t be able to show this safely within an HTML page because the &gt; 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>
</div>
<div class="paragraph">
<p>Example of usage:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">&lt;input name=<span class="string"><span class="delimiter">&quot;</span><span class="content">comment.message</span><span class="delimiter">&quot;</span></span> value=<span class="string"><span class="delimiter">&quot;</span><span class="inline"><span class="inline-delimiter">${</span>comment.message.encodeAsHTML()<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>/&gt;</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
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.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>HTMLCodec defaults to HTML4 style escaping (legacy HTMLCodec implementation in Grails versions before 2.3.0) which escapes non-ascii characters.</p>
</div>
<div class="paragraph">
<p>You can use plain XML escaping instead of HTML4 escaping by setting this config property in <code>application.groovy</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails.views.gsp.htmlcodec = <span class="string"><span class="delimiter">'</span><span class="content">xml</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>XMLCodec</strong></p>
</div>
<div class="paragraph">
<p>This codec performs XML escaping and unescaping. It escapes &amp; , &lt; , &gt; , " , ' , \\\\ , @ , ` , non breaking space (\\\\u00a0), line separator (\\\\u2028) and paragraph separator (\\\\u2029).</p>
</div>
<div class="paragraph">
<p><strong>HTMLJSCodec</strong></p>
</div>
<div class="paragraph">
<p>This codec performs HTML and JS encoding. It is used for preventing some DOM-XSS vulnerabilities. See <a href="https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet">OWASP - DOM based XSS Prevention Cheat Sheet</a> for guidelines of preventing DOM based XSS attacks.</p>
</div>
<div class="paragraph">
<p><strong>URLCodec</strong></p>
</div>
<div class="paragraph">
<p>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 &amp; Blackberry" is not going to work well as a parameter in a GET request as the ampersand will break parameter parsing.</p>
</div>
<div class="paragraph">
<p>Example of usage:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">&lt;a href=<span class="string"><span class="delimiter">&quot;</span><span class="content">/mycontroller/find?searchKey=</span><span class="inline"><span class="inline-delimiter">${</span>lastSearch.encodeAsURL()<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>&gt;
Repeat last search
&lt;<span class="regexp"><span class="delimiter">/</span><span class="content">a&gt;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>Base64Codec</strong></p>
</div>
<div class="paragraph">
<p>Performs Base64 encode/decode functions. Example of usage:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">Your registration code <span class="key">is</span>: <span class="error">$</span>{user.registrationCode.encodeAsBase64()}</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>JavaScriptCodec</strong></p>
</div>
<div class="paragraph">
<p>Escapes Strings so they can be used as valid JavaScript strings. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="predefined-type">Element</span>.update(<span class="string"><span class="delimiter">'</span><span class="content">${elementId}</span><span class="delimiter">'</span></span>,
<span class="string"><span class="delimiter">'</span><span class="content">${render(template: &quot;/common/message&quot;).encodeAsJavaScript()}</span><span class="delimiter">'</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>HexCodec</strong></p>
</div>
<div class="paragraph">
<p>Encodes byte arrays or lists of integers to lowercase hexadecimal strings, and can decode hexadecimal strings into byte arrays. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">Selected <span class="key">colour</span>: <span class="error">#</span><span class="error">$</span>{[<span class="integer">255</span>,<span class="integer">127</span>,<span class="integer">255</span>].encodeAsHex()}</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>MD5Codec</strong></p>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">Your API <span class="predefined-type">Key</span>: <span class="error">$</span>{user.uniqueID.encodeAsMD5()}</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>MD5BytesCodec</strong></p>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">byte</span><span class="type">[]</span> passwordHash = params.password.encodeAsMD5Bytes()</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>SHA1Codec</strong></p>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">Your API <span class="predefined-type">Key</span>: <span class="error">$</span>{user.uniqueID.encodeAsSHA1()}</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>SHA1BytesCodec</strong></p>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">byte</span><span class="type">[]</span> passwordHash = params.password.encodeAsSHA1Bytes()</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>SHA256Codec</strong></p>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">Your API <span class="predefined-type">Key</span>: <span class="error">$</span>{user.uniqueID.encodeAsSHA256()}</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>SHA256BytesCodec</strong></p>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">byte</span><span class="type">[]</span> passwordHash = params.password.encodeAsSHA256Bytes()</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_custom_codecs">Custom Codecs</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">PigLatinCodec</span> {
<span class="directive">static</span> encode = { str -&gt;
<span class="comment">// convert the string to pig latin and return the result</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>With the above codec in place an application could do something like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml">${lastName.encodeAsPigLatin()}</code></pre>
</div>
</div>
</div>
<a name="14.3 Authentication"><!-- Legacy link --></a>
<h2 id="authentication">17.4 Authentication</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/security/authentication.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails has no default mechanism for authentication as it is possible to implement authentication in many different ways. It is however, easy to implement a simple authentication mechanism using <a href="theWebLayer.html#interceptors">interceptors</a>. This is sufficient for simple use cases but it&#8217;s highly preferable to use an established security framework, for example by using the <a href="#springSecurity">Spring Security</a> or the <a href="#shiro">Shiro</a> plugin.</p>
</div>
<div class="paragraph">
<p>Interceptors let you apply authentication across all controllers or across a URI space. For example you can create a new set of filters in a class called <code>grails-app/controllers/SecurityInterceptor.groovy</code> by running:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails create-interceptor security</code></pre>
</div>
</div>
<div class="paragraph">
<p>and implement your interception logic there:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">SecurityInterceptor</span> {
SecurityInterceptor() {
matchAll()
.except(<span class="key">controller</span>:<span class="string"><span class="delimiter">'</span><span class="content">user</span><span class="delimiter">'</span></span>, <span class="key">action</span>:<span class="string"><span class="delimiter">'</span><span class="content">login</span><span class="delimiter">'</span></span>)
}
<span class="type">boolean</span> before() {
<span class="keyword">if</span> (!session.user &amp;&amp; actionName != <span class="string"><span class="delimiter">&quot;</span><span class="content">login</span><span class="delimiter">&quot;</span></span>) {
redirect(<span class="key">controller</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">user</span><span class="delimiter">&quot;</span></span>, <span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">login</span><span class="delimiter">&quot;</span></span>)
<span class="keyword">return</span> <span class="predefined-constant">false</span>
}
<span class="keyword">return</span> <span class="predefined-constant">true</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here the interceptor intercepts execution <em>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>
</div>
<div class="paragraph">
<p>The <code>login</code> action itself is simple too:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> <span class="function">login</span>() {
<span class="keyword">if</span> (request.get) {
<span class="keyword">return</span> <span class="comment">// render the login view</span>
}
<span class="keyword">def</span> u = User.findByLogin(params.login)
<span class="keyword">if</span> (u) {
<span class="keyword">if</span> (u.password == params.password) {
session.user = u
redirect(<span class="key">action</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">home</span><span class="delimiter">&quot;</span></span>)
}
<span class="keyword">else</span> {
render(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">login</span><span class="delimiter">&quot;</span></span>, <span class="key">model</span>: [<span class="key">message</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">Password incorrect</span><span class="delimiter">&quot;</span></span>])
}
}
<span class="keyword">else</span> {
render(<span class="key">view</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">login</span><span class="delimiter">&quot;</span></span>, <span class="key">model</span>: [<span class="key">message</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">User not found</span><span class="delimiter">&quot;</span></span>])
}
}</code></pre>
</div>
</div>
<a name="14.4 Security Plug-ins"><!-- Legacy link --></a>
<h2 id="securityPlugins">17.5 Security Plugins</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/security/securityPlugins.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>If you need more advanced functionality beyond simple authentication such as authorization, roles etc. then you should consider using the spring security core plugin.</p>
</div>
<a name="14.4.1 Spring Security"><!-- Legacy link --></a>
<h2 id="springSecurity">17.5.1 Spring Security</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/security/securityPlugins/springSecurity.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>The Spring Security plugins are built on the <a href="http://projects.spring.io/spring-security/">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>
</div>
<div class="paragraph">
<p>There is a <a href="http://grails.org/plugins.html#plugin/spring-security-core">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="https://grails.org/plugins.html#plugin/spring-security-acl">ACL support</a>, <a href="https://grails.org/plugins.html#plugin/spring-security-cas">single sign-on with Jasig CAS</a>, <a href="https://grails.org/plugins.html#plugin/spring-security-ldap">LDAP authentication</a>, <a href="https://grails.org/plugins.html#plugin/spring-security-kerberos">Kerberos authentication</a>, and a plugin providing <a href="https://grails.org/plugins.html#plugin/spring-security-ui">user interface extensions</a> and security workflows.</p>
</div>
<div class="paragraph">
<p>See the <a href="http://grails.org/plugins.html#plugin/spring-security-core">Core plugin page</a> for basic information and the <a href="http://grails-plugins.github.io/grails-spring-security-core/">user guide</a> for detailed information.</p>
</div>
<a name="15. Plug-ins"><!-- Legacy link --></a>
<h1 id="plugins">18 Plugins</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/plugins.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>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&#8217;ll know how to create a plugin for <a href="#providingBasicArtefacts">sharing a data model</a> or some static resources.</p>
</div>
<a name="15.1 Creating and Installing Plug-ins"><!-- Legacy link --></a>
<h2 id="creatingAndInstallingPlugins">18.1 Creating and Installing Plugins</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/plugins/creatingAndInstallingPlugins.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_creating_plugins">Creating Plugins</h4>
<div class="paragraph">
<p>Creating a Grails plugin is a simple matter of running the command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails create-plugin &lt;&lt;PLUGIN NAME&gt;&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will create a web-plugin project for the name you specify. For example running <code>grails create-plugin example</code> would create a new web-plugin project called <code>example</code>.</p>
</div>
<div class="paragraph">
<p>In Grails 3.0 you should consider whether the plugin you create requires a web environment or whether the plugin can be used with other profiles. If your plugin does not require a web environment then use the "plugin" profile instead of the default "web-plugin" profile:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails create-plugin &lt;&lt;PLUGIN NAME&gt;&gt; --profile=plugin</code></pre>
</div>
</div>
<div class="paragraph">
<p>Make sure the plugin name does not contain more than one capital letter in a row, or it won&#8217;t work. Camel case is fine, though.</p>
</div>
<div class="paragraph">
<p>Being a regular Grails project has a number of benefits in that you can immediately test your plugin by running (if the plugin targets the "web" profile):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails run-app</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Plugin projects don&#8217;t provide an index.gsp by default since most plugins don&#8217;t need it. So, if you try to view the plugin running in a browser right after creating it, you will receive a page not found error. You can easily create a <code>grails-app/views/index.gsp</code> for your plugin if you&#8217;d like.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The structure of a Grails plugin is very nearly the same as a Grails application project&#8217;s except that in the <code>src/main/groovy</code> directory under the plugin package structure you will find a plugin descriptor class (a class that ends in "GrailsPlugin"). For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.plugins.*</span>
<span class="type">class</span> <span class="class">ExampleGrailsPlugin</span> <span class="directive">extends</span> Plugin {
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>All plugins must have this class under the <code>src/main/groovy</code> directory, otherwise they are not regarded as a plugin. The plugin class defines metadata about the plugin, and optionally various hooks into plugin extension points (covered shortly).</p>
</div>
<div class="paragraph">
<p>You can also provide additional information about your plugin using several special properties:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>title</code> - short one-sentence description of your plugin</p>
</li>
<li>
<p><code>grailsVersion</code> - The version range of Grails that the plugin supports. eg. "1.2 &gt; *" (indicating 1.2 or higher)</p>
</li>
<li>
<p><code>author</code> - plugin author&#8217;s name</p>
</li>
<li>
<p><code>authorEmail</code> - plugin author&#8217;s contact e-mail</p>
</li>
<li>
<p><code>developers</code> - Any additional developers beyond the author specified above.</p>
</li>
<li>
<p><code>description</code> - full multi-line description of plugin&#8217;s features</p>
</li>
<li>
<p><code>documentation</code> - URL of the plugin&#8217;s documentation</p>
</li>
<li>
<p><code>license</code> - License of the plugin</p>
</li>
<li>
<p><code>issueManagement</code> - Issue Tracker of the plugin</p>
</li>
<li>
<p><code>scm</code> - Source code management location of the plugin</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Here is a slimmed down example from the <a href="https://github.com/grails-plugins/grails-quartz">Quartz Grails plugin</a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> quartz
<span class="annotation">@Slf4j</span>
<span class="type">class</span> <span class="class">QuartzGrailsPlugin</span> <span class="directive">extends</span> Plugin {
<span class="comment">// the version or versions of Grails the plugin is designed for</span>
<span class="keyword">def</span> grailsVersion = <span class="string"><span class="delimiter">&quot;</span><span class="content">3.0.0.BUILD-SNAPSHOT &gt; *</span><span class="delimiter">&quot;</span></span>
<span class="comment">// resources that are excluded from plugin packaging</span>
<span class="keyword">def</span> pluginExcludes = [
<span class="string"><span class="delimiter">&quot;</span><span class="content">grails-app/views/error.gsp</span><span class="delimiter">&quot;</span></span>
]
<span class="keyword">def</span> title = <span class="string"><span class="delimiter">&quot;</span><span class="content">Quartz</span><span class="delimiter">&quot;</span></span> <span class="comment">// Headline display name of the plugin</span>
<span class="keyword">def</span> author = <span class="string"><span class="delimiter">&quot;</span><span class="content">Jeff Brown</span><span class="delimiter">&quot;</span></span>
<span class="keyword">def</span> authorEmail = <span class="string"><span class="delimiter">&quot;</span><span class="content">zzz@yyy.com</span><span class="delimiter">&quot;</span></span>
<span class="keyword">def</span> description = <span class="string"><span class="delimiter">'''</span><span class="content">\
</span><span class="content">Adds Quartz job scheduling features
</span><span class="delimiter">'''</span></span>
<span class="keyword">def</span> profiles = [<span class="string"><span class="delimiter">'</span><span class="content">web</span><span class="delimiter">'</span></span>]
<span class="predefined-type">List</span> loadAfter = [<span class="string"><span class="delimiter">'</span><span class="content">hibernate3</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">hibernate4</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">hibernate5</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">services</span><span class="delimiter">'</span></span>]
<span class="keyword">def</span> documentation = <span class="string"><span class="delimiter">&quot;</span><span class="content">http://grails.org/plugin/quartz</span><span class="delimiter">&quot;</span></span>
<span class="keyword">def</span> license = <span class="string"><span class="delimiter">&quot;</span><span class="content">APACHE</span><span class="delimiter">&quot;</span></span>
<span class="keyword">def</span> issueManagement = [ <span class="key">system</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">Github Issues</span><span class="delimiter">&quot;</span></span>, <span class="key">url</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">http://github.com/grails3-plugins/quartz/issues</span><span class="delimiter">&quot;</span></span> ]
<span class="keyword">def</span> developers = [
[ <span class="key">name</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">Joe Dev</span><span class="delimiter">&quot;</span></span>, <span class="key">email</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">joedev@gmail.com</span><span class="delimiter">&quot;</span></span> ]
]
<span class="keyword">def</span> scm = [ <span class="key">url</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">https://github.com/grails3-plugins/quartz/</span><span class="delimiter">&quot;</span></span> ]
Closure doWithSpring()......</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_installing_local_plugins">Installing Local Plugins</h4>
<div class="paragraph">
<p>To make your plugin available for use in a Grails application run the <code>install</code> command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails install</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will install the plugin into your local Maven cache. Then to use the plugin within an application declare a dependency on the plugin in your <code>build.gradle</code> file:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">compile <span class="string"><span class="delimiter">&quot;</span><span class="content">org.grails.plugins:quartz:0.1</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
In Grails 2.x plugins were packaged as ZIP files, however in Grails 3.x plugins are simple JAR files that can be added to the classpath of the IDE.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_plugins_and_multi_project_builds">Plugins and Multi-Project Builds</h4>
<div class="paragraph">
<p>If you wish to setup a plugin as part of a multi project build then follow these steps.</p>
</div>
<div class="paragraph">
<p><strong>Step 1: Create the application and the plugin</strong></p>
</div>
<div class="paragraph">
<p>Using the <code>grails</code> command create an application and a plugin:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span> grails create-app myapp
<span class="error">$</span> grails create-plugin myplugin</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>Step 2: Create a settings.gradle file</strong></p>
</div>
<div class="paragraph">
<p>In the same directory create a <code>settings.gradle</code> file with the following contents:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">include <span class="string"><span class="delimiter">&quot;</span><span class="content">myapp</span><span class="delimiter">&quot;</span></span>, <span class="string"><span class="delimiter">&quot;</span><span class="content">myplugin</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The directory structure should be as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">PROJECT_DIR
- settings.gradle
- myapp
- build.gradle
- myplugin
- build.gradle</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>Step 3: Declare a project dependency on the plugin</strong></p>
</div>
<div class="paragraph">
<p>Within the <code>build.gradle</code> of the application declare a dependency on the plugin within the <code>plugins</code> block:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails {
plugins {
compile project(<span class="string"><span class="delimiter">'</span><span class="content">:myplugin</span><span class="delimiter">'</span></span>)
}
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
You can also declare the dependency within the <code>dependencies</code> block, however you will not get subproject reloading if you do this!
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p><strong>Step 4: Configure the plugin to enable reloading</strong></p>
</div>
<div class="paragraph">
<p>In the plugin directory, add or modify the <code>gradle.properties</code> file. A new property <code>exploded=true</code> needs to be set in order for the plugin to add the exploded directories to the classpath.</p>
</div>
<div class="paragraph">
<p><strong>Step 5: Run the application</strong></p>
</div>
<div class="paragraph">
<p>Now run the application using the <code>grails run-app</code> command from the root of the application directory, you can use the <code>verbose</code> flag to see the Gradle output:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span> cd myapp
<span class="error">$</span> grails run-app -verbose</code></pre>
</div>
</div>
<div class="paragraph">
<p>You will notice from the Gradle output that plugins sources are built and placed on the classpath of your application:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">:<span class="key">myplugin</span>:compileAstJava UP-TO-DATE
:<span class="key">myplugin</span>:compileAstGroovy UP-TO-DATE
:<span class="key">myplugin</span>:processAstResources UP-TO-DATE
:<span class="key">myplugin</span>:astClasses UP-TO-DATE
:<span class="key">myplugin</span>:compileJava UP-TO-DATE
:<span class="key">myplugin</span>:configScript UP-TO-DATE
:<span class="key">myplugin</span>:compileGroovy
:<span class="key">myplugin</span>:copyAssets UP-TO-DATE
:<span class="key">myplugin</span>:copyCommands UP-TO-DATE
:<span class="key">myplugin</span>:copyTemplates UP-TO-DATE
:<span class="key">myplugin</span>:processResources
:<span class="key">myapp</span>:compileJava UP-TO-DATE
:<span class="key">myapp</span>:compileGroovy
:<span class="key">myapp</span>:processResources UP-TO-DATE
:<span class="key">myapp</span>:classes
:<span class="key">myapp</span>:findMainClass
:<span class="key">myapp</span>:bootRun
Grails application running at <span class="key">http</span>:<span class="comment">//localhost:8080 in environment: development</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_notes_on_excluded_artefacts">Notes on excluded Artefacts</h4>
<div class="paragraph">
<p>Although the <a href="../ref/Command%20Line/create-plugin.html">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%20Line/package-plugin.html">package-plugin</a>:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>grails-app/build.gradle</code> (although it is used to generate <code>dependencies.groovy</code>)</p>
</li>
<li>
<p><code>grails-app/conf/application.yml</code> (renamed to plugin.yml)</p>
</li>
<li>
<p><code>grails-app/conf/spring/resources.groovy</code></p>
</li>
<li>
<p><code>grails-app/conf/logback.groovy</code></p>
</li>
<li>
<p>Everything within <code>/src/test/*\*</code></p>
</li>
<li>
<p>SCM management files within <code>*\*/.svn/*\*</code> and <code>*\*/CVS/*\*</code></p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_customizing_the_plugin_contents">Customizing the plugin contents</h4>
<div class="paragraph">
<p>When developing a plugin you may create test classes and sources that are used during the development and testing of the plugin but should not be exported to the application.</p>
</div>
<div class="paragraph">
<p>To exclude test sources you need to modify the <code>pluginExcludes</code> property of the plugin descriptor AND exclude the resources inside your <code>build.gradle</code> file. For example say you have some classes under the <code>com.demo</code> package that are in your plugin source tree but should not be packaged in the application. In your plugin descriptor you should exclude these:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// resources that should be loaded by the plugin once installed in the application</span>
<span class="keyword">def</span> pluginExcludes = [
<span class="string"><span class="delimiter">'</span><span class="content">**/com/demo/**</span><span class="delimiter">'</span></span>
]</code></pre>
</div>
</div>
<div class="paragraph">
<p>And in your <code>build.gradle</code> you should exclude the compiled classes from the JAR file:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">jar {
exclude <span class="string"><span class="delimiter">&quot;</span><span class="content">com/demo/**/**</span><span class="delimiter">&quot;</span></span>
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_inline_plugins_in_grails_3_0">Inline Plugins in Grails 3.0</h4>
<div class="paragraph">
<p>In Grails 2.x it was possible to specify inline plugins in <code>BuildConfig</code>, in Grails 3.x this functionality has been replaced by Gradle&#8217;s multi-project build feature.</p>
</div>
<div class="paragraph">
<p>To set up a multi project build create an appliation and a plugin in a parent directory:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span> grails create-app myapp
<span class="error">$</span> grails create-plugin myplugin</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then create a <code>settings.gradle</code> file in the parent directory specifying the location of your application and plugin:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">include <span class="string"><span class="delimiter">'</span><span class="content">myapp</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">myplugin</span><span class="delimiter">'</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Finally add a dependency in your application&#8217;s <code>build.gradle</code> on the plugin:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">compile project(<span class="string"><span class="delimiter">'</span><span class="content">:myplugin</span><span class="delimiter">'</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Using this technique you have achieved the equivalent of inline plugins from Grails 2.x.</p>
</div>
</div>
<a name="15.2 Plugin Repositories"><!-- Legacy link --></a>
<h2 id="repositories">18.2 Plugin Repositories</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/plugins/repositories.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_distributing_plugins_in_the_grails_central_plugin_repository">Distributing Plugins in the Grails Central Plugin Repository</h4>
<div class="paragraph">
<p>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%20Line/list-plugins.html">list-plugins</a> command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails list-plugins</code></pre>
</div>
</div>
<div class="paragraph">
<p>which lists all plugins that are in the central repository. Your plugin will also be available to the <a href="../ref/Command%20Line/plugin-info.html">plugin-info</a> command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails plugin-info [plugin-name]</code></pre>
</div>
</div>
<div class="paragraph">
<p>which prints extra information about it, such as its description, who wrote, etc.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
If you have created a Grails plugin and want it to be hosted in the central repository, you&#8217;ll find instructions for getting an account on the <a href="http://plugins.grails.org/">plugin portal</a> website.
</td>
</tr>
</table>
</div>
</div>
<a name="15.4 Providing Basic Artefacts"><!-- Legacy link --></a>
<h2 id="providingBasicArtefacts">18.3 Providing Basic Artefacts</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/plugins/providingBasicArtefacts.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_add_command_line_commands">Add Command Line Commands</h4>
<div class="paragraph">
<p>A plugin can add new commands to the Grails 3.0 interactive shell in one of two ways. First, using the <a href="../ref/Command%20Line/create-script.html">create-script</a> you can create a code generation script which will become available to the application. The <code>create-script</code> command will create the script in the <code>src/main/scripts</code> directory:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">+ src/main/scripts &lt;-- additional scripts here
+ grails-app
+ controllers
+ services
+ etc.</code></pre>
</div>
</div>
<div class="paragraph">
<p>Code generation scripts can be used to create artefacts within the project tree and automate interactions with Gradle.</p>
</div>
<div class="paragraph">
<p>If you want to create a new shell command that interacts with a loaded Grails application instance then you should use the <code>create-command</code> command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span> grails create-command MyExampleCommand</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will create a file called <code>grails-app/commands/PACKAGE_PATH/MyExampleCommand.groovy</code> that extends <a href="https://grails.apache.org/docs/3.3.7/api/grails/dev/commands/ApplicationCommand.html">ApplicationCommand</a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.dev.commands.*</span>
<span class="type">class</span> <span class="class">MyExampleCommand</span> <span class="directive">implements</span> ApplicationCommand {
<span class="type">boolean</span> handle(ExecutionContext ctx) {
println <span class="string"><span class="delimiter">&quot;</span><span class="content">Hello World</span><span class="delimiter">&quot;</span></span>
<span class="keyword">return</span> <span class="predefined-constant">true</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>An <code>ApplicationCommand</code> has access to the <code>GrailsApplication</code> instance and is subject to autowiring like any other Spring bean.</p>
</div>
<div class="paragraph">
<p>You can also inform Grails to skip the execution of <code>Bootstrap.groovy</code> files with a simple property in your command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">MyExampleCommand</span> <span class="directive">implements</span> ApplicationCommand {
<span class="type">boolean</span> skipBootstrap = <span class="predefined-constant">true</span>
<span class="type">boolean</span> handle(ExecutionContext ctx) {
...
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>For each <code>ApplicationCommand</code> present Grails will create a shell command and a Gradle task to invoke the <code>ApplicationCommand</code>. In the above example you can invoke the <code>MyExampleCommand</code> class using either:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span> grails my-example</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="error">$</span> gradle myExample</code></pre>
</div>
</div>
<div class="paragraph">
<p>The Grails version is all lower case hyphen separated and excludes the "Command" suffix.</p>
</div>
<div class="paragraph">
<p>The main difference between code generation scripts and <code>ApplicationCommand</code> instances is that the latter has full access to the Grails application state and hence can be used to perform tasks that interactive with the database, call into GORM etc.</p>
</div>
<div class="paragraph">
<p>In Grails 2.x Gant scripts could be used to perform both these tasks, in Grails 3.x code generation and interacting with runtime application state has been cleanly separated.</p>
</div>
</div>
<div class="sect3">
<h4 id="_adding_a_new_grails_app_artifact_controller_tag_library_service_etc">Adding a new grails-app artifact (Controller, Tag Library, Service, etc.)</h4>
<div class="paragraph">
<p>A plugin can add new artifacts by creating the relevant file within the <code>grails-app</code> tree.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">+ grails-app
+ controllers &lt;-- additional controllers here
+ services &lt;-- additional services here
+ etc. &lt;-- additional XXX here</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_providing_views_templates_and_view_resolution">Providing Views, Templates and View resolution</h4>
<div class="paragraph">
<p>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&#8217;s <code>grails-app/views</code> directory.</p>
</div>
<div class="paragraph">
<p>For example, consider a controller called <code>BookController</code> that&#8217;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>
</div>
<div class="paragraph">
<p>However if the view uses templates that are also provided by the plugin then the following syntax may be necessary:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">&lt;<span class="key">g</span>:render template=<span class="string"><span class="delimiter">&quot;</span><span class="content">fooTemplate</span><span class="delimiter">&quot;</span></span> plugin=<span class="string"><span class="delimiter">&quot;</span><span class="content">amazon</span><span class="delimiter">&quot;</span></span>/&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
</div>
<div class="sect3">
<h4 id="_excluded_artefacts">Excluded Artefacts</h4>
<div class="paragraph">
<p>By default Grails excludes the following files during the packaging process:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>grails-app/conf/logback.groovy</code></p>
</li>
<li>
<p><code>grails-app/conf/application.yml</code> (renamed to <code>plugin.yml</code>)</p>
</li>
<li>
<p><code>grails-app/conf/spring/resources.groovy</code></p>
</li>
<li>
<p>Everything within <code>/src/test/*\*</code></p>
</li>
<li>
<p>SCM management files within <code>*\*/.svn/*\*</code> and <code>*\*/CVS/*\*</code></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The default <code>UrlMappings.groovy</code> file is not excluded, so remove any mappings that are not required for the plugin to work. You are also free to add a UrlMappings definition under a different name which <strong>will</strong> be included. For example a file called <code>grails-app/controllers/BlogUrlMappings.groovy</code> is fine.</p>
</div>
<div class="paragraph">
<p>The list of excludes is extensible with the <code>pluginExcludes</code> property:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="comment">// resources that are excluded from plugin packaging</span>
<span class="keyword">def</span> pluginExcludes = [
<span class="string"><span class="delimiter">&quot;</span><span class="content">grails-app/views/error.gsp</span><span class="delimiter">&quot;</span></span>
]</code></pre>
</div>
</div>
<div class="paragraph">
<p>This is useful for example to include demo or test resources in the plugin repository, but not include them in the final distribution.</p>
</div>
</div>
<a name="15.5 Evaluating Conventions"><!-- Legacy link --></a>
<h2 id="evaluatingConventions">18.4 Evaluating Conventions</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/plugins/evaluatingConventions.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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="https://grails.apache.org/docs/3.3.7/api/grails/core/GrailsApplication.html">GrailsApplication</a> interface.</p>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>Artifacts implement the <a href="https://grails.apache.org/docs/3.3.7/api/grails/core/GrailsClass.html">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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">for</span> (grailsClass <span class="keyword">in</span> application.allClasses) {
println grailsClass.name
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">for</span> (controllerClass <span class="keyword">in</span> application.controllerClasses) {
println controllerClass.name
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The dynamic method conventions are as follows:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>*Classes</code> - Retrieves all the classes for a particular artefact name. For example <code>application.controllerClasses</code>.</p>
</li>
<li>
<p><code>get*Class</code> - Retrieves a named class for a particular artefact. For example <code>application.getControllerClass("PersonController")</code></p>
</li>
<li>
<p><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></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The <code>GrailsClass</code> interface has a number of useful methods that let you further evaluate and work with the conventions. These include:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>getPropertyValue</code> - Gets the initial value of the given property on the class</p>
</li>
<li>
<p><code>hasProperty</code> - Returns <code>true</code> if the class has the specified property</p>
</li>
<li>
<p><code>newInstance</code> - Creates a new instance of this class.</p>
</li>
<li>
<p><code>getName</code> - Returns the logical name of the class in the application without the trailing convention part if applicable</p>
</li>
<li>
<p><code>getShortName</code> - Returns the short name of the class without package prefix</p>
</li>
<li>
<p><code>getFullName</code> - Returns the full name of the class in the application with the trailing convention part and with the package name</p>
</li>
<li>
<p><code>getPropertyName</code> - Returns the name of the class as a property name</p>
</li>
<li>
<p><code>getLogicalPropertyName</code> - Returns the logical property name of the class in the application without the trailing convention part if applicable</p>
</li>
<li>
<p><code>getNaturalName</code> - Returns the name of the property in natural terms (e.g. 'lastName' becomes 'Last Name')</p>
</li>
<li>
<p><code>getPackageName</code> - Returns the package name</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>For a full reference refer to the <a href="https://grails.apache.org/docs/3.3.7/api/grails/core/GrailsClass.html">javadoc API</a>.</p>
</div>
<a name="15.7 Hooking into Runtime Configuration"><!-- Legacy link --></a>
<h2 id="hookingIntoRuntimeConfiguration">18.5 Hooking into Runtime Configuration</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/plugins/hookingIntoRuntimeConfiguration.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails provides a number of hooks to leverage the different parts of the system and perform runtime configuration by convention.</p>
</div>
<div class="sect3">
<h4 id="_hooking_into_the_grails_spring_configuration">Hooking into the Grails Spring configuration</h4>
<div class="paragraph">
<p>First, you can hook in Grails runtime configuration overriding the <code>doWithSpring</code> method from the <a href="https://grails.apache.org/docs/3.3.7/api/grails/plugins/Plugin.html">Plugin</a> class and returning a closure that defines additional beans. For example the following snippet is from one of the core Grails plugins that provides <a href="i18n.html">i18n</a> support:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">org.springframework.web.servlet.i18n.CookieLocaleResolver</span>
<span class="keyword">import</span> <span class="include">org.springframework.web.servlet.i18n.LocaleChangeInterceptor</span>
<span class="keyword">import</span> <span class="include">org.springframework.context.support.ReloadableResourceBundleMessageSource</span>
<span class="keyword">import</span> <span class="include">grails.plugins.*</span>
<span class="type">class</span> <span class="class">I18nGrailsPlugin</span> <span class="directive">extends</span> Plugin {
<span class="keyword">def</span> version = <span class="string"><span class="delimiter">&quot;</span><span class="content">0.1</span><span class="delimiter">&quot;</span></span>
Closure doWithSpring() {{-&gt;
messageSource(ReloadableResourceBundleMessageSource) {
basename = <span class="string"><span class="delimiter">&quot;</span><span class="content">WEB-INF/grails-app/i18n/messages</span><span class="delimiter">&quot;</span></span>
}
localeChangeInterceptor(LocaleChangeInterceptor) {
paramName = <span class="string"><span class="delimiter">&quot;</span><span class="content">lang</span><span class="delimiter">&quot;</span></span>
}
localeResolver(CookieLocaleResolver)
}}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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="spring.html#theBeanBuilderDSLExplained">Spring Bean Builder</a> syntax to do so.</p>
</div>
</div>
<div class="sect3">
<h4 id="_customizing_the_servlet_environment">Customizing the Servlet Environment</h4>
<div class="paragraph">
<p>In previous versions of Grails it was possible to dynamically modify the generated <code>web.xml</code>. In Grails 3.x there is no <code>web.xml</code> file and it is not possible to programmatically modify the <code>web.xml</code> file anymore.</p>
</div>
<div class="paragraph">
<p>However, it is possible to perform the most commons tasks of modifying the Servlet environment in Grails 3.x.</p>
</div>
</div>
<div class="sect3">
<h4 id="_adding_new_servlets">Adding New Servlets</h4>
<div class="paragraph">
<p>If you want to add a new Servlet instance the simplest way is simply to define a new Spring bean in the <code>doWithSpring</code> method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">Closure doWithSpring() {{-&gt;
myServlet(MyServlet)
}}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you need to customize the servlet you can use Spring Boot&#8217;s <a href="http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/context/embedded/ServletRegistrationBean.html">ServletRegistrationBean</a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">Closure doWithSpring() {{-&gt;
myServlet(ServletRegistrationBean, <span class="keyword">new</span> MyServlet(), <span class="string"><span class="delimiter">&quot;</span><span class="content">/myServlet/*</span><span class="delimiter">&quot;</span></span>) {
loadOnStartup = <span class="integer">2</span>
}
}}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_adding_new_servlet_filters">Adding New Servlet Filters</h4>
<div class="paragraph">
<p>Just like Servlets, the simplest way to configure a new filter is to simply define a Spring bean:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">Closure doWithSpring() {{-&gt;
myFilter(MyFilter)
}}</code></pre>
</div>
</div>
<div class="paragraph">
<p>However, if you want to control the order of filter registrations you will need to use Spring Boot&#8217;s <a href="http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/web/servlet/FilterRegistrationBean.html">FilterRegistrationBean</a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">myFilter(FilterRegistrationBean) {
filter = bean(MyFilter)
urlPatterns = [<span class="string"><span class="delimiter">'</span><span class="content">/*</span><span class="delimiter">'</span></span>]
order = Ordered.HIGHEST_PRECEDENCE
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Grails' internal registered filters (<code>GrailsWebRequestFilter</code>, <code>HiddenHttpMethodFilter</code> etc.) are defined by incrementing <code>HIGHEST_PRECEDENCE</code> by 10 thus allowing several filters to be inserted before or between Grails' filters.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_doing_post_initialisation_configuration">Doing Post Initialisation Configuration</h4>
<div class="paragraph">
<p>Sometimes it is useful to be able do some runtime configuration after the Spring <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/ApplicationContext.html">ApplicationContext</a> has been built. In this case you can define a <code>doWithApplicationContext</code> closure property.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">SimplePlugin</span> <span class="directive">extends</span> Plugin{
<span class="keyword">def</span> name = <span class="string"><span class="delimiter">&quot;</span><span class="content">simple</span><span class="delimiter">&quot;</span></span>
<span class="keyword">def</span> version = <span class="string"><span class="delimiter">&quot;</span><span class="content">1.1</span><span class="delimiter">&quot;</span></span>
<span class="annotation">@Override</span>
<span class="type">void</span> doWithApplicationContext() {
<span class="keyword">def</span> sessionFactory = applicationContext.sessionFactory
<span class="comment">// do something here with session factory</span>
}
}</code></pre>
</div>
</div>
</div>
<h2 id="addingMethodsAtCompileTime">18.6 Adding Methods at Compile Time</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/plugins/addingMethodsAtCompileTime.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails 3.0 makes it easy to add new traits to existing artefact types from a plugin. For example say you wanted to add methods for manipulating dates to controllers. This can be done by defining a trait in <code>src/main/groovy</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> myplugin
<span class="annotation">@Enhances</span>(<span class="string"><span class="delimiter">&quot;</span><span class="content">Controller</span><span class="delimiter">&quot;</span></span>)
trait DateTrait {
<span class="predefined-type">Date</span> currentDate() {
<span class="keyword">return</span> <span class="keyword">new</span> <span class="predefined-type">Date</span>()
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>@Enhances</code> annotation defines the types of artefacts that the trait should be applied to.</p>
</div>
<div class="paragraph">
<p>As an alternative to using the <code>@Enhances</code> annotation above, you can implement a <a href="https://grails.apache.org/docs/3.3.7/api/grails/compiler/traits/TraitInjector.html">TraitInjector</a> to tell Grails which artefacts you want to inject the trait into at compile time:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> myplugin
<span class="annotation">@CompileStatic</span>
<span class="type">class</span> <span class="class">ControllerTraitInjector</span> <span class="directive">implements</span> TraitInjector {
<span class="annotation">@Override</span>
<span class="predefined-type">Class</span> getTrait() {
SomeTrait
}
<span class="annotation">@Override</span>
<span class="predefined-type">String</span><span class="type">[]</span> getArtefactTypes() {
[<span class="string"><span class="delimiter">'</span><span class="content">Controller</span><span class="delimiter">'</span></span>] <span class="keyword">as</span> <span class="predefined-type">String</span><span class="type">[]</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above <code>TraitInjector</code> will add the <code>SomeTrait</code> to all controllers. The <code>getArtefactTypes</code> method defines the types of artefacts that the trait should be applied to.</p>
</div>
<div class="sect3">
<h4 id="_applying_traits_conditionally">Applying traits conditionally</h4>
<div class="paragraph">
<p>A <code>TraitInjector</code> implementation can also implement the <a href="https://grails.apache.org/docs/3.3.7/api/grails/compiler/ast/SupportsClassNode.html">SupportsClassNode</a> interface to apply traits to only those artefacts which satisfy a custom requirement.
For example, if a trait should only be applied if the target artefact class has a specific annotation, it can be done as below</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> myplugin
<span class="annotation">@CompileStatic</span>
<span class="type">class</span> <span class="class">AnnotationBasedTraitInjector</span> <span class="directive">implements</span> TraitInjector, SupportsClassNode {
<span class="annotation">@Override</span>
<span class="predefined-type">Class</span> getTrait() {
SomeTrait
}
<span class="annotation">@Override</span>
<span class="predefined-type">String</span><span class="type">[]</span> getArtefactTypes() {
[<span class="string"><span class="delimiter">'</span><span class="content">Controller</span><span class="delimiter">'</span></span>] <span class="keyword">as</span> <span class="predefined-type">String</span><span class="type">[]</span>
}
<span class="type">boolean</span> supports(ClassNode classNode) {
<span class="keyword">return</span> GrailsASTUtils.hasAnnotation(classNode, SomeAnnotation)
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Above <code>TraitInjector</code> will add the <code>SomeTrait</code> to only those controllers which has the <code>SomeAnnotation</code> declared.</p>
</div>
<div class="paragraph">
<p>The framework discovers trait injectors by way of a <code>META-INF/grails.factories</code> descriptor that is in the .jar file. This descriptor is automatically generated. The descriptor generated for the code shown above would look like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code>#Grails Factories File
grails.compiler.traits.TraitInjector=
myplugin.ControllerTraitInjector,myplugin.DateTraitTraitInjector</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Due to formatting issues, above code snippet includes a line break after equal sign.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>That file is generated automatically and added to the .jar file at build time. If for any reason the application defines its own <code>grails.factories</code> file at <code>src/main/resources/META-INF/grails.factories</code>, it is important that the trait injectors be explicitly defined in that file. The auto-generated metadata is only reliable if the application does not define its own <code>src/main/resources/META-INF/grails.factores</code> file.</p>
</div>
</div>
<a name="15.8 Adding Dynamic Methods at Runtime"><!-- Legacy link --></a>
<h2 id="addingDynamicMethodsAtRuntime">18.7 Adding Dynamic Methods at Runtime</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/plugins/addingDynamicMethodsAtRuntime.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_the_basics">The Basics</h4>
<div class="paragraph">
<p>Grails plugins let you register dynamic methods with any Grails-managed or other class at runtime. This work is done in a <code>doWithDynamicMethods</code> method.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Note that Grails 3.x features newer features such as traits that are usable from code compiled with <code>CompileStatic</code>. It is recommended that dynamic behavior is only added for cases that are not possible with traits.
</td>
</tr>
</table>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ExamplePlugin</span> <span class="directive">extends</span> Plugin {
<span class="type">void</span> doWithDynamicMethods() {
<span class="keyword">for</span> (controllerClass <span class="keyword">in</span> grailsApplication.controllerClasses) {
controllerClass.metaClass.myNewMethod = {-&gt; println <span class="string"><span class="delimiter">&quot;</span><span class="content">hello world</span><span class="delimiter">&quot;</span></span> }
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>For example we can add a new method <code>swapCase</code> to <code>java.lang.String</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ExamplePlugin</span> <span class="directive">extends</span> Plugin {
<span class="annotation">@Override</span>
<span class="type">void</span> doWithDynamicMethods() {
<span class="predefined-type">String</span>.metaClass.swapCase = {-&gt;
<span class="keyword">def</span> sb = <span class="keyword">new</span> <span class="predefined-type">StringBuilder</span>()
delegate.each {
sb &lt;&lt; (<span class="predefined-type">Character</span>.isUpperCase(<span class="local-variable">it</span> <span class="keyword">as</span> <span class="type">char</span>) ?
<span class="predefined-type">Character</span>.toLowerCase(<span class="local-variable">it</span> <span class="keyword">as</span> <span class="type">char</span>) :
<span class="predefined-type">Character</span>.toUpperCase(<span class="local-variable">it</span> <span class="keyword">as</span> <span class="type">char</span>))
}
sb.toString()
}
<span class="keyword">assert</span> <span class="string"><span class="delimiter">&quot;</span><span class="content">UpAndDown</span><span class="delimiter">&quot;</span></span> == <span class="string"><span class="delimiter">&quot;</span><span class="content">uPaNDdOWN</span><span class="delimiter">&quot;</span></span>.swapCase()
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_interacting_with_the_applicationcontext">Interacting with the ApplicationContext</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">org.springframework.orm.hibernate3.HibernateTemplate</span>
<span class="type">class</span> <span class="class">ExampleHibernatePlugin</span> <span class="directive">extends</span> Plugin{
<span class="type">void</span> doWithDynamicMethods() {
<span class="keyword">for</span> (domainClass <span class="keyword">in</span> grailsApplication.domainClasses) {
domainClass.metaClass.static.load = { <span class="predefined-type">Long</span> id-&gt;
<span class="keyword">def</span> sf = applicationContext.sessionFactory
<span class="keyword">def</span> template = <span class="keyword">new</span> HibernateTemplate(sf)
template.load(delegate, id)
}
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">MyConstructorPlugin</span> {
<span class="type">void</span> doWithDynamicMethods()
<span class="keyword">for</span> (domainClass <span class="keyword">in</span> grailsApplication.domainClasses) {
domainClass.metaClass.constructor = {-&gt;
<span class="keyword">return</span> applicationContext.getBean(domainClass.name)
}
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here we actually replace the default constructor with one that looks up prototyped Spring beans instead!</p>
</div>
</div>
<a name="15.9 Participating in Auto Reload Events"><!-- Legacy link --></a>
<h2 id="participatingInAutoReloadEvents">18.8 Participating in Auto Reload Events</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/plugins/participatingInAutoReloadEvents.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_monitoring_resources_for_changes">Monitoring Resources for Changes</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ServicesGrailsPlugin</span> <span class="directive">extends</span> Plugin {
...
def watchedResources = <span class="string"><span class="delimiter">&quot;</span><span class="content">file:./grails-app/services/**/*Service.groovy</span><span class="delimiter">&quot;</span></span>
...
void onChange( <span class="predefined-type">Map</span>&lt;<span class="predefined-type">String</span>, <span class="predefined-type">Object</span>&gt; event) {
<span class="keyword">if</span> (event.source) {
<span class="keyword">def</span> serviceClass = grailsApplication.addServiceClass(event.source)
<span class="keyword">def</span> serviceName = <span class="string"><span class="delimiter">&quot;</span><span class="inline"><span class="inline-delimiter">${</span>serviceClass.propertyName<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>
beans {
<span class="string"><span class="delimiter">&quot;</span><span class="inline"><span class="inline-delimiter">$</span>serviceName</span><span class="delimiter">&quot;</span></span>(serviceClass.getClazz()) { bean -&gt;
bean.autowire = <span class="predefined-constant">true</span>
}
}
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>The <code>event</code> object defines a number of useful properties:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>event.source</code> - The source of the event, either the reloaded <code>Class</code> or a Spring <code>Resource</code></p>
</li>
<li>
<p><code>event.ctx</code> - The Spring <code>ApplicationContext</code> instance</p>
</li>
<li>
<p><code>event.plugin</code> - The plugin object that manages the resource (usually <code>this</code>)</p>
</li>
<li>
<p><code>event.application</code> - The <code>GrailsApplication</code> instance</p>
</li>
<li>
<p><code>event.manager</code> - The <code>GrailsPluginManager</code> instance</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>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>
</div>
</div>
<div class="sect3">
<h4 id="_influencing_other_plugins">Influencing Other Plugins</h4>
<div class="paragraph">
<p>In addition to reacting to changes, sometimes a plugin needs to "influence" another.</p>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> influences = [<span class="string"><span class="delimiter">'</span><span class="content">controllers</span><span class="delimiter">'</span></span>]</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_observing_other_plugins">Observing other plugins</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> observe = [<span class="string"><span class="delimiter">&quot;</span><span class="content">controllers</span><span class="delimiter">&quot;</span></span>]</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this case when a controller is changed you will also receive the event chained from the controllers plugin.</p>
</div>
<div class="paragraph">
<p>It is also possible for a plugin to observe all loaded plugins by using a wildcard:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> observe = [<span class="string"><span class="delimiter">&quot;</span><span class="content">*</span><span class="delimiter">&quot;</span></span>]</code></pre>
</div>
</div>
<div class="paragraph">
<p>The Logging plugin does exactly this so that it can add the <code>log</code> property back to <em>any</em> artefact that changes while the application is running.</p>
</div>
</div>
<a name="15.10 Understanding Plug-in Load Order"><!-- Legacy link --></a>
<h2 id="understandingPluginLoadOrder">18.9 Understanding Plugin Load Order</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/plugins/understandingPluginLoadOrder.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_controlling_plugin_dependencies">Controlling Plugin Dependencies</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">HibernateGrailsPlugin</span> {
<span class="keyword">def</span> version = <span class="string"><span class="delimiter">&quot;</span><span class="content">1.0</span><span class="delimiter">&quot;</span></span>
<span class="keyword">def</span> dependsOn = [<span class="key">dataSource</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">1.0</span><span class="delimiter">&quot;</span></span>,
<span class="key">domainClass</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">1.0</span><span class="delimiter">&quot;</span></span>,
<span class="key">i18n</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">1.0</span><span class="delimiter">&quot;</span></span>,
<span class="key">core</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">1.0</span><span class="delimiter">&quot;</span></span>]
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>The dependencies will be loaded before the Hibernate plugin and if all dependencies do not load, then the plugin will not load.</p>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> dependsOn = [<span class="key">foo</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">* &gt; 1.0</span><span class="delimiter">&quot;</span></span>]
<span class="keyword">def</span> dependsOn = [<span class="key">foo</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">1.0 &gt; 1.1</span><span class="delimiter">&quot;</span></span>]
<span class="keyword">def</span> dependsOn = [<span class="key">foo</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">1.0 &gt; *</span><span class="delimiter">&quot;</span></span>]</code></pre>
</div>
</div>
<div class="paragraph">
<p>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 &gt; 1.1" would match any of the following versions:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>1.1</p>
</li>
<li>
<p>1.0</p>
</li>
<li>
<p>1.0.1</p>
</li>
<li>
<p>1.0.3-SNAPSHOT</p>
</li>
<li>
<p>1.1-BETA2</p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_controlling_load_order">Controlling Load Order</h4>
<div class="paragraph">
<p>Using <code>dependsOn</code> establishes a "hard" dependency in that if the dependency is not resolved, the plugin will give up and won&#8217;t load. It is possible though to have a weaker dependency using the <code>loadAfter</code> and <code>loadBefore</code> properties:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> loadAfter = [<span class="string"><span class="delimiter">'</span><span class="content">controllers</span><span class="delimiter">'</span></span>]</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">if</span> (manager?.hasGrailsPlugin(<span class="string"><span class="delimiter">&quot;</span><span class="content">controllers</span><span class="delimiter">&quot;</span></span>)) {
openSessionInViewInterceptor(OpenSessionInViewInterceptor) {
flushMode = HibernateAccessor.FLUSH_MANUAL
sessionFactory = sessionFactory
}
grailsUrlHandlerMapping.interceptors &lt;&lt; openSessionInViewInterceptor
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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="https://grails.apache.org/docs/3.3.7/api/grails/plugins/GrailsPluginManager.html">GrailsPluginManager</a> interface and it provides methods to interact with other plugins.</p>
</div>
<div class="paragraph">
<p>You can also use the <code>loadBefore</code> property to specify one or more plugins that your plugin should load before:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> loadBefore = [<span class="string"><span class="delimiter">'</span><span class="content">rabbitmq</span><span class="delimiter">'</span></span>]</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_scopes_and_environments">Scopes and Environments</h4>
<div class="paragraph">
<p>It&#8217;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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> environments = [<span class="string"><span class="delimiter">'</span><span class="content">development</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">test</span><span class="delimiter">'</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">myCustomEnv</span><span class="delimiter">'</span></span>]
<span class="keyword">def</span> scopes = [<span class="key">excludes</span>:<span class="string"><span class="delimiter">'</span><span class="content">war</span><span class="delimiter">'</span></span>]</code></pre>
</div>
</div>
<div class="paragraph">
<p>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&#8217;s excluded from the 'war' phase. This allows <code>development-only</code> plugins to not be packaged for production use.</p>
</div>
<div class="paragraph">
<p>The full list of available scopes are defined by the enum <a href="https://grails.apache.org/docs/3.3.7/api/grails/util/BuildScope.html">BuildScope</a>, but here&#8217;s a summary:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>test</code> - when running tests</p>
</li>
<li>
<p><code>functional-test</code> - when running functional tests</p>
</li>
<li>
<p><code>run</code> - for run-app and run-war</p>
</li>
<li>
<p><code>war</code> - when packaging the application as a WAR file</p>
</li>
<li>
<p><code>all</code> - plugin applies to all scopes (default)</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Both properties can be one of:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>a string - a sole inclusion</p>
</li>
<li>
<p>a list - a list of environments or scopes to include</p>
</li>
<li>
<p>a map - for full control, with 'includes' and/or 'excludes' keys that can have string or list values</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>For example,</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> environments = <span class="string"><span class="delimiter">&quot;</span><span class="content">test</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>will only include the plugin in the test environment, whereas</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> environments = [<span class="string"><span class="delimiter">&quot;</span><span class="content">development</span><span class="delimiter">&quot;</span></span>, <span class="string"><span class="delimiter">&quot;</span><span class="content">test</span><span class="delimiter">&quot;</span></span>]</code></pre>
</div>
</div>
<div class="paragraph">
<p>will include it in both the development <em>and</em> test environments. Finally,</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> environments = [<span class="key">includes</span>: [<span class="string"><span class="delimiter">&quot;</span><span class="content">development</span><span class="delimiter">&quot;</span></span>, <span class="string"><span class="delimiter">&quot;</span><span class="content">test</span><span class="delimiter">&quot;</span></span>]]</code></pre>
</div>
</div>
<div class="paragraph">
<p>will do the same thing.</p>
</div>
</div>
<h2 id="artefactApi">18.10 The Artefact API</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/plugins/artefactApi.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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.</p>
</div>
<h2 id="queryingArtefacts">18.10.1 Asking About Available Artefacts</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/plugins/artefactApi/queryingArtefacts.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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="https://grails.org/plugins.html#plugin/elasticsearch">Elasticsearch 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="https://grails.apache.org/docs/3.3.7/api/grails/core/GrailsApplication.html">GrailsApplication</a> that&#8217;s available automatically in controllers and GSPs and can be <a href="services.html#dependencyInjectionServices">injected</a> everywhere else.</p>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">for</span> (cls <span class="keyword">in</span> grailsApplication.&lt;artefactType&gt;Classes) {
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this case, <code>artefactType</code> is the property name form of the artefact type. With core Grails you have:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>domain</p>
</li>
<li>
<p>controller</p>
</li>
<li>
<p>tagLib</p>
</li>
<li>
<p>service</p>
</li>
<li>
<p>codec</p>
</li>
<li>
<p>bootstrap</p>
</li>
<li>
<p>urlMappings</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>So for example, if you want to iterate over all the domain classes, you use:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">for</span> (cls <span class="keyword">in</span> grailsApplication.domainClasses) {
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>and for URL mappings:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">for</span> (cls <span class="keyword">in</span> grailsApplication.urlMappingsClasses) {
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You need to be aware that the objects returned by these properties are not instances of <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html">Class</a>. Instead, they are instances of <a href="https://grails.apache.org/docs/3.3.7/api/grails/core/GrailsClass.html">GrailsClass</a> that has some particularly useful properties and methods, including one for the underlying <code>Class</code>:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>shortName</code> - the class name of the artefact without the package (equivalent of <code>Class.simpleName</code>).</p>
</li>
<li>
<p><code>logicalPropertyName</code> - the artefact name in property form without the 'type' suffix. So <code>MyGreatController</code> becomes 'myGreat'.</p>
</li>
<li>
<p><code>isAbstract()</code> - a boolean indicating whether the artefact class is abstract or not.</p>
</li>
<li>
<p><code>getPropertyValue(name)</code> - returns the value of the given property, whether it&#8217;s a static or an instance one. This works best if the property is initialised on declaration, e.g. <code>static transactional = true</code>.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The artefact API also allows you to fetch classes by name and check whether a class is an artefact:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>get&lt;type&gt;Class(String name)</p>
</li>
<li>
<p>is&lt;type&gt;Class(Class clazz)</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>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.</p>
</div>
<h2 id="customArtefacts">18.10.2 Adding Your Own Artefact Types</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/plugins/artefactApi/customArtefacts.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">MyGrailsPlugin</span> {
<span class="keyword">def</span> artefacts = [ org.somewhere.MyArtefactHandler ]
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>artefacts</code> list can contain either handler classes (as above) or instances of handlers.</p>
</div>
<div class="paragraph">
<p>So, what does an artefact handler look like? Well, put simply it is an implementation of the <a href="https://grails.apache.org/docs/3.3.7/api/grails/core/ArtefactHandler.html">ArtefactHandler</a> interface. To make life a bit easier, there is a skeleton implementation that can readily be extended: <a href="https://grails.apache.org/docs/3.3.7/api/grails/core/ArtefactHandlerAdapter.html">ArtefactHandlerAdapter</a>.</p>
</div>
<div class="paragraph">
<p>In addition to the handler itself, every new artefact needs a corresponding wrapper class that implements <a href="https://grails.apache.org/docs/3.3.7/api/grails/core/GrailsClass.html">GrailsClass</a>. Again, skeleton implementations are available such as <a href="https://grails.apache.org/docs/3.3.7/api/org/grails/core/AbstractInjectableGrailsClass.html">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>
</div>
<div class="paragraph">
<p>The best way to understand how both the handler and wrapper classes work is to look at the Quartz plugin:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://github.com/grails-plugins/grails-quartz/blob/master/src/main/groovy/grails/plugins/quartz/GrailsJobClass.java">GrailsJobClass</a></p>
</li>
<li>
<p><a href="https://github.com/grails-plugins/grails-quartz/blob/master/src/main/groovy/grails/plugins/quartz/DefaultGrailsJobClass.java">DefaultGrailsJobClass</a></p>
</li>
<li>
<p><a href="https://github.com/grails-plugins/grails-quartz/blob/master/src/main/groovy/grails/plugins/quartz/JobArtefactHandler.groovy">JobArtefactHandler</a></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Another example is the <a href="http://github.com/pledbrook/grails-shiro">Shiro plugin</a> which adds a realm artefact.</p>
</div>
<a name="16. Grails and Spring"><!-- Legacy link --></a>
<h1 id="spring">19 Grails and Spring</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/spring.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>This section is for advanced users and those who are interested in how Grails integrates with and builds on the <a href="http://spring.io/">Spring Framework</a>. It is also useful for <a href="plugins.html">plugin developers</a> considering doing runtime configuration Grails.</p>
</div>
<a name="16.2 Configuring Additional Beans"><!-- Legacy link --></a>
<h2 id="springdslAdditional">19.1 Configuring Additional Beans</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/spring/springdslAdditional.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_using_the_spring_bean_dsl">Using the Spring Bean DSL</h4>
<div class="paragraph">
<p>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="#springdsl">Spring DSL</a>. Beans are defined inside a <code>beans</code> property (a Closure):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">beans = {
<span class="comment">// beans here</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>As a simple example you can configure a bean with the following syntax:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">my.company.MyBeanImpl</span>
beans = {
myBean(MyBeanImpl) {
someProperty = <span class="integer">42</span>
otherProperty = <span class="string"><span class="delimiter">&quot;</span><span class="content">blue</span><span class="delimiter">&quot;</span></span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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&#8217;s name (in this case <code>myBean</code>):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ExampleController</span> {
<span class="keyword">def</span> myBean
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Using the DSL has the advantage that you can mix bean declarations and logic, for example based on the <a href="conf.html#environments">environment</a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.util.Environment</span>
<span class="keyword">import</span> <span class="include">my.company.mock.MockImpl</span>
<span class="keyword">import</span> <span class="include">my.company.MyBeanImpl</span>
beans = {
<span class="keyword">switch</span>(Environment.current) {
<span class="keyword">case</span> Environment.PRODUCTION:
myBean(MyBeanImpl) {
someProperty = <span class="integer">42</span>
otherProperty = <span class="string"><span class="delimiter">&quot;</span><span class="content">blue</span><span class="delimiter">&quot;</span></span>
}
<span class="keyword">break</span>
<span class="keyword">case</span> Environment.DEVELOPMENT:
myBean(MockImpl) {
someProperty = <span class="integer">42</span>
otherProperty = <span class="string"><span class="delimiter">&quot;</span><span class="content">blue</span><span class="delimiter">&quot;</span></span>
}
<span class="keyword">break</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.util.Environment</span>
<span class="keyword">import</span> <span class="include">my.company.mock.MockImpl</span>
<span class="keyword">import</span> <span class="include">my.company.MyBeanImpl</span>
beans = {
<span class="keyword">if</span> (application.config.my.company.mockService) {
myBean(MockImpl) {
someProperty = <span class="integer">42</span>
otherProperty = <span class="string"><span class="delimiter">&quot;</span><span class="content">blue</span><span class="delimiter">&quot;</span></span>
}
} <span class="keyword">else</span> {
myBean(MyBeanImpl) {
someProperty = <span class="integer">42</span>
otherProperty = <span class="string"><span class="delimiter">&quot;</span><span class="content">blue</span><span class="delimiter">&quot;</span></span>
}
}
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
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.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_using_xml">Using XML</h4>
<div class="paragraph">
<p>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&#8217;t automatically generated now. But it is still supported - you just need to create it yourself.</p>
</div>
<div class="paragraph">
<p>This file is typical Spring XML file and the Spring documentation has an <a href="http://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/beans.html#beans-basics">excellent reference</a> on how to configure Spring beans.</p>
</div>
<div class="paragraph">
<p>The <code>myBean</code> bean that we configured using the DSL would be configured with this syntax in the XML file:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;bean</span> <span class="attribute-name">id</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">myBean</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">class</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">my.company.MyBeanImpl</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
<span class="tag">&lt;property</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">someProperty</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">42</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
<span class="tag">&lt;property</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">otherProperty</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">blue</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
<span class="tag">&lt;/bean&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Like the other bean it can be auto-wired into any class that supports dependency injection:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">ExampleController</span> {
<span class="keyword">def</span> myBean
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_referencing_existing_beans">Referencing Existing Beans</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">beans = {
myBean(MyBeanImpl) {
someProperty = <span class="integer">42</span>
otherProperty = <span class="string"><span class="delimiter">&quot;</span><span class="content">blue</span><span class="delimiter">&quot;</span></span>
bookService = ref(<span class="string"><span class="delimiter">&quot;</span><span class="content">bookService</span><span class="delimiter">&quot;</span></span>)
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>or like this in XML:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;bean</span> <span class="attribute-name">id</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">myBean</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">class</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">my.company.MyBeanImpl</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
<span class="tag">&lt;property</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">someProperty</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">42</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
<span class="tag">&lt;property</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">otherProperty</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">value</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">blue</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
<span class="tag">&lt;property</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">bookService</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">ref</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">bookService</span><span class="delimiter">&quot;</span></span> <span class="tag">/&gt;</span>
<span class="tag">&lt;/bean&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> my.company
<span class="type">class</span> <span class="class">MyBeanImpl</span> {
<span class="predefined-type">Integer</span> someProperty
<span class="predefined-type">String</span> otherProperty
BookService bookService <span class="comment">// or just &quot;def bookService&quot;</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>or in Java like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">package</span> my.company;
<span class="type">class</span> <span class="class">MyBeanImpl</span> {
<span class="directive">private</span> BookService bookService;
<span class="directive">private</span> <span class="predefined-type">Integer</span> someProperty;
<span class="directive">private</span> <span class="predefined-type">String</span> otherProperty;
<span class="directive">public</span> <span class="type">void</span> setBookService(BookService theBookService) {
<span class="local-variable">this</span>.bookService = theBookService;
}
<span class="directive">public</span> <span class="type">void</span> setSomeProperty(<span class="predefined-type">Integer</span> someProperty) {
<span class="local-variable">this</span>.someProperty = someProperty;
}
<span class="directive">public</span> <span class="type">void</span> setOtherProperty(<span class="predefined-type">String</span> otherProperty) {
<span class="local-variable">this</span>.otherProperty = otherProperty;
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Using <code>ref</code> (in XML or the DSL) is very powerful since it configures a runtime reference, so the referenced bean doesn&#8217;t have to exist yet. As long as it&#8217;s in place when the final application context configuration occurs, everything will be resolved correctly.</p>
</div>
<div class="paragraph">
<p>For a full reference of the available beans see the plugin reference in the reference guide.</p>
</div>
</div>
<a name="16.3 Runtime Spring with the Beans DSL"><!-- Legacy link --></a>
<h2 id="springdsl">19.2 Runtime Spring with the Beans DSL</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/spring/springdsl.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>This Bean builder in Grails aims to provide a simplified way of wiring together dependencies that uses Spring at its core.</p>
</div>
<div class="paragraph">
<p>In addition, Spring&#8217;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="https://grails.apache.org/docs/3.3.7/api/grails/spring/BeanBuilder.html">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>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="sect3">
<h4 id="_the_beanbuilder_class">The BeanBuilder class</h4>
<div class="paragraph">
<p>Grails provides a <a href="https://grails.apache.org/docs/3.3.7/api/grails/spring/BeanBuilder.html">grails.spring.BeanBuilder</a> class that uses dynamic Groovy to construct bean definitions. The basics are as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">org.apache.commons.dbcp.BasicDataSource</span>
<span class="keyword">import</span> <span class="include">org.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean</span>
<span class="keyword">import</span> <span class="include">org.springframework.context.ApplicationContext</span>
<span class="keyword">import</span> <span class="include">grails.spring.BeanBuilder</span>
<span class="keyword">def</span> bb = <span class="keyword">new</span> BeanBuilder()
bb.beans {
dataSource(BasicDataSource) {
driverClassName = <span class="string"><span class="delimiter">&quot;</span><span class="content">org.h2.Driver</span><span class="delimiter">&quot;</span></span>
url = <span class="string"><span class="delimiter">&quot;</span><span class="content">jdbc:h2:mem:grailsDB</span><span class="delimiter">&quot;</span></span>
username = <span class="string"><span class="delimiter">&quot;</span><span class="content">sa</span><span class="delimiter">&quot;</span></span>
password = <span class="string"><span class="delimiter">&quot;</span><span class="delimiter">&quot;</span></span>
}
sessionFactory(ConfigurableLocalSessionFactoryBean) {
dataSource = ref(<span class="string"><span class="delimiter">'</span><span class="content">dataSource</span><span class="delimiter">'</span></span>)
hibernateProperties = [<span class="string"><span class="delimiter">&quot;</span><span class="content">hibernate.hbm2ddl.auto</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">create-drop</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">hibernate.show_sql</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">true</span><span class="delimiter">&quot;</span></span>]
}
}
ApplicationContext appContext = bb.createApplicationContext()</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Within <a href="plugins.html">plugins</a> and the <code>grails-app/conf/spring/resources.groovy</code> file you don&#8217;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.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>This example shows how you would configure Hibernate with a data source with the <code>BeanBuilder</code> class.</p>
</div>
<div class="paragraph">
<p>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&#8217;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>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>Certain special properties related to bean management can also be set by the builder, as seen in the following code:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">sessionFactory(ConfigurableLocalSessionFactoryBean) { bean -&gt;
<span class="comment">// Autowiring behaviour. The other option is 'byType'. &lt;&lt;autowire&gt;&gt;</span>
bean.autowire = <span class="string"><span class="delimiter">'</span><span class="content">byName</span><span class="delimiter">'</span></span>
<span class="comment">// Sets the initialisation method to 'init'. [init-method]</span>
bean.initMethod = <span class="string"><span class="delimiter">'</span><span class="content">init</span><span class="delimiter">'</span></span>
<span class="comment">// Sets the destruction method to 'destroy'. [destroy-method]</span>
bean.destroyMethod = <span class="string"><span class="delimiter">'</span><span class="content">destroy</span><span class="delimiter">'</span></span>
<span class="comment">// Sets the scope of the bean. &lt;&lt;scope&gt;&gt;</span>
bean.scope = <span class="string"><span class="delimiter">'</span><span class="content">request</span><span class="delimiter">'</span></span>
dataSource = ref(<span class="string"><span class="delimiter">'</span><span class="content">dataSource</span><span class="delimiter">'</span></span>)
hibernateProperties = [<span class="string"><span class="delimiter">&quot;</span><span class="content">hibernate.hbm2ddl.auto</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">create-drop</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">hibernate.show_sql</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">true</span><span class="delimiter">&quot;</span></span>]
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The strings in square brackets are the names of the equivalent bean attributes in Spring&#8217;s XML definition.</p>
</div>
</div>
<div class="sect3">
<h4 id="_using_beanbuilder_with_spring_mvc">Using BeanBuilder with Spring MVC</h4>
<div class="paragraph">
<p>Include the <code>grails-spring-&lt;version&gt;.jar</code> file in your classpath to use BeanBuilder in a regular Spring MVC application. Then add the following <code>&lt;context-param&gt;</code> values to your <code>/WEB-INF/web.xml</code> file:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;context-param&gt;</span>
<span class="tag">&lt;param-name&gt;</span>contextConfigLocation<span class="tag">&lt;/param-name&gt;</span>
<span class="tag">&lt;param-value&gt;</span>/WEB-INF/applicationContext.groovy<span class="tag">&lt;/param-value&gt;</span>
<span class="tag">&lt;/context-param&gt;</span>
<span class="tag">&lt;context-param&gt;</span>
<span class="tag">&lt;param-name&gt;</span>contextClass<span class="tag">&lt;/param-name&gt;</span>
<span class="tag">&lt;param-value&gt;</span>
grails.web.servlet.context.GrailsWebApplicationContext
<span class="tag">&lt;/param-value&gt;</span>
<span class="tag">&lt;/context-param&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Then create a <code>/WEB-INF/applicationContext.groovy</code> file that does the rest:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">org.apache.commons.dbcp.BasicDataSource</span>
beans {
dataSource(BasicDataSource) {
driverClassName = <span class="string"><span class="delimiter">&quot;</span><span class="content">org.h2.Driver</span><span class="delimiter">&quot;</span></span>
url = <span class="string"><span class="delimiter">&quot;</span><span class="content">jdbc:h2:mem:grailsDB</span><span class="delimiter">&quot;</span></span>
username = <span class="string"><span class="delimiter">&quot;</span><span class="content">sa</span><span class="delimiter">&quot;</span></span>
password = <span class="string"><span class="delimiter">&quot;</span><span class="delimiter">&quot;</span></span>
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_loading_bean_definitions_from_the_file_system">Loading Bean Definitions from the File System</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> bb = <span class="keyword">new</span> BeanBuilder()
bb.loadBeans(<span class="string"><span class="delimiter">&quot;</span><span class="content">classpath:*SpringBeans.groovy</span><span class="delimiter">&quot;</span></span>)
<span class="keyword">def</span> applicationContext = bb.createApplicationContext()</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">org.apache.commons.dbcp.BasicDataSource</span>
<span class="keyword">import</span> <span class="include">org.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean</span>
beans {
dataSource(BasicDataSource) {
driverClassName = <span class="string"><span class="delimiter">&quot;</span><span class="content">org.h2.Driver</span><span class="delimiter">&quot;</span></span>
url = <span class="string"><span class="delimiter">&quot;</span><span class="content">jdbc:h2:mem:grailsDB</span><span class="delimiter">&quot;</span></span>
username = <span class="string"><span class="delimiter">&quot;</span><span class="content">sa</span><span class="delimiter">&quot;</span></span>
password = <span class="string"><span class="delimiter">&quot;</span><span class="delimiter">&quot;</span></span>
}
sessionFactory(ConfigurableLocalSessionFactoryBean) {
dataSource = dataSource
hibernateProperties = [<span class="string"><span class="delimiter">&quot;</span><span class="content">hibernate.hbm2ddl.auto</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">create-drop</span><span class="delimiter">&quot;</span></span>,
<span class="string"><span class="delimiter">&quot;</span><span class="content">hibernate.show_sql</span><span class="delimiter">&quot;</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">true</span><span class="delimiter">&quot;</span></span>]
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_adding_variables_to_the_binding_context">Adding Variables to the Binding (Context)</h4>
<div class="paragraph">
<p>If you&#8217;re loading beans from a script you can set the binding to use by creating a Groovy <code>Binding</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> binding = <span class="keyword">new</span> <span class="predefined-type">Binding</span>()
binding.maxSize = <span class="integer">10000</span>
binding.productGroup = <span class="string"><span class="delimiter">'</span><span class="content">finance</span><span class="delimiter">'</span></span>
<span class="keyword">def</span> bb = <span class="keyword">new</span> BeanBuilder()
bb.binding = binding
bb.loadBeans(<span class="string"><span class="delimiter">&quot;</span><span class="content">classpath:*SpringBeans.groovy</span><span class="delimiter">&quot;</span></span>)
<span class="keyword">def</span> ctx = bb.createApplicationContext()</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then you can access the <code>maxSize</code> and <code>productGroup</code> properties in your DSL files.</p>
</div>
</div>
<a name="16.4 The BeanBuilder DSL Explained"><!-- Legacy link --></a>
<h2 id="theBeanBuilderDSLExplained">19.3 The BeanBuilder DSL Explained</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/spring/theBeanBuilderDSLExplained.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect3">
<h4 id="_using_constructor_arguments">Using Constructor Arguments</h4>
<div class="paragraph">
<p>Constructor arguments can be defined using parameters to each bean-defining method. Put them after the first argument (the Class):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">bb.beans {
exampleBean(MyExampleBean, <span class="string"><span class="delimiter">&quot;</span><span class="content">firstArgument</span><span class="delimiter">&quot;</span></span>, <span class="integer">2</span>) {
someProperty = [<span class="integer">1</span>, <span class="integer">2</span>, <span class="integer">3</span>]
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This configuration corresponds to a <code>MyExampleBean</code> with a constructor that looks like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">MyExampleBean(<span class="predefined-type">String</span> foo, <span class="type">int</span> bar) {
...
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_configuring_the_beandefinition_using_factory_methods">Configuring the BeanDefinition (Using factory methods)</h4>
<div class="paragraph">
<p>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="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/support/AbstractBeanDefinition.html">AbstractBeanDefinition</a> class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">bb.beans {
exampleBean(MyExampleBean) { bean -&gt;
bean.factoryMethod = <span class="string"><span class="delimiter">&quot;</span><span class="content">getInstance</span><span class="delimiter">&quot;</span></span>
bean.singleton = <span class="predefined-constant">false</span>
someProperty = [<span class="integer">1</span>, <span class="integer">2</span>, <span class="integer">3</span>]
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>As an alternative you can also use the return value of the bean defining method to configure the bean:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">bb.beans {
<span class="keyword">def</span> example = exampleBean(MyExampleBean) {
someProperty = [<span class="integer">1</span>, <span class="integer">2</span>, <span class="integer">3</span>]
}
example.factoryMethod = <span class="string"><span class="delimiter">&quot;</span><span class="content">getInstance</span><span class="delimiter">&quot;</span></span>
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_using_factory_beans">Using Factory beans</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">bb.beans {
myFactory(ExampleFactoryBean) {
someProperty = [<span class="integer">1</span>, <span class="integer">2</span>, <span class="integer">3</span>]
}
myBean(myFactory) {
name = <span class="string"><span class="delimiter">&quot;</span><span class="content">blah</span><span class="delimiter">&quot;</span></span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Another common approach is provide the name of the factory method to call on the factory bean. This can be done using Groovy&#8217;s named parameter syntax:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">bb.beans {
myFactory(ExampleFactoryBean) {
someProperty = [<span class="integer">1</span>, <span class="integer">2</span>, <span class="integer">3</span>]
}
myBean(<span class="key">myFactory</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">getInstance</span><span class="delimiter">&quot;</span></span>) {
name = <span class="string"><span class="delimiter">&quot;</span><span class="content">blah</span><span class="delimiter">&quot;</span></span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here the <code>getInstance</code> method on the <code>ExampleFactoryBean</code> bean will be called to create the <code>myBean</code> bean.</p>
</div>
</div>
<div class="sect3">
<h4 id="_creating_bean_references_at_runtime">Creating Bean References at Runtime</h4>
<div class="paragraph">
<p>Sometimes you don&#8217;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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> beanName = <span class="string"><span class="delimiter">&quot;</span><span class="content">example</span><span class="delimiter">&quot;</span></span>
bb.beans {
<span class="string"><span class="delimiter">&quot;</span><span class="inline"><span class="inline-delimiter">${</span>beanName<span class="inline-delimiter">}</span></span><span class="content">Bean</span><span class="delimiter">&quot;</span></span>(MyExampleBean) {
someProperty = [<span class="integer">1</span>, <span class="integer">2</span>, <span class="integer">3</span>]
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> beanName = <span class="string"><span class="delimiter">&quot;</span><span class="content">example</span><span class="delimiter">&quot;</span></span>
bb.beans {
<span class="string"><span class="delimiter">&quot;</span><span class="inline"><span class="inline-delimiter">${</span>beanName<span class="inline-delimiter">}</span></span><span class="content">Bean</span><span class="delimiter">&quot;</span></span>(MyExampleBean) {
someProperty = [<span class="integer">1</span>, <span class="integer">2</span>, <span class="integer">3</span>]
}
anotherBean(AnotherBean) {
example = ref(<span class="string"><span class="delimiter">&quot;</span><span class="inline"><span class="inline-delimiter">${</span>beanName<span class="inline-delimiter">}</span></span><span class="content">Bean</span><span class="delimiter">&quot;</span></span>)
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">ApplicationContext parent = ...<span class="comment">//</span>
<span class="keyword">def</span> bb = <span class="keyword">new</span> BeanBuilder(parent)
bb.beans {
anotherBean(AnotherBean) {
example = ref(<span class="string"><span class="delimiter">&quot;</span><span class="inline"><span class="inline-delimiter">${</span>beanName<span class="inline-delimiter">}</span></span><span class="content">Bean</span><span class="delimiter">&quot;</span></span>, <span class="predefined-constant">true</span>)
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here the second parameter <code>true</code> specifies that the reference will look for the bean in the parent context.</p>
</div>
</div>
<div class="sect3">
<h4 id="_using_anonymous_inner_beans">Using Anonymous (Inner) Beans</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">bb.beans {
marge(Person) {
name = <span class="string"><span class="delimiter">&quot;</span><span class="content">Marge</span><span class="delimiter">&quot;</span></span>
husband = { Person p -&gt;
name = <span class="string"><span class="delimiter">&quot;</span><span class="content">Homer</span><span class="delimiter">&quot;</span></span>
age = <span class="integer">45</span>
props = [<span class="key">overweight</span>: <span class="predefined-constant">true</span>, <span class="key">height</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">1.8m</span><span class="delimiter">&quot;</span></span>]
}
children = [ref(<span class="string"><span class="delimiter">'</span><span class="content">bart</span><span class="delimiter">'</span></span>), ref(<span class="string"><span class="delimiter">'</span><span class="content">lisa</span><span class="delimiter">'</span></span>)]
}
bart(Person) {
name = <span class="string"><span class="delimiter">&quot;</span><span class="content">Bart</span><span class="delimiter">&quot;</span></span>
age = <span class="integer">11</span>
}
lisa(Person) {
name = <span class="string"><span class="delimiter">&quot;</span><span class="content">Lisa</span><span class="delimiter">&quot;</span></span>
age = <span class="integer">9</span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the above example we set the <code>marge</code> bean&#8217;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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">bb.beans {
personFactory(PersonFactory)
marge(Person) {
name = <span class="string"><span class="delimiter">&quot;</span><span class="content">Marge</span><span class="delimiter">&quot;</span></span>
husband = { bean -&gt;
bean.factoryBean = <span class="string"><span class="delimiter">&quot;</span><span class="content">personFactory</span><span class="delimiter">&quot;</span></span>
bean.factoryMethod = <span class="string"><span class="delimiter">&quot;</span><span class="content">newInstance</span><span class="delimiter">&quot;</span></span>
name = <span class="string"><span class="delimiter">&quot;</span><span class="content">Homer</span><span class="delimiter">&quot;</span></span>
age = <span class="integer">45</span>
props = [<span class="key">overweight</span>: <span class="predefined-constant">true</span>, <span class="key">height</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">1.8m</span><span class="delimiter">&quot;</span></span>]
}
children = [ref(<span class="string"><span class="delimiter">'</span><span class="content">bart</span><span class="delimiter">'</span></span>), ref(<span class="string"><span class="delimiter">'</span><span class="content">lisa</span><span class="delimiter">'</span></span>)]
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_abstract_beans_and_parent_bean_definitions">Abstract Beans and Parent Bean Definitions</h4>
<div class="paragraph">
<p>To create an abstract bean definition define a bean without a <code>Class</code> parameter:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">HolyGrailQuest</span> {
<span class="keyword">def</span> <span class="function">start</span>() { println <span class="string"><span class="delimiter">&quot;</span><span class="content">lets begin</span><span class="delimiter">&quot;</span></span> }
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">KnightOfTheRoundTable</span> {
<span class="predefined-type">String</span> name
<span class="predefined-type">String</span> leader
HolyGrailQuest quest
KnightOfTheRoundTable(<span class="predefined-type">String</span> name) {
<span class="local-variable">this</span>.name = name
}
<span class="keyword">def</span> <span class="function">embarkOnQuest</span>() {
quest.start()
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.spring.BeanBuilder</span>
<span class="keyword">def</span> bb = <span class="keyword">new</span> BeanBuilder()
bb.beans {
abstractBean {
leader = <span class="string"><span class="delimiter">&quot;</span><span class="content">Lancelot</span><span class="delimiter">&quot;</span></span>
}
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">bb.beans {
...
quest(HolyGrailQuest)
knights(KnightOfTheRoundTable, <span class="string"><span class="delimiter">&quot;</span><span class="content">Camelot</span><span class="delimiter">&quot;</span></span>) { bean -&gt;
bean.parent = abstractBean
quest = ref(<span class="string"><span class="delimiter">'</span><span class="content">quest</span><span class="delimiter">'</span></span>)
}
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
When using a parent bean you must set the parent property of the bean before setting any other properties on the bean!
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>If you want an abstract bean that has a <code>Class</code> specified you can do it this way:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">import</span> <span class="include">grails.spring.BeanBuilder</span>
<span class="keyword">def</span> bb = <span class="keyword">new</span> BeanBuilder()
bb.beans {
abstractBean(KnightOfTheRoundTable) { bean -&gt;
bean.<span class="string"><span class="delimiter">'</span><span class="content">abstract</span><span class="delimiter">'</span></span> = <span class="predefined-constant">true</span>
leader = <span class="string"><span class="delimiter">&quot;</span><span class="content">Lancelot</span><span class="delimiter">&quot;</span></span>
}
quest(HolyGrailQuest)
knights(<span class="string"><span class="delimiter">&quot;</span><span class="content">Camelot</span><span class="delimiter">&quot;</span></span>) { bean -&gt;
bean.parent = abstractBean
quest = quest
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
</div>
<div class="sect3">
<h4 id="_using_spring_namespaces">Using Spring Namespaces</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">xmlns <span class="key">context</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">http://www.springframework.org/schema/context</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>and then invoking a method that matches the names of the Spring namespace tag and its associated attributes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">context.<span class="string"><span class="delimiter">'</span><span class="content">component-scan</span><span class="delimiter">'</span></span>(<span class="string"><span class="delimiter">'</span><span class="content">base-package</span><span class="delimiter">'</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">my.company.domain</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can do some useful things with Spring namespaces, such as looking up a JNDI resource:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">xmlns <span class="key">jee</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">http://www.springframework.org/schema/jee</span><span class="delimiter">&quot;</span></span>
jee.<span class="string"><span class="delimiter">'</span><span class="content">jndi-lookup</span><span class="delimiter">'</span></span>(<span class="key">id</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">dataSource</span><span class="delimiter">&quot;</span></span>, <span class="string"><span class="delimiter">'</span><span class="content">jndi-name</span><span class="delimiter">'</span></span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">java:comp/env/myDataSource</span><span class="delimiter">&quot;</span></span>)</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">Person</span> {
<span class="type">int</span> age
<span class="predefined-type">String</span> name
<span class="type">void</span> birthday() {
++age;
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BirthdayCardSender</span> {
<span class="predefined-type">List</span> peopleSentCards = <span class="type">[]</span>
<span class="type">void</span> onBirthday(Person person) {
peopleSentCards &lt;&lt; person
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can define an aspect that uses a pointcut to detect whenever the <code>birthday()</code> method is called:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">xmlns <span class="key">aop</span>:<span class="string"><span class="delimiter">&quot;</span><span class="content">http://www.springframework.org/schema/aop</span><span class="delimiter">&quot;</span></span>
fred(Person) {
name = <span class="string"><span class="delimiter">&quot;</span><span class="content">Fred</span><span class="delimiter">&quot;</span></span>
age = <span class="integer">45</span>
}
birthdayCardSenderAspect(BirthdayCardSender)
aop {
config(<span class="string"><span class="delimiter">&quot;</span><span class="content">proxy-target-class</span><span class="delimiter">&quot;</span></span>: <span class="predefined-constant">true</span>) {
aspect(<span class="key">id</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">sendBirthdayCard</span><span class="delimiter">&quot;</span></span>, <span class="key">ref</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">birthdayCardSenderAspect</span><span class="delimiter">&quot;</span></span>) {
after <span class="key">method</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">onBirthday</span><span class="delimiter">&quot;</span></span>,
<span class="key">pointcut</span>: <span class="string"><span class="delimiter">&quot;</span><span class="content">execution(void ..Person.birthday()) and this(person)</span><span class="delimiter">&quot;</span></span>
}
}
}</code></pre>
</div>
</div>
</div>
<a name="16.5 Property Placeholder Configuration"><!-- Legacy link --></a>
<h2 id="propertyPlaceholderConfiguration">19.4 Property Placeholder Configuration</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/spring/propertyPlaceholderConfiguration.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails supports the notion of property placeholder configuration through an extended version of Spring&#8217;s <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html">PropertyPlaceholderConfigurer</a>.</p>
</div>
<div class="paragraph">
<p>Settings defined in either <a href="http://docs.groovy-lang.org/latest/html/gapi/groovy/util/ConfigSlurper.html">ConfigSlurper</a> scripts or Java properties files can be used as placeholder values for Spring configuration in <code>grails-app/conf/spring/resources.xml</code> and <code>grails-app/conf/spring/resources.groovy</code>. For example given the following entries in <code>grails-app/conf/application.groovy</code> (or an externalized config):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">database.driver=<span class="string"><span class="delimiter">&quot;</span><span class="content">com.mysql.jdbc.Driver</span><span class="delimiter">&quot;</span></span>
database.dbname=<span class="string"><span class="delimiter">&quot;</span><span class="content">mysql:mydb</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>You can then specify placeholders in <code>resources.xml</code> as follows using the familiar ${..} syntax:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="tag">&lt;bean</span> <span class="attribute-name">id</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">dataSource</span><span class="delimiter">&quot;</span></span>
<span class="attribute-name">class</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">org.springframework.jdbc.datasource.DriverManagerDataSource</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
<span class="tag">&lt;property</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">driverClassName</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
<span class="tag">&lt;value&gt;</span>${database.driver}<span class="tag">&lt;/value&gt;</span>
<span class="tag">&lt;/property&gt;</span>
<span class="tag">&lt;property</span> <span class="attribute-name">name</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">url</span><span class="delimiter">&quot;</span></span><span class="tag">&gt;</span>
<span class="tag">&lt;value&gt;</span>jdbc:${database.dbname}<span class="tag">&lt;/value&gt;</span>
<span class="tag">&lt;/property&gt;</span>
<span class="tag">&lt;/bean&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>To specify placeholders in <code>resources.groovy</code> you need to use single quotes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">dataSource(org.springframework.jdbc.datasource.DriverManagerDataSource) {
driverClassName = <span class="string"><span class="delimiter">'</span><span class="content">${database.driver}</span><span class="delimiter">'</span></span>
url = <span class="string"><span class="delimiter">'</span><span class="content">jdbc:${database.dbname}</span><span class="delimiter">'</span></span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This sets the property value to a literal string which is later resolved against the config by Spring&#8217;s PropertyPlaceholderConfigurer.</p>
</div>
<div class="paragraph">
<p>A better option for <code>resources.groovy</code> is to access properties through the <code>grailsApplication</code> variable:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">dataSource(org.springframework.jdbc.datasource.DriverManagerDataSource) {
driverClassName = grailsApplication.config.database.driver
url = <span class="string"><span class="delimiter">&quot;</span><span class="content">jdbc</span><span class="content">\:</span><span class="inline"><span class="inline-delimiter">${</span>grailsApplication.config.database.dbname<span class="inline-delimiter">}</span></span><span class="delimiter">&quot;</span></span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Using this approach will keep the types as defined in your config.</p>
</div>
<a name="16.6 Property Override Configuration"><!-- Legacy link --></a>
<h2 id="propertyOverrideConfiguration">19.5 Property Override Configuration</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/spring/propertyOverrideConfiguration.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails supports setting of bean properties via <a href="conf.html">configuration</a>.</p>
</div>
<div class="paragraph">
<p>You define a <code>beans</code> block with the names of beans and their values:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">beans {
bookService {
webServiceURL = <span class="string"><span class="delimiter">&quot;</span><span class="content">http://www.amazon.com</span><span class="delimiter">&quot;</span></span>
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The general format is:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">&lt;&lt;bean name&gt;&gt;.&lt;&lt;property name&gt;&gt; = &lt;&lt;value&gt;&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>The same configuration in a Java properties file would be:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">beans.bookService.webServiceURL=<span class="key">http</span>:<span class="comment">//www.amazon.com</span></code></pre>
</div>
</div>
<h2 id="actuators">19.6 Spring Boot Actuators</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/spring/actuators.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p><a href="https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html">Spring Boot Actuator endpoints</a> allow you to monitor and interact with your application. Spring Boot includes a number of built-in endpoints. For example the <code>health</code> endpoint provides basic application health information.</p>
</div>
<div class="paragraph">
<p>These endpoints are disabled by default since Grails 3.1.8.</p>
</div>
<div class="paragraph">
<p>You can enable actuator endpoints in your <code>application.yml</code> as follows:</p>
</div>
<div class="listingblock">
<div class="title">grails-app/conf/application.yml</div>
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yml"><span class="key">endpoints</span>:
<span class="key">enabled</span>: <span class="string"><span class="content">true</span></span></code></pre>
</div>
</div>
<a name="18. Scaffolding"><!-- Legacy link --></a>
<h1 id="scaffolding">20 Scaffolding</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/scaffolding.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Scaffolding lets you generate some basic CRUD interfaces for a domain class, including:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>The necessary <a href="theWebLayer.html#gsp">views</a></p>
</li>
<li>
<p>Controller actions for create/read/update/delete (CRUD) operations</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The way for an application to express a dependency on the scaffolding plugin is by including the following in <code>build.gradle</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">dependencies {
<span class="comment">// ...</span>
compile <span class="string"><span class="delimiter">&quot;</span><span class="content">org.grails.plugins:scaffolding</span><span class="delimiter">&quot;</span></span>
<span class="comment">// ...</span>
}</code></pre>
</div>
</div>
<div class="sect3">
<h4 id="_dynamic_scaffolding">Dynamic Scaffolding</h4>
<div class="paragraph">
<p>The simplest way to get started with scaffolding is to enable it by setting the <code>scaffold</code> property in the controller to a specific domain class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> {
<span class="directive">static</span> scaffold = <span class="predefined-type">Book</span> <span class="comment">// Or any other domain class such as &quot;Author&quot;, &quot;Publisher&quot;</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>With this configured, when you start your application the actions and views will be autogenerated at runtime. The following actions are dynamically implemented by default by the runtime scaffolding mechanism:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>index</p>
</li>
<li>
<p>show</p>
</li>
<li>
<p>edit</p>
</li>
<li>
<p>delete</p>
</li>
<li>
<p>create</p>
</li>
<li>
<p>save</p>
</li>
<li>
<p>update</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>A CRUD interface will also be generated. To access this open <code><a href="http://localhost:8080/book" class="bare">http://localhost:8080/book</a></code> in a browser.</p>
</div>
<div class="paragraph">
<p>Note: The old alternative of defining <code>scaffold</code> property:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> {
<span class="directive">static</span> scaffold = <span class="predefined-constant">true</span>
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>is no longer supported above Grails 3.0.</p>
</div>
<div class="paragraph">
<p>If you prefer to keep your domain model in Java and <a href="hibernate.html">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>
</div>
<div class="paragraph">
<p>You can add new actions to a scaffolded controller, for example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> {
<span class="directive">static</span> scaffold = <span class="predefined-type">Book</span>
<span class="keyword">def</span> <span class="function">changeAuthor</span>() {
<span class="keyword">def</span> b = <span class="predefined-type">Book</span>.get(params.id)
b.author = Author.get(params[<span class="string"><span class="delimiter">&quot;</span><span class="content">author.id</span><span class="delimiter">&quot;</span></span>])
b.save()
<span class="comment">// redirect to a scaffolded action</span>
redirect(<span class="key">action</span>:show)
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also override the scaffolded actions:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="type">class</span> <span class="class">BookController</span> {
<span class="directive">static</span> scaffold = <span class="predefined-type">Book</span>
<span class="comment">// overrides scaffolded action to return both authors and books</span>
<span class="keyword">def</span> <span class="function">index</span>() {
[<span class="key">bookInstanceList</span>: <span class="predefined-type">Book</span>.list(),
<span class="key">bookInstanceTotal</span>: <span class="predefined-type">Book</span>.count(),
<span class="key">authorInstanceList</span>: Author.list()]
}
<span class="keyword">def</span> <span class="function">show</span>() {
<span class="keyword">def</span> book = <span class="predefined-type">Book</span>.get(params.id)
log.error(<span class="string"><span class="delimiter">&quot;</span><span class="content">{}</span><span class="delimiter">&quot;</span></span>, book)
[bookInstance : book]
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>All of this is what is known as "dynamic scaffolding" where the CRUD interface is generated dynamically at runtime.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
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.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Also, the standard scaffold views expect model variables of the form <code>&lt;propertyName&gt;InstanceList</code> for collections and <code>&lt;propertyName&gt;Instance</code> for single instances. It&#8217;s tempting to use properties like 'books' and 'book', but those won&#8217;t work.</p>
</div>
</div>
<div class="sect3">
<h4 id="_static_scaffolding">Static Scaffolding</h4>
<div class="paragraph">
<p>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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails generate-controller <span class="predefined-type">Book</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>or to generate the views:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails generate-views <span class="predefined-type">Book</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>or to generate everything:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails generate-all <span class="predefined-type">Book</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>If you have a domain class in a package or are generating from a <a href="hibernate.html">Hibernate mapped class</a> remember to include the fully qualified package name:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails generate-all com.bookstore.Book</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_customizing_the_generated_views">Customizing the Generated Views</h4>
<div class="paragraph">
<p>The views adapt to <a href="constraints.html">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>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> constraints = {
title()
releaseDate()
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also get the generator to generate lists instead of text inputs if you use the <code>inList</code> constraint:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> constraints = {
title()
category(<span class="key">inList</span>: [<span class="string"><span class="delimiter">&quot;</span><span class="content">Fiction</span><span class="delimiter">&quot;</span></span>, <span class="string"><span class="delimiter">&quot;</span><span class="content">Non-fiction</span><span class="delimiter">&quot;</span></span>, <span class="string"><span class="delimiter">&quot;</span><span class="content">Biography</span><span class="delimiter">&quot;</span></span>])
releaseDate()
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or if you use the <code>range</code> constraint on a number:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> constraints = {
age(<span class="key">range</span>:<span class="integer">18</span>..<span class="integer">65</span>)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Restricting the size with a constraint also effects how many characters can be entered in the d view:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="keyword">def</span> constraints = {
name(<span class="key">size</span>:<span class="integer">0</span>..<span class="integer">30</span>)
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_the_fields_plugin">The Fields Plugin</h4>
<div class="paragraph">
<p>The Grails scaffolding templates make use of the <a href="https://grails.org/plugins.html#plugin&#47;fields">The Fields Plugin</a>. Once you&#8217;ve generated the scaffold views, you can customize the forms and tables using the <code>Taglib</code> provided by the plugin (see the <a href="http://grails3-plugins.github.io/fields/snapshot/">Fields plugin docs</a> for details).</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml"><span class="error">&lt;</span>%-- Generate an HTML table from bookInstanceList, showing only 'title' and 'category' columns --%<span class="error">&gt;</span>
<span class="tag">&lt;f:table</span> <span class="attribute-name">collection</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">bookInstanceList</span><span class="delimiter">&quot;</span></span> <span class="attribute-name">properties</span>=<span class="string"><span class="delimiter">&quot;</span><span class="content">['title', 'category']</span><span class="delimiter">&quot;</span></span><span class="tag">/&gt;</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_customizing_the_scaffolding_templates">Customizing the Scaffolding templates</h4>
<div class="paragraph">
<p>The templates used by Grails to generate the controller and views can be customized by installing the templates with the <a href="../ref/Command%20Line/install-templates.html">install-templates</a> command.</p>
</div>
</div>
<a name="19. Deployment"><!-- Legacy link --></a>
<h1 id="deployment">21 Deployment</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/deployment.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails applications can be deployed in a number of ways, each of which has its pros and cons.</p>
</div>
<h2 id="deploymentStandalone">21.1 Standalone</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/deployment/deploymentStandalone.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect2">
<h3 id="__grails_run_app">"grails run-app"</h3>
<div class="paragraph">
<p>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 any changes to application files.</p>
</div>
<div class="paragraph">
<p>You can run the application in the production environment using:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails prod run-app</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can run the app using the <code>bootRun</code> Gradle task. The next command uses the <a href="https://docs.gradle.org/current/userguide/gradle_wrapper.html">Gradle Wrapper</a>.</p>
</div>
<div class="paragraph">
<p><code>./gradlew bootRun</code></p>
</div>
<div class="paragraph">
<p>You can specify an environment supplying <code>grails.env</code> system property.</p>
</div>
<div class="paragraph">
<p><code>./gradlew -Dgrails.env=prod bootRun</code></p>
</div>
</div>
<div class="sect2">
<h3 id="_runnable_war_or_jar_file">Runnable WAR or JAR file</h3>
<div class="paragraph">
<p>Another way to deploy in Grails 3.0 or above is to use the new support for runnable JAR or WAR files. To create runnable archives, run <code>grails package</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="xml">grails package</code></pre>
</div>
</div>
<div class="paragraph">
<p>Alternatively, you could use the <code>assemble</code> Gradle task.</p>
</div>
<div class="paragraph">
<p><code>./gradlew assemble</code></p>
</div>
<div class="paragraph">
<p>You can then run either the WAR file or the JAR using your Java installation:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">java -Dgrails.env=prod -jar build/libs/mywar-<span class="float">0.1</span>.war (or .jar)</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_a_tar_zip_distribution">A TAR/ZIP distribution</h3>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
Note: TAR/ZIP distribution assembly has been removed from Grails 3.1.
</td>
</tr>
</table>
</div>
</div>
<h2 id="deploymentContainer">21.2 Container Deployment (e.g. Tomcat)</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/deployment/deploymentContainer.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails apps can be deployed to a Servlet Container or Application Server.</p>
</div>
<div class="sect2">
<h3 id="_war_file">WAR file</h3>
<div class="paragraph">
<p>A common approach to Grails application deployment in production is to deploy to an existing Servlet container via a WAR file. Containers allow multiple applications to be deployed on the same port with different paths.</p>
</div>
<div class="paragraph">
<p>Creating a WAR file is as simple as executing the <a href="../ref/Command%20Line/war.html">war</a> command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails war</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will produce a WAR file that can be deployed to a container, in the <code>build/libs</code> directory.</p>
</div>
<div class="paragraph">
<p>Note that by default Grails will include an embeddable version of Tomcat inside the WAR file so that it is runnable (see the previous section), this can cause problems if you deploy to a different version of Tomcat. If you don&#8217;t intend to use the embedded container then you should change the scope of the Tomcat dependencies to <code>provided</code> prior to deploying to your production container in <code>build.gradle</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">provided <span class="string"><span class="delimiter">&quot;</span><span class="content">org.springframework.boot:spring-boot-starter-tomcat</span><span class="delimiter">&quot;</span></span></code></pre>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_application_servers">Application servers</h2>
<div class="sectionbody">
<div class="paragraph">
<p>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">Grails website</a> contains a list of application servers that Grails has been tested with, along with any additional steps required to get a Grails WAR file working.</p>
</div>
</div>
</div>
<h2 id="deploymentTasks">21.3 Deployment Configuration Tasks</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/deployment/deploymentTasks.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect2">
<h3 id="_setting_up_https_and_ssl_certificates_for_standalone_deployment">Setting up HTTPS and SSL certificates for standalone deployment</h3>
<div class="paragraph">
<p>To configure an SSL certificate and to listen on an HTTPS port instead of HTTP, add properties like these to <code>application.yml</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy"><span class="key">server</span>:
<span class="key">port</span>: <span class="integer">8443</span> <span class="error">#</span> The port to listen on
<span class="key">ssl</span>:
<span class="key">enabled</span>: <span class="predefined-constant">true</span> <span class="error">#</span> Activate HTTPS mode on the server port
key-<span class="key">store</span>: &lt;the-location-of-your-keystore&gt; <span class="error">#</span> e.g. <span class="regexp"><span class="delimiter">/</span><span class="content">etc</span><span class="delimiter">/</span></span>tomcat7/keystore/tomcat.keystore
key-store-<span class="key">password</span>: &lt;your-key-store-password&gt; <span class="error">#</span> e.g. changeit
key-<span class="key">alias</span>: &lt;your-key-alias&gt; <span class="error">#</span> e.g. tomcat
key-<span class="key">password</span>: &lt;usually-the-same-<span class="keyword">as</span>-your-key-store-password&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>These settings control the embedded Tomcat container for a production deployment. Alternatively, the properties can be specified on the command-line. Example: <code>-Dserver.ssl.enabled=true -Dserver.ssl.key-store=/path/to/keystore</code>.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Configuration of both an HTTP and HTTPS connector via application properties is not supported. If you want to have both, then you&#8217;ll need to configure one of them programmatically. (More information on how to do this can be found in the how-to guide below.)
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>There are other relevant settings. Further reference:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://docs.spring.io/spring-boot/docs/current/reference/html/howto-embedded-servlet-containers.html#howto-configure-ssl">Spring Boot: How to configure SSL on embedded servlet containers</a></p>
</li>
<li>
<p><a href="https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html">Spring Boot: Common Application Properties</a></p>
</li>
</ul>
</div>
</div>
<h1 id="contributing">22 Contributing to Grails</h1>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/contributing.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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="plugins.html">writing useful plugins</a> and making them publicly available. In this chapter, we&#8217;ll look at some of the other options.</p>
</div>
<h2 id="issues">22.1 Report Issues in Github's issue tracker</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/contributing/issues.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>Grails uses Github to track issues in the <a href="https://github.com/grails/grails-core/issues">core framework</a>. Similarly for its documentation there is a <a href="https://github.com/grails/grails-doc/issues">separate tracker</a>. If you&#8217;ve found a bug or wish to see a particular feature added, these are the places to start. You&#8217;ll need to create a (free) github account in order to either submit an issue or comment on an existing one in either of these.</p>
</div>
<div class="paragraph">
<p>When submitting issues, please provide as much information as possible and in the case of bugs, make sure you explain which versions of Groovy, Grails and various plugins you are using. Other environment details - OS version, JDK, Gradle etc. should also be included. Also, an issue is much more likely to be dealt with if you upload a reproducible sample application on a github repository and provide a link in the issue.</p>
</div>
<div class="sect2">
<h3 id="_reviewing_issues">Reviewing issues</h3>
<div class="paragraph">
<p>There are quite a few old issues in github, some of which may no longer be valid. The core team can&#8217;t track down these alone, so a very simple contribution that you can make is to verify one or two issues occasionally.</p>
</div>
<div class="paragraph">
<p>Which issues need verification? Going to the <a href="https://github.com/grails/grails-core/issues?q=is%3Aopen+is%3Aissue">issue tracker</a> will display all issues that haven&#8217;t been resolved.</p>
</div>
<div class="paragraph">
<p>Once you&#8217;ve verified an issue, simply add a short comment explaining what you found. Be sure to metion your environment details and grails version.</p>
</div>
</div>
<h2 id="build">22.2 Build From Source and Run Tests</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/contributing/build.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>If you&#8217;re interested in contributing fixes and features to any part of grails, you will have to learn how to get hold of the project&#8217;s source, build it and test it with your own applications. Before you start, make sure you have:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>A JDK (7 or above)</p>
</li>
<li>
<p>A git client</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>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">GitHub</a> in several repositories owned by the <a href="http://github.com/grails">"grails" GitHub user</a>. This is a simple case of cloning the repository you&#8217;re interested in. For example, to get the core framework run:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">git clone <span class="key">http</span>:<span class="comment">//github.com/grails/grails-core.git</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="sect2">
<h3 id="_creating_a_grails_installation">Creating a Grails installation</h3>
<div class="paragraph">
<p>If you look at the project structure, you&#8217;ll see that it doesn&#8217;t look much like a standard <code>GRAILS_HOME</code> installation. But, it&#8217;s very simple to turn it into one. Just run this from the root directory of the project:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">.<span class="regexp"><span class="delimiter">/</span><span class="content">gradlew install</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>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 <code>grails</code> command to run, you&#8217;ll be using the version you just built.</p>
</div>
<div class="paragraph">
<p>If you are using <a href="http://sdkman.io">SDKMAN</a> then that can also be used to work with this local installation via the following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">sdk install grails dev /path/to/grails-core</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now you will have a dev version in your local which you can use to test your features.</p>
</div>
</div>
<div class="sect2">
<h3 id="_running_the_test_suite">Running the test suite</h3>
<div class="paragraph">
<p>All you have to do to run the full suite of tests is:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">.<span class="regexp"><span class="delimiter">/</span><span class="content">gradlew test</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>These will take a while (15-30 mins), so consider running individual tests using the command line. For example, to run the test spec <code>BinaryPluginSpec</code> simply execute the following command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">.<span class="regexp"><span class="delimiter">/</span><span class="content">gradlew :grails-core:test --tests *.BinaryPluginSpec</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that you need to specify the sub-project that the test case resides in, because the top-level "test" target won&#8217;t work&#8230;&#8203;.</p>
</div>
</div>
<div class="sect2">
<h3 id="_developing_in_intellij_idea">Developing in IntelliJ IDEA</h3>
<div class="paragraph">
<p>You need to run the following gradle task:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">.<span class="regexp"><span class="delimiter">/</span><span class="content">gradlew idea</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Then open the project file which is generated in IDEA. Simple!</p>
</div>
</div>
<div class="sect2">
<h3 id="_developing_in_sts_eclipse">Developing in STS / Eclipse</h3>
<div class="paragraph">
<p>You need to run the following gradle task:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">.<span class="regexp"><span class="delimiter">/</span><span class="content">gradlew cleanEclipse eclipse</span></span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Before importing projects to STS do the following action:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Edit grails-scripts/.classpath and remove the line "&lt;classpathentry kind="src" path="../scripts"/&gt;".</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Use "Import&#8594;General&#8594;Existing Projects into Workspace" to import all projects to STS. There will be a few build errors. To fix them do the following:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Add the springloaded-core JAR file in $GRAILS_HOME/lib/org.springsource.springloaded/springloaded-core/jars to grails-core&#8217;s classpath.</p>
</li>
<li>
<p>Remove "src/test/groovy" from grails-plugin-testing&#8217;s source path GRECLIPSE-1067</p>
</li>
<li>
<p>Add the jsp-api JAR file in $GRAILS_HOME/lib/javax.servlet.jsp/jsp-api/jars to the classpath of grails-web</p>
</li>
<li>
<p>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 "&lt;classpathentry kind="src" path="../scripts"/&gt;"). Remove possible empty "scripts" directory under grails-scripts if you are not able to add the linked folder.</p>
</li>
<li>
<p>Do a clean build for the whole workspace.</p>
</li>
<li>
<p>To use Eclipse GIT scm team provider: Select all projects (except "Servers") in the navigation and right click &#8594; Team &#8594; Share project (not "Share projects"). Choose "Git". Then check "Use or create repository in parent folder of project" and click "Finish".</p>
</li>
<li>
<p>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">mailing list thread</a> (final style not decided yet, currently <a href="http://grails.1312388.n4.nabble.com/attachment/3854262/0/profile.xml">profile.xml</a>). Import the code style xml file to STS in Window&#8594;Preferences&#8594;Java&#8594;Code Style&#8594;Formatter&#8594;Import . Grails code uses spaces instead of tabs for indenting.</p>
</li>
</ul>
</div>
</div>
<div class="sect2">
<h3 id="_debugging_grails_or_a_grails_application">Debugging Grails or a Grails application</h3>
<div class="paragraph">
<p>To enable debugging, run:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails run-app --debug-jvm</code></pre>
</div>
</div>
<div class="paragraph">
<p>By default Grails forks a JVM to run the application in. The <code>-debug-jvm</code> argument causes the debugger to be associated with the forked JVM. In order to instead attach the debugger to the build system which is going to fork the JVM use the <code>-debug</code> option:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">grails -debug run-app</code></pre>
</div>
</div>
</div>
<h2 id="patchesCore">22.3 Submit Patches to Grails Core</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/contributing/patchesCore.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="sect2">
<h3 id="_forking_and_pull_requests">Forking and Pull Requests</h3>
<div class="paragraph">
<p>One of the benefits of <a href="http://github.com">GitHub</a> is the way that you can easily contribute to a project by <a href="https://help.github.com/articles/fork-a-repo/">forking the repository</a> and <a href="https://help.github.com/articles/creating-a-pull-request/">sending pull requests</a> with your changes.</p>
</div>
<div class="paragraph">
<p>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>
</div>
<div class="sect3">
<h4 id="_make_sure_your_fork_is_up_to_date">Make sure your fork is up to date</h4>
<div class="paragraph">
<p>Making changes to outdated sources is not a good idea. Someone else may have already made the change.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">git pull upstream master</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_create_a_local_branch_for_your_changes">Create a local branch for your changes</h4>
<div class="paragraph">
<p>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</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">git checkout -b issue_123</code></pre>
</div>
</div>
<div class="paragraph">
<p>This will create a new local branch called "issue_123" based off the "master" branch. Of course, you can name the branch whatever you like, but a good idea would be to reference the GitHub issue number that the change is relevant to. Each Pull Request should have its own branch.</p>
</div>
</div>
<div class="sect3">
<h4 id="_create_github_issues_for_non_trivial_changes">Create Github issues for non-trivial changes</h4>
<div class="paragraph">
<p>For any non-trivial changes, raise an issue on github if one doesn&#8217;t already exist. That helps us keep track of what changes go into each new version of Grails.</p>
</div>
</div>
<div class="sect3">
<h4 id="_include_github_issue_id_in_commit_messages">Include github issue ID in commit messages</h4>
<div class="paragraph">
<p>This may not seem particularly important, but having a github 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&#8217;t related to an issue, then there&#8217;s no need to include an issue ID.</p>
</div>
</div>
<div class="sect3">
<h4 id="_make_sure_your_fork_is_up_to_date_again_and_rebase">Make sure your fork is up to date again and rebase</h4>
<div class="paragraph">
<p>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>
</div>
<div class="paragraph">
<p>Let&#8217;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 "issue_123" 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:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">git checkout master
git pull upstream master</code></pre>
</div>
</div>
<div class="paragraph">
<p>This should complete without any problems or conflicts. Next, rebase your local branch against the now up-to-date master:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">git checkout issue_123
git rebase master</code></pre>
</div>
</div>
<div class="paragraph">
<p>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>
</div>
</div>
<div class="sect3">
<h4 id="_push_your_branch_to_github_and_send_pull_request">Push your branch to GitHub and send Pull Request</h4>
<div class="paragraph">
<p>Finally, you must push your changes to your fork on GitHub, otherwise the core developers won&#8217;t be able to pick them up:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="groovy">git push origin issue_123</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
You should not merge your branch to your forks master. If the Pull Request is not accepted, your master will then be out of sync with upstream forever.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>You&#8217;re now ready to send the pull request from the GitHub user interface.</p>
</div>
</div>
<div class="sect3">
<h4 id="_say_what_your_pull_request_is_for">Say what your pull request is for</h4>
<div class="paragraph">
<p>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. Fixes #xxxx".</p>
</div>
</div>
</div>
<h2 id="patchesDoc">22.4 Submit Patches to Grails Documentation</h2>
<div class='contribute-btn'>
<button type='button' class='btn btn-default' onclick='window.location.href="https://github.com/grails/grails-doc/edit/3.3.x/src/en/guide/contributing/patchesDoc.adoc"'>
<i class='fa fa-pencil-square-o'></i> Improve this doc
</button>
</div>
<div class="sect2">
<h3 id="_contributing_simple_changes">Contributing Simple Changes</h3>
<div class="paragraph">
<p>The user guide is written using <a href="http://asciidoctor.org/docs/user-manual/">Asciidoctor</a>. The simplest way to contribute fixes is to simply click on the "Improve this doc" link that is to the right of each section of the documentation.</p>
</div>
<div class="paragraph">
<p>This will link to the Github edit screen where you can make changes, preview them and create a pull request.</p>
</div>
</div>
<div class="sect2">
<h3 id="_building_the_guide">Building the Guide</h3>
<div class="paragraph">
<p>If you want to make significant changes, such as changing the structure of the table of contents etc. then we recommend you build the user guide. To do that simply checkout the sources from github:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ git clone https://github.com/grails/grails-doc/
$ cd grails-doc</code></pre>
</div>
</div>
<div class="paragraph">
<p>The source files can be found in the <code>src/en/guide</code> directory. Whilst the Table of Contents (TOC) is defined in the <code>src/en/guide/toc.yml</code> file.</p>
</div>
<div class="paragraph">
<p>Each YAML key points to a Asciidoc template. For example consider the following YAML:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="yaml"><span class="key">introduction</span>:
<span class="key">title</span>: <span class="string"><span class="content">Introduction</span></span>
<span class="key">whatsNew</span>:
<span class="key">title</span>: <span class="string"><span class="content">What's new in Grails 3.2?</span></span>
<span class="error">...</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>introduction</code> key points to <code>src/en/guide/introduction.adoc</code>. The <code>title</code> key defines the title that is dislayed in the TOC. Because <code>whatsNew</code> key is nested underneath the <code>introduction</code> key it points to <code>src/en/guide/introduction/whatsNew.adoc</code>, which is nested in a directory called <code>introduction</code>.</p>
</div>
<div class="paragraph">
<p>Essentially, using the <code>toc.yml</code> file and the directory structure you can manipulate the structure of the user guide.</p>
</div>
<div class="paragraph">
<p>To generate the documentation run the <code>publishGuide</code> task:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="CodeRay highlight"><code data-lang="bash">$ ./gradlew publishGuide -x apiDocs</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
In the above example we skip the <code>apiDocs</code> task to speed up building of the guide, otherwise all Groovydoc documentation will be built too!
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Once the guide is built simply open the <code>build/docs/index.html</code> file in a browser to review your changes.</p>
</div>
</div>
</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/bug-report.html">bug-report</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/clean.html">clean</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/compile.html">compile</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/console.html">console</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/create-app.html">create-app</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/create-command.html">create-command</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/create-controller.html">create-controller</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/create-domain-class.html">create-domain-class</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/create-functional-test.html">create-functional-test</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/create-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-interceptor.html">create-interceptor</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/create-plugin.html">create-plugin</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/create-profile.html">create-profile</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-taglib.html">create-taglib</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/docs.html">docs</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/install-templates.html">install-templates</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/list-profiles.html">list-profiles</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/profile-info.html">profile-info</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/run-app.html">run-app</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/run-command.html">run-command</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/schema-export.html">schema-export</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/shell.html">shell</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/stats.html">stats</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/stop-app.html">stop-app</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/test-app.html">test-app</a>
</div>
<div class="menu-item"><a href="../ref/Command%20Line/war.html">war</a>
</div>
</div>
</div>
<div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Constraints</h1><div class="menu-sub">
<div class="menu-item"><a href="../ref/Constraints/Usage.html">Usage</a></div>
<div class="menu-item"><a href="../ref/Constraints/attributes.html">attributes</a>
</div>
<div class="menu-item"><a href="../ref/Constraints/bindable.html">bindable</a>
</div>
<div class="menu-item"><a href="../ref/Constraints/blank.html">blank</a>
</div>
<div class="menu-item"><a href="../ref/Constraints/creditCard.html">creditCard</a>
</div>
<div class="menu-item"><a href="../ref/Constraints/email.html">email</a>
</div>
<div class="menu-item"><a href="../ref/Constraints/inList.html">inList</a>
</div>
<div class="menu-item"><a href="../ref/Constraints/matches.html">matches</a>
</div>
<div class="menu-item"><a href="../ref/Constraints/max.html">max</a>
</div>
<div class="menu-item"><a href="../ref/Constraints/maxSize.html">maxSize</a>
</div>
<div class="menu-item"><a href="../ref/Constraints/min.html">min</a>
</div>
<div class="menu-item"><a href="../ref/Constraints/minSize.html">minSize</a>
</div>
<div class="menu-item"><a href="../ref/Constraints/notEqual.html">notEqual</a>
</div>
<div class="menu-item"><a href="../ref/Constraints/nullable.html">nullable</a>
</div>
<div class="menu-item"><a href="../ref/Constraints/range.html">range</a>
</div>
<div class="menu-item"><a href="../ref/Constraints/scale.html">scale</a>
</div>
<div class="menu-item"><a href="../ref/Constraints/size.html">size</a>
</div>
<div class="menu-item"><a href="../ref/Constraints/unique.html">unique</a>
</div>
<div class="menu-item"><a href="../ref/Constraints/url.html">url</a>
</div>
<div class="menu-item"><a href="../ref/Constraints/validator.html">validator</a>
</div>
<div class="menu-item"><a href="../ref/Constraints/widget.html">widget</a>
</div>
</div>
</div>
<div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Controllers</h1><div class="menu-sub">
<div class="menu-item"><a href="../ref/Controllers/Usage.html">Usage</a></div>
<div class="menu-item"><a href="../ref/Controllers/actionName.html">actionName</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/allowedMethods.html">allowedMethods</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/bindData.html">bindData</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/chain.html">chain</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/controllerName.html">controllerName</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/defaultAction.html">defaultAction</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/errors.html">errors</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/flash.html">flash</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/forward.html">forward</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/grailsApplication.html">grailsApplication</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/hasErrors.html">hasErrors</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/namespace.html">namespace</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/params.html">params</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/redirect.html">redirect</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/render.html">render</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/request.html">request</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/respond.html">respond</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/response.html">response</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/responseFormats.html">responseFormats</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/scope.html">scope</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/servletContext.html">servletContext</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/session.html">session</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/withForm.html">withForm</a>
</div>
<div class="menu-item"><a href="../ref/Controllers/withFormat.html">withFormat</a>
</div>
</div>
</div>
<div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Database Mapping</h1><div class="menu-sub">
<div class="menu-item"><a href="../ref/Database%20Mapping/Usage.html">Usage</a></div>
<div class="menu-item"><a href="../ref/Database%20Mapping/autoImport.html">autoImport</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/autoTimestamp.html">autoTimestamp</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/batchSize.html">batchSize</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/cache.html">cache</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/cascade.html">cascade</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/column.html">column</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/comment.html">comment</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/discriminator.html">discriminator</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/dynamicInsert.html">dynamicInsert</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/dynamicUpdate.html">dynamicUpdate</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/fetch.html">fetch</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/id.html">id</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/ignoreNotFound.html">ignoreNotFound</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/indexColumn.html">indexColumn</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/insertable.html">insertable</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/joinTable.html">joinTable</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/lazy.html">lazy</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/order.html">order</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/sort.html">sort</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/table.html">table</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/type.html">type</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/updateable.html">updateable</a>
</div>
<div class="menu-item"><a href="../ref/Database%20Mapping/version.html">version</a>
</div>
</div>
</div>
<div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Domain Classes</h1><div class="menu-sub">
<div class="menu-item"><a href="../ref/Domain%20Classes/Usage.html">Usage</a></div>
<div class="menu-item"><a href="../ref/Domain%20Classes/addTo.html">addTo</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/attach.html">attach</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/belongsTo.html">belongsTo</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/clearErrors.html">clearErrors</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/constraints.html">constraints</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/count.html">count</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/countBy.html">countBy</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/createCriteria.html">createCriteria</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/delete.html">delete</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/discard.html">discard</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/embedded.html">embedded</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/errors.html">errors</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/executeQuery.html">executeQuery</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/executeUpdate.html">executeUpdate</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/exists.html">exists</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/fetchMode.html">fetchMode</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/find.html">find</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/findAll.html">findAll</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/findAllBy.html">findAllBy</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/findAllWhere.html">findAllWhere</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/findBy.html">findBy</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/findOrCreateBy.html">findOrCreateBy</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/findOrCreateWhere.html">findOrCreateWhere</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/findOrSaveBy.html">findOrSaveBy</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/findOrSaveWhere.html">findOrSaveWhere</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/findWhere.html">findWhere</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/first.html">first</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/get.html">get</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/getAll.html">getAll</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/getDirtyPropertyNames.html">getDirtyPropertyNames</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/getPersistentValue.html">getPersistentValue</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/hasErrors.html">hasErrors</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/hasMany.html">hasMany</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/hasOne.html">hasOne</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/ident.html">ident</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/instanceOf.html">instanceOf</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/isAttached.html">isAttached</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/isDirty.html">isDirty</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/last.html">last</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/list.html">list</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/listOrderBy.html">listOrderBy</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/load.html">load</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/lock.html">lock</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/mapWith.html">mapWith</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/mappedBy.html">mappedBy</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/mapping.html">mapping</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/merge.html">merge</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/namedQueries.html">namedQueries</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/properties.html">properties</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/read.html">read</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/refresh.html">refresh</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/removeFrom.html">removeFrom</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/save.html">save</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/transients.html">transients</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/validate.html">validate</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/where.html">where</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/whereAny.html">whereAny</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/withCriteria.html">withCriteria</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/withNewSession.html">withNewSession</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/withSession.html">withSession</a>
</div>
<div class="menu-item"><a href="../ref/Domain%20Classes/withTransaction.html">withTransaction</a>
</div>
</div>
</div>
<div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Plug-ins</h1><div class="menu-sub">
<div class="menu-item"><a href="../ref/Plug-ins/Usage.html">Usage</a></div>
<div class="menu-item"><a href="../ref/Plug-ins/URL%20mappings.html">URL mappings</a>
</div>
<div class="menu-item"><a href="../ref/Plug-ins/codecs.html">codecs</a>
</div>
<div class="menu-item"><a href="../ref/Plug-ins/controllers.html">controllers</a>
</div>
<div class="menu-item"><a href="../ref/Plug-ins/core.html">core</a>
</div>
<div class="menu-item"><a href="../ref/Plug-ins/dataSource.html">dataSource</a>
</div>
<div class="menu-item"><a href="../ref/Plug-ins/domainClasses.html">domainClasses</a>
</div>
<div class="menu-item"><a href="../ref/Plug-ins/hibernate.html">hibernate</a>
</div>
<div class="menu-item"><a href="../ref/Plug-ins/i18n.html">i18n</a>
</div>
<div class="menu-item"><a href="../ref/Plug-ins/logging.html">logging</a>
</div>
<div class="menu-item"><a href="../ref/Plug-ins/scaffolding.html">scaffolding</a>
</div>
<div class="menu-item"><a href="../ref/Plug-ins/services.html">services</a>
</div>
<div class="menu-item"><a href="../ref/Plug-ins/servlets.html">servlets</a>
</div>
</div>
</div>
<div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Services</h1><div class="menu-sub">
<div class="menu-item"><a href="../ref/Services/Usage.html">Usage</a></div>
<div class="menu-item"><a href="../ref/Services/scope.html">scope</a>
</div>
<div class="menu-item"><a href="../ref/Services/transactional.html">transactional</a>
</div>
</div>
</div>
<div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Servlet API</h1><div class="menu-sub">
<div class="menu-item"><a href="../ref/Servlet%20API/request.html">request</a>
</div>
<div class="menu-item"><a href="../ref/Servlet%20API/response.html">response</a>
</div>
<div class="menu-item"><a href="../ref/Servlet%20API/servletContext.html">servletContext</a>
</div>
<div class="menu-item"><a href="../ref/Servlet%20API/session.html">session</a>
</div>
</div>
</div>
</div>
</div>
</td>
</tr>
</table>
<div id="footer">
Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.
</div>
<script type="text/javascript" src="../js/docs.js"></script>
</body>
</html>