| <html> |
| <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 1.3.5 - Reference Documentation</title> |
| <link rel="stylesheet" href="../css/main.css" type="text/css" media="screen" title="Style" charset="utf-8" /> |
| <link rel="stylesheet" href="../css/pdf.css" type="text/css" media="print" title="PDF" charset="utf-8" /> |
| <link rel="icon" href="../img/favicon.ico" type="image/x-icon" /> |
| <link rel="shortcut icon" href="../img/favicon.ico" type="image/x-icon" /> |
| </head> |
| <body class="body"> |
| <div id="header"> |
| <div class="images"><br/><br/> |
| <a href="http://grails.org" target="_blank"><img alt="The Grails Framework" src="../img/grails.png" border="0"/></a> |
| <span style="right:30px; top:20px; position:absolute;"> |
| <a href="../index.html" target="_top">Frames</a> | <a href="index.html" target="_top">No Frames</a><br/><br/> |
| <a href="http://springsource.com" target="_blank"><img alt="SpringSource - Weapons for the War on Java Complexity" src="../img/springsource-logo.png" border="0"/></a> |
| </span> |
| </div> |
| <div class="message">See the light - agile, industrial strength, rapid web application development made easy</div> |
| <h1>The Grails Framework - Reference Documentation</h1> |
| <p><strong>Authors:</strong> Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown</p> |
| <p><strong>Version:</strong> 1.3.5</p> |
| <em>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.</em> |
| </div> |
| |
| <div id="toc"> |
| <h2>Table of Contents</h2> |
| <div class="tocItem" style="margin-left:0px"><a href="#1. Introduction">1. Introduction</a></div><div class="tocItem" style="margin-left:0px"><a href="#2. Getting Started">2. Getting Started</a></div><div class="tocItem" style="margin-left:10px"><a href="#2.1 Downloading and Installing">2.1 Downloading and Installing</a></div><div class="tocItem" style="margin-left:10px"><a href="#2.2 Upgrading from previous versions of Grails">2.2 Upgrading from previous versions of Grails</a></div><div class="tocItem" style="margin-left:10px"><a href="#2.3 Creating an Application">2.3 Creating an Application</a></div><div class="tocItem" style="margin-left:10px"><a href="#2.4 A Hello World Example">2.4 A Hello World Example</a></div><div class="tocItem" style="margin-left:10px"><a href="#2.5 Getting Set-up in an IDE">2.5 Getting Set-up in an IDE</a></div><div class="tocItem" style="margin-left:10px"><a href="#2.6 Convention over Configuration">2.6 Convention over Configuration</a></div><div class="tocItem" style="margin-left:10px"><a href="#2.7 Running an Application">2.7 Running an Application</a></div><div class="tocItem" style="margin-left:10px"><a href="#2.8 Testing an Application">2.8 Testing an Application</a></div><div class="tocItem" style="margin-left:10px"><a href="#2.9 Deploying an Application">2.9 Deploying an Application</a></div><div class="tocItem" style="margin-left:10px"><a href="#2.10 Supported Java EE Containers">2.10 Supported Java EE Containers</a></div><div class="tocItem" style="margin-left:10px"><a href="#2.11 Generating an Application">2.11 Generating an Application</a></div><div class="tocItem" style="margin-left:10px"><a href="#2.12 Creating Artefacts">2.12 Creating Artefacts</a></div><div class="tocItem" style="margin-left:0px"><a href="#3. Configuration">3. Configuration</a></div><div class="tocItem" style="margin-left:10px"><a href="#3.1 Basic Configuration">3.1 Basic Configuration</a></div><div class="tocItem" style="margin-left:20px"><a href="#3.1.1 Built in options">3.1.1 Built in options</a></div><div class="tocItem" style="margin-left:20px"><a href="#3.1.2 Logging">3.1.2 Logging</a></div><div class="tocItem" style="margin-left:20px"><a href="#3.1.3 GORM">3.1.3 GORM</a></div><div class="tocItem" style="margin-left:10px"><a href="#3.2 Environments">3.2 Environments</a></div><div class="tocItem" style="margin-left:10px"><a href="#3.3 The DataSource">3.3 The DataSource</a></div><div class="tocItem" style="margin-left:20px"><a href="#3.3.1 DataSources and Environments">3.3.1 DataSources and Environments</a></div><div class="tocItem" style="margin-left:20px"><a href="#3.3.2 JNDI DataSources">3.3.2 JNDI DataSources</a></div><div class="tocItem" style="margin-left:20px"><a href="#3.3.3 Automatic Database Migration">3.3.3 Automatic Database Migration</a></div><div class="tocItem" style="margin-left:20px"><a href="#3.3.4 Transaction-aware DataSource Proxy">3.3.4 Transaction-aware DataSource Proxy</a></div><div class="tocItem" style="margin-left:10px"><a href="#3.4 Externalized Configuration">3.4 Externalized Configuration</a></div><div class="tocItem" style="margin-left:10px"><a href="#3.5 Versioning">3.5 Versioning</a></div><div class="tocItem" style="margin-left:10px"><a href="#3.6 Project Documentation">3.6 Project Documentation</a></div><div class="tocItem" style="margin-left:10px"><a href="#3.7 Dependency Resolution">3.7 Dependency Resolution</a></div><div class="tocItem" style="margin-left:20px"><a href="#3.7.1 Configurations and Dependencies">3.7.1 Configurations and Dependencies</a></div><div class="tocItem" style="margin-left:20px"><a href="#3.7.2 Dependency Repositories">3.7.2 Dependency Repositories</a></div><div class="tocItem" style="margin-left:20px"><a href="#3.7.3 Debugging Resolution">3.7.3 Debugging Resolution</a></div><div class="tocItem" style="margin-left:20px"><a href="#3.7.4 Inherited Dependencies">3.7.4 Inherited Dependencies</a></div><div class="tocItem" style="margin-left:20px"><a href="#3.7.5 Providing Default Dependencies">3.7.5 Providing Default Dependencies</a></div><div class="tocItem" style="margin-left:20px"><a href="#3.7.6 Dependency Reports">3.7.6 Dependency Reports</a></div><div class="tocItem" style="margin-left:20px"><a href="#3.7.7 Plugin JAR Dependencies">3.7.7 Plugin JAR Dependencies</a></div><div class="tocItem" style="margin-left:20px"><a href="#3.7.8 Maven Integration">3.7.8 Maven Integration</a></div><div class="tocItem" style="margin-left:20px"><a href="#3.7.9 Deploying to a Maven Repository">3.7.9 Deploying to a Maven Repository</a></div><div class="tocItem" style="margin-left:20px"><a href="#3.7.10 Plugin Dependencies">3.7.10 Plugin Dependencies</a></div><div class="tocItem" style="margin-left:0px"><a href="#4. The Command Line">4. The Command Line</a></div><div class="tocItem" style="margin-left:10px"><a href="#4.1 Creating Gant Scripts">4.1 Creating Gant Scripts</a></div><div class="tocItem" style="margin-left:10px"><a href="#4.2 Re-using Grails scripts">4.2 Re-using Grails scripts</a></div><div class="tocItem" style="margin-left:10px"><a href="#4.3 Hooking into Events">4.3 Hooking into Events</a></div><div class="tocItem" style="margin-left:10px"><a href="#4.4 Customising the build">4.4 Customising the build</a></div><div class="tocItem" style="margin-left:10px"><a href="#4.5 Ant and Maven">4.5 Ant and Maven</a></div><div class="tocItem" style="margin-left:0px"><a href="#5. Object Relational Mapping (GORM)">5. Object Relational Mapping (GORM)</a></div><div class="tocItem" style="margin-left:10px"><a href="#5.1 Quick Start Guide">5.1 Quick Start Guide</a></div><div class="tocItem" style="margin-left:20px"><a href="#5.1.1 Basic CRUD">5.1.1 Basic CRUD</a></div><div class="tocItem" style="margin-left:10px"><a href="#5.2 Domain Modelling in GORM">5.2 Domain Modelling in GORM</a></div><div class="tocItem" style="margin-left:20px"><a href="#5.2.1 Association in GORM">5.2.1 Association in GORM</a></div><div class="tocItem" style="margin-left:30px"><a href="#5.2.1.1 One-to-one">5.2.1.1 One-to-one</a></div><div class="tocItem" style="margin-left:30px"><a href="#5.2.1.2 One-to-many">5.2.1.2 One-to-many</a></div><div class="tocItem" style="margin-left:30px"><a href="#5.2.1.3 Many-to-many">5.2.1.3 Many-to-many</a></div><div class="tocItem" style="margin-left:30px"><a href="#5.2.1.4 Basic Collection Types">5.2.1.4 Basic Collection Types</a></div><div class="tocItem" style="margin-left:20px"><a href="#5.2.2 Composition in GORM">5.2.2 Composition in GORM</a></div><div class="tocItem" style="margin-left:20px"><a href="#5.2.3 Inheritance in GORM">5.2.3 Inheritance in GORM</a></div><div class="tocItem" style="margin-left:20px"><a href="#5.2.4 Sets, Lists and Maps">5.2.4 Sets, Lists and Maps</a></div><div class="tocItem" style="margin-left:10px"><a href="#5.3 Persistence Basics">5.3 Persistence Basics</a></div><div class="tocItem" style="margin-left:20px"><a href="#5.3.1 Saving and Updating">5.3.1 Saving and Updating</a></div><div class="tocItem" style="margin-left:20px"><a href="#5.3.2 Deleting Objects">5.3.2 Deleting Objects</a></div><div class="tocItem" style="margin-left:20px"><a href="#5.3.3 Understanding Cascading Updates and Deletes">5.3.3 Understanding Cascading Updates and Deletes</a></div><div class="tocItem" style="margin-left:20px"><a href="#5.3.4 Eager and Lazy Fetching">5.3.4 Eager and Lazy Fetching</a></div><div class="tocItem" style="margin-left:20px"><a href="#5.3.5 Pessimistic and Optimistic Locking">5.3.5 Pessimistic and Optimistic Locking</a></div><div class="tocItem" style="margin-left:20px"><a href="#5.3.6 Modification Checking">5.3.6 Modification Checking</a></div><div class="tocItem" style="margin-left:10px"><a href="#5.4 Querying with GORM">5.4 Querying with GORM</a></div><div class="tocItem" style="margin-left:20px"><a href="#5.4.1 Dynamic Finders">5.4.1 Dynamic Finders</a></div><div class="tocItem" style="margin-left:20px"><a href="#5.4.2 Criteria">5.4.2 Criteria</a></div><div class="tocItem" style="margin-left:20px"><a href="#5.4.3 Hibernate Query Language (HQL)">5.4.3 Hibernate Query Language (HQL)</a></div><div class="tocItem" style="margin-left:10px"><a href="#5.5 Advanced GORM Features">5.5 Advanced GORM Features</a></div><div class="tocItem" style="margin-left:20px"><a href="#5.5.1 Events and Auto Timestamping">5.5.1 Events and Auto Timestamping</a></div><div class="tocItem" style="margin-left:20px"><a href="#5.5.2 Custom ORM Mapping">5.5.2 Custom ORM Mapping</a></div><div class="tocItem" style="margin-left:30px"><a href="#5.5.2.1 Table and Column Names">5.5.2.1 Table and Column Names</a></div><div class="tocItem" style="margin-left:30px"><a href="#5.5.2.2 Caching Strategy">5.5.2.2 Caching Strategy</a></div><div class="tocItem" style="margin-left:30px"><a href="#5.5.2.3 Inheritance Strategies">5.5.2.3 Inheritance Strategies</a></div><div class="tocItem" style="margin-left:30px"><a href="#5.5.2.4 Custom Database Identity">5.5.2.4 Custom Database Identity</a></div><div class="tocItem" style="margin-left:30px"><a href="#5.5.2.5 Composite Primary Keys">5.5.2.5 Composite Primary Keys</a></div><div class="tocItem" style="margin-left:30px"><a href="#5.5.2.6 Database Indices">5.5.2.6 Database Indices</a></div><div class="tocItem" style="margin-left:30px"><a href="#5.5.2.7 Optimistic Locking and Versioning">5.5.2.7 Optimistic Locking and Versioning</a></div><div class="tocItem" style="margin-left:30px"><a href="#5.5.2.8 Eager and Lazy Fetching">5.5.2.8 Eager and Lazy Fetching</a></div><div class="tocItem" style="margin-left:30px"><a href="#5.5.2.9 Custom Cascade Behaviour">5.5.2.9 Custom Cascade Behaviour</a></div><div class="tocItem" style="margin-left:30px"><a href="#5.5.2.10 Custom Hibernate Types">5.5.2.10 Custom Hibernate Types</a></div><div class="tocItem" style="margin-left:30px"><a href="#5.5.2.11 Derived Properties">5.5.2.11 Derived Properties</a></div><div class="tocItem" style="margin-left:30px"><a href="#5.5.2.12 Custom Naming Strategy">5.5.2.12 Custom Naming Strategy</a></div><div class="tocItem" style="margin-left:20px"><a href="#5.5.3 Default Sort Order">5.5.3 Default Sort Order</a></div><div class="tocItem" style="margin-left:10px"><a href="#5.6 Programmatic Transactions">5.6 Programmatic Transactions</a></div><div class="tocItem" style="margin-left:10px"><a href="#5.7 GORM and Constraints">5.7 GORM and Constraints</a></div><div class="tocItem" style="margin-left:0px"><a href="#6. The Web Layer">6. The Web Layer</a></div><div class="tocItem" style="margin-left:10px"><a href="#6.1 Controllers">6.1 Controllers</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.1.1 Understanding Controllers and Actions">6.1.1 Understanding Controllers and Actions</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.1.2 Controllers and Scopes">6.1.2 Controllers and Scopes</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.1.3 Models and Views">6.1.3 Models and Views</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.1.4 Redirects and Chaining">6.1.4 Redirects and Chaining</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.1.5 Controller Interceptors">6.1.5 Controller Interceptors</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.1.6 Data Binding">6.1.6 Data Binding</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.1.7 XML and JSON Responses">6.1.7 XML and JSON Responses</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.1.8 More on JSONBuilder">6.1.8 More on JSONBuilder</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.1.9 Uploading Files">6.1.9 Uploading Files</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.1.10 Command Objects">6.1.10 Command Objects</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.1.11 Handling Duplicate Form Submissions">6.1.11 Handling Duplicate Form Submissions</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.1.12 Simple Type Converters">6.1.12 Simple Type Converters</a></div><div class="tocItem" style="margin-left:10px"><a href="#6.2 Groovy Server Pages">6.2 Groovy Server Pages</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.2.1 GSP Basics">6.2.1 GSP Basics</a></div><div class="tocItem" style="margin-left:30px"><a href="#6.2.1.1 Variables and Scopes">6.2.1.1 Variables and Scopes</a></div><div class="tocItem" style="margin-left:30px"><a href="#6.2.1.2 Logic and Iteration">6.2.1.2 Logic and Iteration</a></div><div class="tocItem" style="margin-left:30px"><a href="#6.2.1.3 Page Directives">6.2.1.3 Page Directives</a></div><div class="tocItem" style="margin-left:30px"><a href="#6.2.1.4 Expressions">6.2.1.4 Expressions</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.2.2 GSP Tags">6.2.2 GSP Tags</a></div><div class="tocItem" style="margin-left:30px"><a href="#6.2.2.1 Variables and Scopes">6.2.2.1 Variables and Scopes</a></div><div class="tocItem" style="margin-left:30px"><a href="#6.2.2.2 Logic and Iteration">6.2.2.2 Logic and Iteration</a></div><div class="tocItem" style="margin-left:30px"><a href="#6.2.2.3 Search and Filtering">6.2.2.3 Search and Filtering</a></div><div class="tocItem" style="margin-left:30px"><a href="#6.2.2.4 Links and Resources">6.2.2.4 Links and Resources</a></div><div class="tocItem" style="margin-left:30px"><a href="#6.2.2.5 Forms and Fields">6.2.2.5 Forms and Fields</a></div><div class="tocItem" style="margin-left:30px"><a href="#6.2.2.6 Tags as Method Calls">6.2.2.6 Tags as Method Calls</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.2.3 Views and Templates">6.2.3 Views and Templates</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.2.4 Layouts with Sitemesh">6.2.4 Layouts with Sitemesh</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.2.5 Sitemesh Content Blocks">6.2.5 Sitemesh Content Blocks</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.2.6 Making Changes to a Deployed Application">6.2.6 Making Changes to a Deployed Application</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.2.7 GSP Debugging">6.2.7 GSP Debugging</a></div><div class="tocItem" style="margin-left:10px"><a href="#6.3 Tag Libraries">6.3 Tag Libraries</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.3.1 Variables and Scopes">6.3.1 Variables and Scopes</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.3.2 Simple Tags">6.3.2 Simple Tags</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.3.3 Logical Tags">6.3.3 Logical Tags</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.3.4 Iterative Tags">6.3.4 Iterative Tags</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.3.5 Tag Namespaces">6.3.5 Tag Namespaces</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.3.6 Using JSP Tag Libraries">6.3.6 Using JSP Tag Libraries</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.3.7 Tag return value">6.3.7 Tag return value</a></div><div class="tocItem" style="margin-left:10px"><a href="#6.4 URL Mappings">6.4 URL Mappings</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.4.1 Mapping to Controllers and Actions">6.4.1 Mapping to Controllers and Actions</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.4.2 Embedded Variables">6.4.2 Embedded Variables</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.4.3 Mapping to Views">6.4.3 Mapping to Views</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.4.4 Mapping to Response Codes">6.4.4 Mapping to Response Codes</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.4.5 Mapping to HTTP methods">6.4.5 Mapping to HTTP methods</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.4.6 Mapping Wildcards">6.4.6 Mapping Wildcards</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.4.7 Automatic Link Re-Writing">6.4.7 Automatic Link Re-Writing</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.4.8 Applying Constraints">6.4.8 Applying Constraints</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.4.9 Named URL Mappings">6.4.9 Named URL Mappings</a></div><div class="tocItem" style="margin-left:10px"><a href="#6.5 Web Flow">6.5 Web Flow</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.5.1 Start and End States">6.5.1 Start and End States</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.5.2 Action States and View States">6.5.2 Action States and View States</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.5.3 Flow Execution Events">6.5.3 Flow Execution Events</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.5.4 Flow Scopes">6.5.4 Flow Scopes</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.5.5 Data Binding and Validation">6.5.5 Data Binding and Validation</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.5.6 Subflows and Conversations">6.5.6 Subflows and Conversations</a></div><div class="tocItem" style="margin-left:10px"><a href="#6.6 Filters">6.6 Filters</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.6.1 Applying Filters">6.6.1 Applying Filters</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.6.2 Filter Types">6.6.2 Filter Types</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.6.3 Variables and Scopes">6.6.3 Variables and Scopes</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.6.4 Filter Dependencies">6.6.4 Filter Dependencies</a></div><div class="tocItem" style="margin-left:10px"><a href="#6.7 Ajax">6.7 Ajax</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.7.1 Ajax using Prototype">6.7.1 Ajax using Prototype</a></div><div class="tocItem" style="margin-left:30px"><a href="#6.7.1.1 Remoting Linking">6.7.1.1 Remoting Linking</a></div><div class="tocItem" style="margin-left:30px"><a href="#6.7.1.2 Updating Content">6.7.1.2 Updating Content</a></div><div class="tocItem" style="margin-left:30px"><a href="#6.7.1.3 Remote Form Submission">6.7.1.3 Remote Form Submission</a></div><div class="tocItem" style="margin-left:30px"><a href="#6.7.1.4 Ajax Events">6.7.1.4 Ajax Events</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.7.2 Ajax with Dojo">6.7.2 Ajax with Dojo</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.7.3 Ajax with GWT">6.7.3 Ajax with GWT</a></div><div class="tocItem" style="margin-left:20px"><a href="#6.7.4 Ajax on the Server">6.7.4 Ajax on the Server</a></div><div class="tocItem" style="margin-left:10px"><a href="#6.8 Content Negotiation">6.8 Content Negotiation</a></div><div class="tocItem" style="margin-left:0px"><a href="#7. Validation">7. Validation</a></div><div class="tocItem" style="margin-left:10px"><a href="#7.1 Declaring Constraints">7.1 Declaring Constraints</a></div><div class="tocItem" style="margin-left:10px"><a href="#7.2 Validating Constraints">7.2 Validating Constraints</a></div><div class="tocItem" style="margin-left:10px"><a href="#7.3 Validation on the Client">7.3 Validation on the Client</a></div><div class="tocItem" style="margin-left:10px"><a href="#7.4 Validation and Internationalization">7.4 Validation and Internationalization</a></div><div class="tocItem" style="margin-left:10px"><a href="#7.5 Validation Non Domain and Command Object Classes">7.5 Validation Non Domain and Command Object Classes</a></div><div class="tocItem" style="margin-left:0px"><a href="#8. The Service Layer">8. The Service Layer</a></div><div class="tocItem" style="margin-left:10px"><a href="#8.1 Declarative Transactions">8.1 Declarative Transactions</a></div><div class="tocItem" style="margin-left:10px"><a href="#8.2 Scoped Services">8.2 Scoped Services</a></div><div class="tocItem" style="margin-left:10px"><a href="#8.3 Dependency Injection and Services">8.3 Dependency Injection and Services</a></div><div class="tocItem" style="margin-left:10px"><a href="#8.4 Using Services from Java">8.4 Using Services from Java</a></div><div class="tocItem" style="margin-left:0px"><a href="#9. Testing">9. Testing</a></div><div class="tocItem" style="margin-left:10px"><a href="#9.1 Unit Testing">9.1 Unit Testing</a></div><div class="tocItem" style="margin-left:10px"><a href="#9.2 Integration Testing">9.2 Integration Testing</a></div><div class="tocItem" style="margin-left:10px"><a href="#9.3 Functional Testing">9.3 Functional Testing</a></div><div class="tocItem" style="margin-left:0px"><a href="#10. Internationalization">10. Internationalization</a></div><div class="tocItem" style="margin-left:10px"><a href="#10.1 Understanding Message Bundles">10.1 Understanding Message Bundles</a></div><div class="tocItem" style="margin-left:10px"><a href="#10.2 Changing Locales">10.2 Changing Locales</a></div><div class="tocItem" style="margin-left:10px"><a href="#10.3 Reading Messages">10.3 Reading Messages</a></div><div class="tocItem" style="margin-left:10px"><a href="#10.4 Scaffolding and i18n">10.4 Scaffolding and i18n</a></div><div class="tocItem" style="margin-left:0px"><a href="#11. Security">11. Security</a></div><div class="tocItem" style="margin-left:10px"><a href="#11.1 Securing Against Attacks">11.1 Securing Against Attacks</a></div><div class="tocItem" style="margin-left:10px"><a href="#11.2 Encoding and Decoding Objects">11.2 Encoding and Decoding Objects</a></div><div class="tocItem" style="margin-left:10px"><a href="#11.3 Authentication">11.3 Authentication</a></div><div class="tocItem" style="margin-left:10px"><a href="#11.4 Security Plug-ins">11.4 Security Plug-ins</a></div><div class="tocItem" style="margin-left:20px"><a href="#11.4.1 Spring Security">11.4.1 Spring Security</a></div><div class="tocItem" style="margin-left:20px"><a href="#11.4.2 Shiro">11.4.2 Shiro</a></div><div class="tocItem" style="margin-left:0px"><a href="#12. Plug-ins">12. Plug-ins</a></div><div class="tocItem" style="margin-left:10px"><a href="#12.1 Creating and Installing Plug-ins">12.1 Creating and Installing Plug-ins</a></div><div class="tocItem" style="margin-left:10px"><a href="#12.2 Plugin Repositories">12.2 Plugin Repositories</a></div><div class="tocItem" style="margin-left:10px"><a href="#12.3 Understanding a Plug-ins Structure">12.3 Understanding a Plug-ins Structure</a></div><div class="tocItem" style="margin-left:10px"><a href="#12.4 Providing Basic Artefacts">12.4 Providing Basic Artefacts</a></div><div class="tocItem" style="margin-left:10px"><a href="#12.5 Evaluating Conventions">12.5 Evaluating Conventions</a></div><div class="tocItem" style="margin-left:10px"><a href="#12.6 Hooking into Build Events">12.6 Hooking into Build Events</a></div><div class="tocItem" style="margin-left:10px"><a href="#12.7 Hooking into Runtime Configuration">12.7 Hooking into Runtime Configuration</a></div><div class="tocItem" style="margin-left:10px"><a href="#12.8 Adding Dynamic Methods at Runtime">12.8 Adding Dynamic Methods at Runtime</a></div><div class="tocItem" style="margin-left:10px"><a href="#12.9 Participating in Auto Reload Events">12.9 Participating in Auto Reload Events</a></div><div class="tocItem" style="margin-left:10px"><a href="#12.10 Understanding Plug-in Load Order">12.10 Understanding Plug-in Load Order</a></div><div class="tocItem" style="margin-left:0px"><a href="#13. Web Services">13. Web Services</a></div><div class="tocItem" style="margin-left:10px"><a href="#13.1 REST">13.1 REST</a></div><div class="tocItem" style="margin-left:10px"><a href="#13.2 SOAP">13.2 SOAP</a></div><div class="tocItem" style="margin-left:10px"><a href="#13.3 RSS and Atom">13.3 RSS and Atom</a></div><div class="tocItem" style="margin-left:0px"><a href="#14. Grails and Spring">14. Grails and Spring</a></div><div class="tocItem" style="margin-left:10px"><a href="#14.1 The Underpinnings of Grails">14.1 The Underpinnings of Grails</a></div><div class="tocItem" style="margin-left:10px"><a href="#14.2 Configuring Additional Beans">14.2 Configuring Additional Beans</a></div><div class="tocItem" style="margin-left:10px"><a href="#14.3 Runtime Spring with the Beans DSL">14.3 Runtime Spring with the Beans DSL</a></div><div class="tocItem" style="margin-left:10px"><a href="#14.4 The BeanBuilder DSL Explained">14.4 The BeanBuilder DSL Explained</a></div><div class="tocItem" style="margin-left:10px"><a href="#14.5 Property Placeholder Configuration">14.5 Property Placeholder Configuration</a></div><div class="tocItem" style="margin-left:10px"><a href="#14.6 Property Override Configuration">14.6 Property Override Configuration</a></div><div class="tocItem" style="margin-left:0px"><a href="#15. Grails and Hibernate">15. Grails and Hibernate</a></div><div class="tocItem" style="margin-left:10px"><a href="#15.1 Using Hibernate XML Mapping Files">15.1 Using Hibernate XML Mapping Files</a></div><div class="tocItem" style="margin-left:10px"><a href="#15.2 Mapping with Hibernate Annotations">15.2 Mapping with Hibernate Annotations</a></div><div class="tocItem" style="margin-left:10px"><a href="#15.3 Adding Constraints">15.3 Adding Constraints</a></div><div class="tocItem" style="margin-left:10px"><a href="#15.4 Further Reading">15.4 Further Reading</a></div><div class="tocItem" style="margin-left:0px"><a href="#16. Scaffolding">16. Scaffolding</a></div><div class="tocItem" style="margin-left:0px"><a href="#17. Deployment">17. Deployment</a></div> |
| </div> |
| <div id="content"> |
| <h1><a name="1. Introduction">1. Introduction</a></h1>Java web development as it stands today is dramatically more complicated than it needs to be. Most modern web frameworks in the Java space are over complicated and don't embrace the Don't Repeat Yourself (DRY) principles.<p class="paragraph"/>Dynamic frameworks like Rails, Django and TurboGears helped pave the way to a more modern way of thinking about web applications. Grails builds on these concepts and dramatically reduces the complexity of building web applications on the Java platform. What makes it different, however, is that it does so by building on already established Java technology like Spring & Hibernate.<p class="paragraph"/>Grails is a full stack framework and attempts to solve as many pieces of the web development puzzle through the core technology and it's associated plug-ins. Included out the box are things like: |
| <ul class="star"> |
| <li>An easy to use Object Relational Mapping (ORM) layer built on <a href="http://www.hibernate.org" target="blank">Hibernate</a></li> |
| <li>An expressive view technology called Groovy Server Pages (GSP)</li> |
| <li>A controller layer built on <a href="http://www.springframework.org" target="blank">Spring</a> MVC</li> |
| <li>A command line scripting environment built on the Groovy-powered <a href="http://groovy.codehaus.org/Gant" target="blank">Gant</a></li> |
| <li>An embedded <a href="http://tomcat.apache.org" target="blank">Tomcat</a> container which is configured for on the fly reloading</li> |
| <li>Dependency injection with the inbuilt <a href="http://www.springframework.org" target="blank">Spring</a> container</li> |
| <li>Support for internationalization (i18n) built on Spring's core MessageSource concept</li> |
| <li>A transactional service layer built on Spring's transaction abstraction</li> |
| </ul><p class="paragraph"/>All of these are made easy to use through the power of the <a href="http://groovy.codehaus.org" target="blank">Groovy</a> language and the extensive use of Domain Specific Languages (DSLs)<p class="paragraph"/>This documentation will take you through getting started with Grails and building web applications with the Grails framework. <h1><a name="2. Getting Started">2. Getting Started</a></h1><h2><a name="2.1 Downloading and Installing">2.1 Downloading and Installing</a></h2>The first step to getting up and running with Grails is to install the distribution. To do so follow these steps: |
| <ul class="star"> |
| <li><a href="http://grails.org/Download" target="blank">Download</a> a binary distribution of Grails and extract the resulting zip file to a location of your choice</li> |
| <li>Set the GRAILS_HOME environment variable to the location where you extracted the zip</li> |
| <ul class="star"> |
| <li>On Unix/Linux based systems this is typically a matter of adding something like the following <code>export GRAILS_HOME=/path/to/grails</code> to your profile</li> |
| <li>On Windows this is typically a matter of setting an environment variable under <code>My Computer/Advanced/Environment Variables</code></li> |
| </ul> |
| <li>Now you need to add the <code>bin</code> directory to your <code>PATH</code> variable:</li> |
| <ul class="star"> |
| <li>On Unix/Linux base system this can be done by doing a <code>export PATH="$PATH:$GRAILS_HOME/bin"</code></li> |
| <li>On windows this is done by modifying the <code>Path</code> environment variable under <code>My Computer/Advanced/Environment Variables</code></li> |
| </ul></ul><p class="paragraph"/>If Grails is working correctly you should now be able to type <code>grails</code> in the terminal window and see output similar to the below:<p class="paragraph"/><pre class="bq"><code> |
| Welcome to Grails 1.0 - http://grails.org/ |
| Licensed under Apache Standard License 2.0 |
| Grails home is set to: /Developer/grails-1.0 |
| No script name specified. Use 'grails help' for more info</code></pre><p class="paragraph"/> |
| <h2><a name="2.2 Upgrading from previous versions of Grails">2.2 Upgrading from previous versions of Grails</a></h2>Although the Grails development team have tried to keep breakages to a minimum there are a number of items to consider when upgrading a Grails 1.0.x, 1.1.x, or 1.2.x applications to Grails 1.3. The major changes are described in detail below.<p class="paragraph"/><h3>Upgrading from Grails 1.2.x</h3><p class="paragraph"/><h4>Plugin Repositories</h4><p class="paragraph"/>As of Grails 1.3, Grails no longer natively supports resolving plugins against secured SVN repositories. Grails 1.2 and below's plugin resolution mechanism has been replaced by one built on Ivy the upside of which is that you can now resolve Grails plugins against Maven repositories as well as regular Grails repositories.<p class="paragraph"/>Ivy supports a much richer setter of repository resolvers for resolving plugins with, including support for Webdav, HTTP, SSH and FTP. See the section on <a href="http://ant.apache.org/ivy/history/trunk/settings/resolvers.html" target="blank">resolvers</a> in the Ivy docs for all the available options and the section of <a href="../guide/single.html#12.2 Plugin Repositories" class="guide">plugin repositories</a> in the user guide which explains how to configure additional resolvers.<p class="paragraph"/>If you still need support for resolving plugins against secured SVN repositories then the <a href="http://code.google.com/p/ivysvn/" target="blank">IvySvn</a> project provides a set of Ivy resolvers for resolving against SVN repositories.<p class="paragraph"/><h3>Upgrading from Grails 1.1.x</h3><p class="paragraph"/><h4>Plugin paths</h4><p class="paragraph"/>In Grails 1.1.x typically a <code>pluginContextPath</code> variable was used to establish paths to plugin resources. For example:<p class="paragraph"/><div class="code"><pre><g:resource dir=<span class="java-quote">"${pluginContextPath}/images"</span> file=<span class="java-quote">"foo.jpg"</span> /></pre></div><p class="paragraph"/>In Grails 1.2 views have been made plugin aware and this is no longer necessary:<p class="paragraph"/><div class="code"><pre><g:resource dir=<span class="java-quote">"images"</span> file=<span class="java-quote">"foo.jpg"</span> /></pre></div><p class="paragraph"/>Additionally the above example will no longer link to an application image from a plugin view. To do so you need to change the above to:<p class="paragraph"/><div class="code"><pre><g:resource contextPath=<span class="java-quote">""</span> dir=<span class="java-quote">"images"</span> file=<span class="java-quote">"foo.jpg"</span> /></pre></div><p class="paragraph"/>The same rules apply to the <a href="../ref/Tags/javascript.html" class="tags">javascript</a> and <a href="../ref/Tags/render.html" class="tags">render</a><p class="paragraph"/><h4>Tag and Body return values</h4><p class="paragraph"/>Tags no longer return <code>java.lang.String</code> instances but instead return a <code>StreamCharBuffer</code> instance. The <code>StreamCharBuffer</code> class implements all the same methods as <code>String</code>, however code like this may break:<p class="paragraph"/><div class="code"><pre>def foo = body() |
| <span class="java-keyword">if</span>(foo <span class="java-keyword">instanceof</span> <span class="java-object">String</span>) { |
| // <span class="java-keyword">do</span> something |
| }</pre></div><p class="paragraph"/>In these cases you should use the <code>java.lang.CharSequence</code> interface, which both <code>String</code> and <code>StreamCharBuffer</code> implement:<p class="paragraph"/><div class="code"><pre>def foo = body() |
| <span class="java-keyword">if</span>(foo <span class="java-keyword">instanceof</span> CharSequence) { |
| // <span class="java-keyword">do</span> something |
| }</pre></div><p class="paragraph"/><h4>New JSONBuilder</h4><p class="paragraph"/>There is a new version of <code>JSONBuilder</code> which is semantically different to earlier versions of Grails. However, if your application depends on the older semantics you can still use the now deprecated implementation by settings the following property to <code>true</code> in Config.groovy:<p class="paragraph"/><div class="code"><pre>grails.json.legacy.builder=<span class="java-keyword">true</span></pre></div><p class="paragraph"/><h4>Validation on Flush</h4><p class="paragraph"/>Grails now executes validation routines when the underlying Hibernate session is flushed to ensure that no invalid objects are persisted. If one of your constraints (such as a custom validator) is executing a query then this can cause an addition flush resulting in a <code>StackOverflowError</code>. Example:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> constraints = { |
| author validator: { a -> |
| assert a != Book.findByTitle(<span class="java-quote">"My Book"</span>).author |
| } |
| }</pre></div><p class="paragraph"/>The above code can lead to a <code>StackOverflowError</code> in Grails 1.2. The solution is to run the query in a new Hibernate <code>session</code> (which is recommended in general as doing Hibernate work during flushing can cause other issues):<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> constraints = { |
| author validator: { a -> |
| Book.withNewSession { |
| assert a != Book.findByTitle(<span class="java-quote">"My Book"</span>).author |
| } |
| } |
| }</pre></div><p class="paragraph"/><h3>Upgrading from Grails 1.0.x</h3><p class="paragraph"/><h4>Groovy 1.6</h4><p class="paragraph"/>Grails 1.1 and above ship with Groovy 1.6 and no longer supports code compiled against Groovy 1.5. If you have a library that is written in Groovy 1.5 you will need to recompile it against Groovy 1.6 before using it with Grails 1.1.<p class="paragraph"/><h4>Java 5.0</h4><p class="paragraph"/>Grails 1.1 now no longer supports JDK 1.4, if you wish to continue using Grails then it is recommended you stick to the Grails 1.0.x stream until you are able to upgrade your JDK.<p class="paragraph"/><h4>Configuration Changes</h4><p class="paragraph"/>1) The setting <code>grails.testing.reports.destDir</code> has been renamed to <code>grails.project.test.reports.dir</code> for consistency.<p class="paragraph"/>2) The following settings have been moved from <code>grails-app/conf/Config.groovy</code> to <code>grails-app/conf/BuildConfig.groovy</code>: |
| <ul class="star"> |
| <ul class="star"> |
| <li><code>grails.config.base.webXml</code></li> |
| <li><code>grails.project.war.file</code> (renamed from <code>grails.war.destFile</code>)</li> |
| <li><code>grails.war.dependencies</code></li> |
| <li><code>grails.war.copyToWebApp</code></li> |
| <li><code>grails.war.resources</code></li> |
| </ul></ul><p class="paragraph"/>3) The <code>grails.war.java5.dependencies</code> option is no longer supported, since Java 5.0 is now the baseline (see above).<p class="paragraph"/>4) The use of jsessionid (now considered harmful) is disabled by default. If your application requires jsessionid you can re-enable its usage by adding the following to <code>grails-app/conf/Config.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.views.enable.jsessionid=<span class="java-keyword">true</span></pre></div><p class="paragraph"/>5) The syntax used to configure Log4j has changed. See the user guide section on <a href="../guide/single.html#3.1.2 Logging" class="guide">Logging</a> for more information.<p class="paragraph"/><h4>Plugin Changes </h4><p class="paragraph"/>Since 1.1, Grails no longer stores plugins inside your <code>PROJECT_HOME/plugins</code> directory by default. This may result in compilation errors in your application unless you either re-install all your plugins or set the following property in <code>grails-app/conf/BuildConfig.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.project.plugins.dir=<span class="java-quote">"./plugins"</span></pre></div><p class="paragraph"/><h4>Script Changes</h4><p class="paragraph"/>1) If you were previously using Grails 1.0.3 or below the following syntax is no longer support for importing scripts from GRAILS_HOME:<p class="paragraph"/><div class="code"><pre>Ant.property(environment:<span class="java-quote">"env"</span>) |
| grailsHome = Ant.antProject.properties.<span class="java-quote">"env.GRAILS_HOME"</span><p class="paragraph"/>includeTargets << <span class="java-keyword">new</span> File ( <span class="java-quote">"${grailsHome}/scripts/Bootstrap.groovy"</span> )</pre></div><p class="paragraph"/>Instead you should use the new <code>grailsScript</code> method to import a named script:<p class="paragraph"/><div class="code"><pre>includeTargets << grailsScript( <span class="java-quote">"Bootstrap.groovy"</span> )</pre></div><p class="paragraph"/>2) Due to an upgrade to Gant all references to the variable <code>Ant</code> should be changed to <code>ant</code>.<p class="paragraph"/>3) The root directory of the project is no long on the classpath, the result is that loading a resource like this will no longer work:<p class="paragraph"/><div class="code"><pre>def stream = getClass().classLoader.getResourceAsStream(<span class="java-quote">"grails-app/conf/my-config.xml"</span>)</pre></div><p class="paragraph"/>Instead you should use the Java File APIs with the <code>basedir</code> property:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">new</span> File(<span class="java-quote">"${basedir}/grails-app/conf/my-config.xml"</span>).withInputStream { stream -> |
| // read the file |
| }</pre></div><p class="paragraph"/><h4>Command Line Changes</h4><p class="paragraph"/>The <code>run-app-https</code> and <code>run-war-https</code> commands no longer exist and have been replaced by an argument to <a href="../ref/Command Line/run-app.html" class="commandLine">run-app</a>:<p class="paragraph"/><div class="code"><pre>grails run-app -https</pre></div><p class="paragraph"/><h4>Data Mapping Changes</h4><p class="paragraph"/>1) Enum types are now mapped using their String value rather than the ordinal value. You can revert to the old behavior by changing your mapping as follows:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mapping = { |
| someEnum enumType:<span class="java-quote">"ordinal"</span> |
| }</pre></div><p class="paragraph"/>2) Bidirectional one-to-one associations are now mapped with a single column on the owning side and a foreign key reference. You shouldn't need to change anything, however you may want to drop the column on the inverse side as it contains duplicate data.<p class="paragraph"/><h4>REST Support</h4><p class="paragraph"/>Incoming XML requests are now no longer automatically parsed. To enable parsing of REST requests you can do so using the <code>parseRequest</code> argument inside a URL mapping:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/book"</span>(controller:<span class="java-quote">"book"</span>,parseRequest:<span class="java-keyword">true</span>)</pre></div><p class="paragraph"/>Alternatively, you can use the new <code>resource</code> argument, which enables parsing by default:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/book"</span>(resource:<span class="java-quote">"book"</span>)</pre></div> |
| <h2><a name="2.3 Creating an Application">2.3 Creating an Application</a></h2>To create a Grails application you first need to familiarize yourself with the usage of the <code>grails</code> command which is used in the following manner:<p class="paragraph"/><div class="code"><pre>grails [command name]</pre></div><p class="paragraph"/>In this case the command you need to execute is <a href="../ref/Command Line/create-app.html" class="commandLine">create-app</a>:<p class="paragraph"/><pre class="bq"><code> |
| grails create-app helloworld</code></pre><p class="paragraph"/>This will create a new directory inside the current one that contains the project. You should now navigate to this directory in terminal:<p class="paragraph"/><pre class="bq"><code> |
| cd helloworld</code></pre><p class="paragraph"/><h2><a name="2.4 A Hello World Example">2.4 A Hello World Example</a></h2>To implement the typical "hello world!" example run the <a href="../ref/Command Line/create-controller.html" class="commandLine">create-controller</a> command:<p class="paragraph"/><pre class="bq"><code> |
| grails create-controller hello </code></pre><p class="paragraph"/>This will create a new controller (Refer to the section on <a href="../guide/single.html#6.1 Controllers" class="guide">Controllers</a> for more information) in the <code>grails-app/controllers</code> directory called <code>HelloController.groovy</code>.<p class="paragraph"/>Controllers are capable of dealing with web requests and to fulfil the "hello world!" use case our implementation needs to look like the following:<p class="paragraph"/><div class="code"><pre>class HelloController { |
| def world = { |
| render <span class="java-quote">"Hello World!"</span> |
| } |
| }</pre></div><p class="paragraph"/>Job done. Now start-up the container with another new command called <a href="../ref/Command Line/run-app.html" class="commandLine">run-app</a>:<p class="paragraph"/><pre class="bq"><code> |
| grails run-app</code></pre><p class="paragraph"/>This will start-up a server on port 8080 and you should now be able to access your application with the URL: <code>http://localhost:8080/helloworld</code><p class="paragraph"/>The result will look something like the following screenshot:<p class="paragraph"/><img border="0" class="center" src="../img/intropage.png"></img><p class="paragraph"/>This is the Grails intro page which is rendered by the <code>web-app/index.gsp</code> file. You will note it has a detected the presence of your controller and clicking on the link to our controller we can see the text "Hello World!" printed to the browser window.<p class="paragraph"/><h2><a name="2.5 Getting Set-up in an IDE">2.5 Getting Set-up in an IDE</a></h2><h4>IntelliJ IDEA</h4><p class="paragraph"/><a href="http://www.jetbrains.com/idea" target="blank">IntelliJ IDEA</a> and the <a href="http://www.jetbrains.net/confluence/display/GRVY/Groovy+Home" target="blank">JetGroovy</a> plug-in offer good support for Groovy & Grails developer. Refer to the section on <a href="http://www.jetbrains.com/idea/features/groovy_grails.html" target="blank">Groovy and Grails</a> support on the JetBrains website for a feature overview.<p class="paragraph"/>To integrate Grails 1.2 to with IntelliJ run the following command to generate appropriate project files:<p class="paragraph"/><div class="code"><pre>grails integrate-with --intellij</pre></div><p class="paragraph"/><h4>NetBeans </h4><p class="paragraph"/>A good Open Source alternative is Sun's NetBeans, which provides a Groovy/Grails plugin that automatically recognizes Grails projects and provides the ability to run Grails applications in the IDE, code completion and integration with Sun's Glassfish server. For an overview of features see the <a href="http://www.grails.org/NetBeans+Integration" target="blank">NetBeans Integration</a> guide on the Grails website which was written by the NetBeans team.<p class="paragraph"/><h4>Eclipse</h4><p class="paragraph"/>We recommend that users of <a href="http://www.eclipse.org/" target="blank">Eclipse</a> looking to develop Grails application take a look at <a href="http://www.springsource.com/products/sts" target="blank">SpringSource Tool Suite</a>, which offers built in support for Grails including automatic classpath management, a GSP editor and quick access to Grails commands. See the <a href="http://www.grails.org/STS+Integration" target="blank">STS Integration</a> page for an overview.<p class="paragraph"/><h4>TextMate</h4><p class="paragraph"/>Since Grails' focus is on simplicity it is often possible to utilize more simple editors and <a href="http://macromates.com/" target="blank">TextMate</a> on the Mac has an excellent Groovy/Grails bundle available from the <a href="http://wiki.macromates.com/Main/SubversionCheckout" target="blank">Texmate bundles SVN</a>.<p class="paragraph"/>To integrate Grails 1.2 to with TextMate run the following command to generate appropriate project files:<p class="paragraph"/><div class="code"><pre>grails integrate-with --textmate</pre></div><p class="paragraph"/>Alternatively TextMate can easily open any project with its command line integration by issuing the following command from the root of your project:<p class="paragraph"/><div class="code"><pre>mate .</pre></div><p class="paragraph"/><p class="paragraph"/><h2><a name="2.6 Convention over Configuration">2.6 Convention over Configuration</a></h2>Grails uses "convention over configuration" to configure itself. This typically means that the name and location of files is used instead of explicit configuration, hence you need to familiarize yourself with the directory structure provided by Grails.<p class="paragraph"/>Here is a breakdown and links to the relevant sections: |
| <ul class="star"> |
| <li><code>grails-app</code> - top level directory for Groovy sources</li> |
| <ul class="star"> |
| <li><code>conf</code> - <a href="../guide/single.html#3. Configuration" class="guide">Configuration sources</a>.</li> |
| <li><code>controllers</code> - <a href="../guide/single.html#6.1 Controllers" class="guide">Web controllers</a> - The C in MVC.</li> |
| <li><code>domain</code> - The <a href="../guide/single.html#5. Object Relational Mapping (GORM)" class="guide">application domain</a>.</li> |
| <li><code>i18n</code> - Support for <a href="../guide/single.html#10. Internationalization" class="guide">internationalization (i18n)</a>.</li> |
| <li><code>services</code> - The <a href="../guide/single.html#8. The Service Layer" class="guide">service layer</a>.</li> |
| <li><code>taglib</code> - <a href="../guide/single.html#6.3 Tag Libraries" class="guide">Tag libraries</a>.</li> |
| <li><code>views</code> - <a href="../guide/single.html#6.2 Groovy Server Pages" class="guide">Groovy Server Pages</a>.</li> |
| </ul> |
| <li><code>scripts</code> - <a href="../guide/single.html#4. The Command Line" class="guide">Gant scripts</a>.</li> |
| <li><code>src</code> - Supporting sources</li> |
| <ul class="star"> |
| <li><code>groovy</code> - Other Groovy sources</li> |
| <li><code>java</code> - Other Java sources</li> |
| </ul> |
| <li><code>test</code> - <a href="../guide/single.html#9. Testing" class="guide">Unit and integration tests</a>.</li> |
| </ul><p class="paragraph"/><h2><a name="2.7 Running an Application">2.7 Running an Application</a></h2>Grails applications can be run with the built in Tomcat server using the <a href="../ref/Command Line/run-app.html" class="commandLine">run-app</a> command which will load a server on port 8080 by default:<p class="paragraph"/><div class="code"><pre>grails run-app</pre></div><p class="paragraph"/>You can specify a different port by using the <code>server.port</code> argument:<p class="paragraph"/><div class="code"><pre>grails -Dserver.port=8090 run-app</pre></div><p class="paragraph"/>More information on the <a href="../ref/Command Line/run-app.html" class="commandLine">run-app</a> command can be found in the reference guide.<h2><a name="2.8 Testing an Application">2.8 Testing an Application</a></h2>The <code>create-*</code> commands in Grails automatically create integration tests for you within the <code>test/integration</code> directory. It is of course up to you to populate these tests with valid test logic, information on which can be found in the section on <a href="../guide/single.html#9. Testing" class="guide">Testing</a>. However, if you wish to execute tests you can run the <a href="../ref/Command Line/test-app.html" class="commandLine">test-app</a> command as follows:<p class="paragraph"/><div class="code"><pre>grails test-app</pre></div><p class="paragraph"/>Grails also automatically generates an Ant <code>build.xml</code> which can also run the tests by delegating to Grails' <a href="../ref/Command Line/test-app.html" class="commandLine">test-app</a> command:<p class="paragraph"/><div class="code"><pre>ant test</pre></div><p class="paragraph"/>This is useful when you need to build Grails applications as part of a continuous integration platform such as CruiseControl.<h2><a name="2.9 Deploying an Application">2.9 Deploying an Application</a></h2>Grails applications are deployed as Web Application Archives (WAR files), and Grails includes the <a href="../ref/Command Line/war.html" class="commandLine">war</a> command for performing this task:<p class="paragraph"/><div class="code"><pre>grails war</pre></div><p class="paragraph"/>This will produce a WAR file in the root of your project which can then be deployed as per your containers instructions.<p class="paragraph"/><blockquote class="warning"> |
| NEVER deploy Grails using the <a href="../ref/Command Line/run-app.html" class="commandLine">run-app</a> command as this command sets Grails up for auto-reloading at runtime which has a severe performance and scalability implication |
| </blockquote><p class="paragraph"/>When deploying Grails you should always run your containers JVM with the <code>-server</code> option and with sufficient memory allocation. A good set of VM flags would be:<p class="paragraph"/><div class="code"><pre>-server -Xmx512M</pre></div><h2><a name="2.10 Supported Java EE Containers">2.10 Supported Java EE Containers</a></h2>Grails runs on any Servlet 2.4 and above container and is known to work on the following specific container products: |
| <ul class="star"> |
| <li>Tomcat 5.5</li> |
| <li>Tomcat 6.0</li> |
| <li>SpringSource tc Server</li> |
| <li>SpringSource dm Server 1.0</li> |
| <li>GlassFish v1 (Sun AS 9.0)</li> |
| <li>GlassFish v2 (Sun AS 9.1)</li> |
| <li>GlassFish v3 Prelude</li> |
| <li>Sun App Server 8.2</li> |
| <li>Websphere 6.1</li> |
| <li>Websphere 5.1</li> |
| <li>Resin 3.2</li> |
| <li>Oracle AS</li> |
| <li>JBoss 4.2</li> |
| <li>Jetty 6.1</li> |
| <li>Jetty 5</li> |
| <li>Weblogic 7/8/9/10</li> |
| </ul><p class="paragraph"/>Some containers have bugs however, which in most cases can be worked around. A <a href="http://grails.org/Deployment" target="blank">list of known deployment issues</a> can be found on the Grails wiki.<h2><a name="2.11 Generating an Application">2.11 Generating an Application</a></h2>To get started quickly with Grails it is often useful to use a feature called <a href="../guide/single.html#16. Scaffolding" class="guide">Scaffolding</a> to generate the skeleton of an application. To do this use one of the <code>generate-*</code> commands such as <a href="../ref/Command Line/generate-all.html" class="commandLine">generate-all</a>, which will generate a <a href="../guide/single.html#6.1 Controllers" class="guide">controller</a> and the relevant <a href="../guide/single.html#6.2 Groovy Server Pages" class="guide">views</a>:<p class="paragraph"/><div class="code"><pre>grails generate-all Book</pre></div><p class="paragraph"/><h2><a name="2.12 Creating Artefacts">2.12 Creating Artefacts</a></h2>Grails ships with a few convenience targets such as <a href="../ref/Command Line/create-controller.html" class="commandLine">create-controller</a>, <a href="../ref/Command Line/create-domain-class.html" class="commandLine">create-domain-class</a> and so on that will create <a href="../guide/single.html#6.1 Controllers" class="guide">Controllers</a> and different artefact types for you. |
| <blockquote class="note"> |
| These are merely for your convenience and you can just as easily use an IDE or your favourite text editor. |
| </blockquote> |
| For example to create the basis of an application you typically need a <a href="../guide/single.html#5. Object Relational Mapping (GORM)" class="guide">domain model</a>:<p class="paragraph"/><div class="code"><pre>grails create-domain-class book</pre></div><p class="paragraph"/>This will result in the creation of a domain class at <code>grails-app/domain/Book.groovy</code> such as:<p class="paragraph"/><div class="code"><pre>class Book { |
| }</pre></div><p class="paragraph"/>There are many such <code>create-*</code> commands that can be explored in the command line reference guide.<h1><a name="3. Configuration">3. Configuration</a></h1>It may seem odd that in a framework that embraces "convention-over-configuration" that we tackle this topic now, but since what configuration there is typically a one off, it is best to get it out the way.<p class="paragraph"/>With Grails' default settings you can actually develop and application without doing any configuration whatsoever. Grails ships with an embedded container and in-memory HSQLDB meaning there isn't even a database to set-up.<p class="paragraph"/>However, typically you want to set-up a real database at some point and the way you do that is described in the following section.<h2><a name="3.1 Basic Configuration">3.1 Basic Configuration</a></h2>For general configuration Grails provides a file called <code>grails-app/conf/Config.groovy</code>. This file uses Groovy's <a href="http://groovy.codehaus.org/ConfigSlurper" target="blank">ConfigSlurper</a> which is very similar to Java properties files except it is pure Groovy hence you can re-use variables and use proper Java types!<p class="paragraph"/>You can add your own configuration in here, for example:<p class="paragraph"/><div class="code"><pre>foo.bar.hello = <span class="java-quote">"world"</span></pre></div><p class="paragraph"/>Then later in your application you can access these settings in one of two ways. The most common is via the <a href="../api/org/codehaus/groovy/grails/commons/GrailsApplication.html" class="api">GrailsApplication</a> object, which is available as a variable in controllers and tag libraries:<p class="paragraph"/><div class="code"><pre>assert <span class="java-quote">"world"</span> == grailsApplication.config.foo.bar.hello</pre></div><p class="paragraph"/>The other way involves getting a reference to the <a href="../api/org/codehaus/groovy/grails/commons/ConfigurationHolder.html" class="api">ConfigurationHolder</a> class that holds a reference to the configuration object:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.codehaus.groovy.grails.commons.* |
| … |
| def config = ConfigurationHolder.config |
| assert <span class="java-quote">"world"</span> == config.foo.bar.hello</pre></div> |
| <h2><a name="3.1.1 Built in options">3.1.1 Built in options</a></h2>Grails also provides the following configuration options: |
| <ul class="star"> |
| <li><code>grails.config.locations</code> - The location of properties files or addition Grails Config files that should be merged with main configuration</li> |
| <li><code>grails.enable.native2ascii</code> - Set this to false if you do not require native2ascii conversion of Grails i18n properties files</li> |
| <li><code>grails.views.default.codec</code> - Sets the default encoding regime for GSPs - can be one of 'none', 'html', or 'base64' (default: 'none'). To reduce risk of XSS attacks, set this to 'html'.</li> |
| <li><code>grails.views.gsp.encoding</code> - The file encoding used for GSP source files (default is 'utf-8')</li> |
| <li><code>grails.mime.file.extensions</code> - Whether to use the file extension to dictate the mime type in <a href="../guide/single.html#6.8 Content Negotiation" class="guide">Content Negotiation</a></li> |
| <li><code>grails.mime.types</code> - A map of supported mime types used for <a href="../guide/single.html#6.8 Content Negotiation" class="guide">Content Negotiation</a></li> |
| <li><code>grails.serverURL</code> - A string specifying the server URL portion of absolute links, including server name e.g. grails.serverURL="http://my.yourportal.com". See <a href="../ref/Tags/createLink.html" class="Tags">createLink</a>.</li> |
| </ul><p class="paragraph"/><h3>War generation</h3> |
| <ul class="star"> |
| <li><code>grails.project.war.file</code> - Sets the location where the <a href="../ref/Command Line/war.html" class="commandLine">war</a> command should place the generated WAR file</li> |
| <li><code>grails.war.dependencies</code> - A closure containing Ant builder syntax or a list of JAR filenames. Allows you to customise what libaries are included in the WAR file.</li> |
| <li><code>grails.war.java5.dependencies</code> - A list of the JARs that should be included in the WAR file for JDK 1.5 and above.</li> |
| <li><code>grails.war.copyToWebApp</code> - A closure containing Ant builder syntax that is legal inside an Ant copy, for example "fileset()". Allows you to control what gets included in the WAR file from the "web-app" directory.</li> |
| <li><code>grails.war.resources</code> - A closure containing Ant builder syntax. Allows the application to do any other pre-warring stuff it needs to.</li> |
| </ul><p class="paragraph"/>For more information on using these options, see the section on <a href="../guide/single.html#17. Deployment" class="guide">deployment</a> |
| <h2><a name="3.1.2 Logging">3.1.2 Logging</a></h2><h4>Logging Basics</h4><p class="paragraph"/>Grails uses its common configuration mechanism to configure the underlying <a href="http://logging.apache.org/log4j/1.2/index.html" target="blank">Log4j</a> log system. To configure logging you must modify the file <code>Config.groovy</code> located in the <code>grails-app/conf</code> directory.<p class="paragraph"/>This single <code>Config.groovy</code> file allows you to specify separate logging configurations for <code>development</code>, <code>test</code>, and <code>production</code> <a href="../guide/single.html#3.2 Environments" class="guide">environments</a>. Grails processes the <code>Config.groovy</code> and configures Log4j appropriately.<p class="paragraph"/>Since 1.1 Grails provides a Log4j DSL, that you can use to configure Log4j an example of which can be seen below:<p class="paragraph"/><div class="code"><pre>log4j = { |
| error 'org.codehaus.groovy.grails.web.servlet', // controllers |
| 'org.codehaus.groovy.grails.web.pages' // GSP<p class="paragraph"/> warn 'org.mortbay.log' |
| }</pre></div><p class="paragraph"/>Essentially, each method translates into a log level and you can pass the names of the packages you want to log at that level as arguments to the method.<p class="paragraph"/>Some useful loggers include: |
| <ul class="star"> |
| <li><code>org.codehaus.groovy.grails.commons</code> - Core artefact information such as class loading etc.</li> |
| <li><code>org.codehaus.groovy.grails.web</code> - Grails web request processing</li> |
| <li><code>org.codehaus.groovy.grails.web.mapping</code> - URL mapping debugging</li> |
| <li><code>org.codehaus.groovy.grails.plugins</code> - Log plugin activity</li> |
| <li><code>org.springframework</code> - See what Spring is doing</li> |
| <li><code>org.hibernate</code> - See what Hibernate is doing</li> |
| </ul><p class="paragraph"/><h4>The Root Logger</h4><p class="paragraph"/>The Root logger is the logger that all other loggers inherit from. You can configure the Root logger using the root method:<p class="paragraph"/><div class="code"><pre>root { |
| error() |
| additivity = <span class="java-keyword">true</span> |
| }</pre></div><p class="paragraph"/>The above example configures the root logger to log messages at the error level and above to the default standard out appender. You can also configure the root logger to log to one or more named appenders:<p class="paragraph"/><div class="code"><pre>appenders { |
| file name:'file', file:'/<span class="java-keyword">var</span>/logs/mylog.log' |
| } |
| root { |
| debug 'stdout', 'file' |
| additivity = <span class="java-keyword">true</span> |
| }</pre></div><p class="paragraph"/>Here the root logger will log to two appenders - the default 'stdout' appender and a 'file' appender.<p class="paragraph"/>You can also configure the root logger from the argument passed into the Log4J closure: |
| <div class="code"><pre>log4j = { root -> |
| root.level = org.apache.log4j.Level.DEBUG |
| … |
| }</pre></div> |
| The closure argument "root" is an instance of <code>org.apache.log4j.Logger</code> , so refer to the API documentation for Log4J to find out what properties and methods are available to you.<p class="paragraph"/><h4>Custom Appenders</h4><p class="paragraph"/>Using the Log4j you can define custom appenders. The following appenders are available by default: |
| <ul class="star"> |
| <li><code>jdbc</code> - An appender that logs to a JDBC connection</li> |
| <li><code>console</code> - An appender that logs to standard out</li> |
| <li><code>file</code> - An appender that logs to a file</li> |
| <li><code>rollingFile</code> - An appender that logs to rolling set of files</li> |
| </ul><p class="paragraph"/>For example to configure a rolling file appender you can do:<p class="paragraph"/><div class="code"><pre>log4j = { |
| appenders { |
| rollingFile name:<span class="java-quote">"myAppender"</span>, maxFileSize:1024, file:<span class="java-quote">"/tmp/logs/myApp.log"</span> |
| } |
| }</pre></div><p class="paragraph"/>Each argument passed to the appender maps to a property of underlying <a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Appender.html" target="blank">Appender</a> class. The example above sets the <code>name</code>, <code>maxFileSize</code> and <code>file</code> properties of the <a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/RollingFileAppender.html" target="blank">RollingFileAppender</a> class.<p class="paragraph"/>If you prefer to simply create the appender programmatically yourself, or you have your own appender implementation then you can simply call the <code>appender</code> method and appender instance:<p class="paragraph"/> |
| <div class="code"><pre><span class="java-keyword">import</span> org.apache.log4j.*<p class="paragraph"/>log4j = { |
| appenders { |
| appender <span class="java-keyword">new</span> RollingFileAppender(name:<span class="java-quote">"myAppender"</span>, maxFileSize:1024, file:<span class="java-quote">"/tmp/logs/myApp.log"</span>) |
| } |
| }</pre></div><p class="paragraph"/>You can then log to a particular appender by passing the name as a key to one of the log level methods from the previous section:<p class="paragraph"/><div class="code"><pre>error myAppender:<span class="java-quote">"org.codehaus.groovy.grails.commons"</span></pre></div><p class="paragraph"/><p class="paragraph"/><h4>Custom Layouts</h4><p class="paragraph"/>By default the Log4j DSL assumes that you want to use a <a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html" target="blank">PatternLayout</a>. However, there are other layouts available including: |
| <ul class="star"> |
| <li><code>xml</code> - Create an XML log file</li> |
| <li><code>html</code> - Creates an HTML log file</li> |
| <li><code>simple</code> - A simple textual log</li> |
| <li><code>pattern</code> - A Pattern layout</li> |
| </ul><p class="paragraph"/>You can specify custom patterns to an appender using the <code>layout</code> setting:<p class="paragraph"/><div class="code"><pre>log4j = { |
| appenders { |
| console name:'customAppender', layout:pattern(conversionPattern: '%c{2} %m%n') |
| } |
| }</pre></div><p class="paragraph"/>This also works for the built-in appender "stdout", which logs to the console: |
| <div class="code"><pre>log4j = { |
| appenders { |
| console name:'stdout', layout:pattern(conversionPattern: '%c{2} %m%n') |
| } |
| }</pre></div><p class="paragraph"/><h4>Full stacktraces</h4><p class="paragraph"/>When exceptions occur, there can be an awful lot of noise in the stacktrace from Java and Groovy internals. Grails filters these typically irrelevant details and restricts traces to non-core Grails/Groovy class packages.<p class="paragraph"/>When this happens, the full trace is always written to the <code>StackTrace</code> logger. This logs to a file called <code>stacktrace.log</code> - but you can change this in your <code>Config.groovy</code> to do anything you like. For example if you prefer full stack traces to go to standard out you can add this line:<p class="paragraph"/><div class="code"><pre>error stdout:<span class="java-quote">"StackTrace"</span></pre></div><p class="paragraph"/>You can completely disable stacktrace filtering by setting the <code>grails.full.stacktrace</code> VM property to <code>true</code>:<p class="paragraph"/><div class="code"><pre>grails -Dgrails.full.stacktrace=<span class="java-keyword">true</span> run-app</pre></div><p class="paragraph"/><h4>Logging by Convention</h4><p class="paragraph"/>All application artefacts have a dynamically added <code>log</code> property. This includes <a href="../guide/single.html#5. Object Relational Mapping (GORM)" class="guide">domain classes</a>, <a href="../guide/single.html#6.1 Controllers" class="guide">controllers</a>, tag libraries and so on. Below is an example of its usage:<p class="paragraph"/><div class="code"><pre>def foo = <span class="java-quote">"bar"</span> |
| log.debug <span class="java-quote">"The value of foo is $foo"</span></pre></div><p class="paragraph"/>Logs are named using the convention <code>grails.app.<artefactType>.ClassName</code>. Below is an example of how to configure logs for different Grails artefacts:<p class="paragraph"/><div class="code"><pre>log4j = { |
| // Set level <span class="java-keyword">for</span> all application artefacts |
| info <span class="java-quote">"grails.app"</span> |
| // Set <span class="java-keyword">for</span> a specific controller |
| debug <span class="java-quote">"grails.app.controller.YourController"</span> |
| // Set <span class="java-keyword">for</span> a specific domain class |
| debug <span class="java-quote">"grails.app.domain.Book"</span> |
| // Set <span class="java-keyword">for</span> all taglibs |
| info <span class="java-quote">"grails.app.tagLib"</span><p class="paragraph"/>}</pre></div><p class="paragraph"/>The artefacts names are dictated by convention, some of the common ones are listed below: |
| <ul class="star"> |
| <li><code>bootstrap</code> - For bootstrap classes</li> |
| <li><code>dataSource</code> - For data sources</li> |
| <li><code>tagLib</code> - For tag libraries</li> |
| <li><code>service</code> - For service classes</li> |
| <li><code>controller</code> - For controllers</li> |
| <li><code>domain</code> - For domain entities</li> |
| </ul><p class="paragraph"/><h2><a name="3.1.3 GORM">3.1.3 GORM</a></h2>Grails provides the following GORM configuration options: |
| <ul class="star"> |
| <li><code>grails.gorm.failOnError</code> - If set to <code>true</code>, causes the save() method on domain classes to throw a <code>grails.validation.ValidationException</code> if <a href="../guide/single.html#7. Validation" class="guide">validation</a> fails during a save. This option may also be assigned a list of Strings representing package names. If the value is a list of Strings then the failOnError behavior will only be applied to domain classes in those packages (including sub-packages). See the <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> method docs for more information.</li> |
| </ul><p class="paragraph"/>Enable failOnError for all domain classes… |
| <div class="code"><pre>grails.gorm.failOnError=<span class="java-keyword">true</span></pre></div><p class="paragraph"/>Enable failOnError for domain classes by package… |
| <div class="code"><pre>grails.gorm.failOnError = ['com.companyname.somepackage', 'com.companyname.someotherpackage']</pre></div> |
| <ul class="star"> |
| <li><code>grails.gorm.autoFlush</code> = If set to <code>true</code>, causes the <a href="../ref/Domain Classes/merge.html" class="domainClasses">merge</a>, <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> and <a href="../ref/Domain Classes/delete.html" class="domainClasses">delete</a> methods to flush the session, replacing the need to do something like <code>save(flush: true)</code>.</li> |
| </ul><p class="paragraph"/><h2><a name="3.2 Environments">3.2 Environments</a></h2><h4>Per Environment Configuration</h4><p class="paragraph"/>Grails supports the concept of per environment configuration. Both the <code>Config.groovy</code> file and the <code>DataSource.groovy</code> file within the <code>grails-app/conf</code> directory can take advantage of per environment configuration using the syntax provided by <a href="http://groovy.codehaus.org/ConfigSlurper." target="blank">ConfigSlurper</a> As an example consider the following default <code>DataSource</code> definition provided by Grails:<p class="paragraph"/><div class="code"><pre>dataSource { |
| pooled = <span class="java-keyword">false</span> |
| driverClassName = <span class="java-quote">"org.hsqldb.jdbcDriver"</span> |
| username = <span class="java-quote">"sa"</span> |
| password = <span class="java-quote">""</span> |
| } |
| environments { |
| development { |
| dataSource { |
| dbCreate = <span class="java-quote">"create-drop"</span> // one of 'create', 'createeate-drop','update' |
| url = <span class="java-quote">"jdbc:hsqldb:mem:devDB"</span> |
| } |
| } |
| test { |
| dataSource { |
| dbCreate = <span class="java-quote">"update"</span> |
| url = <span class="java-quote">"jdbc:hsqldb:mem:testDb"</span> |
| } |
| } |
| production { |
| dataSource { |
| dbCreate = <span class="java-quote">"update"</span> |
| url = <span class="java-quote">"jdbc:hsqldb:file:prodDb;shutdown=<span class="java-keyword">true</span>"</span> |
| } |
| } |
| }</pre></div><p class="paragraph"/>Notice how the common configuration is provided at the top level and then an <code>environments</code> block specifies per environment settings for the <code>dbCreate</code> and <code>url</code> properties of the <code>DataSource</code>. This syntax can also be used within <code>Config.groovy</code>.<p class="paragraph"/><h4>Packaging and Running for Different Environments</h4><p class="paragraph"/>Grails' <a href="../guide/single.html#4. The Command Line" class="guide">command line</a> has built in capabilities to execute any command within the context of a specific environment. The format is:<p class="paragraph"/><div class="code"><pre>grails [environment] [command name]</pre></div><p class="paragraph"/>In addition, there are 3 preset environments known to Grails: <code>dev</code>, <code>prod</code>, and <code>test</code> for <code>development</code>, <code>production</code> and <code>test</code>. For example to create a WAR for the <code>test</code> environment you could do:<p class="paragraph"/><div class="code"><pre>grails test war</pre></div><p class="paragraph"/>If you have other environments that you need to target you can pass a <code>grails.env</code> variable to any command:<p class="paragraph"/><div class="code"><pre>grails -Dgrails.env=UAT run-app</pre></div><p class="paragraph"/><h4>Programmatic Environment Detection</h4><p class="paragraph"/>Within your code, such as in a Gant script or a bootstrap class you can detect the environment using the <a href="../api/grails/util/Environment.html" class="api">Environment</a> class:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.util.Environment<p class="paragraph"/>...<p class="paragraph"/><span class="java-keyword">switch</span>(Environment.current) { |
| <span class="java-keyword">case</span> Environment.DEVELOPMENT: |
| configureForDevelopment() |
| <span class="java-keyword">break</span> |
| <span class="java-keyword">case</span> Environment.PRODUCTION: |
| configureForProduction() |
| <span class="java-keyword">break</span> |
| }</pre></div><p class="paragraph"/><h4>Per Environment Bootstrapping</h4><p class="paragraph"/>Its often desirable to run code when your application starts up on a per-environment basis. To do so you can use the <code>grails-app/conf/BootStrap.groovy</code> file's support for per-environment execution:<p class="paragraph"/><div class="code"><pre>def init = { ServletContext ctx -> |
| environments { |
| production { |
| ctx.setAttribute(<span class="java-quote">"env"</span>, <span class="java-quote">"prod"</span>) |
| } |
| development { |
| ctx.setAttribute(<span class="java-quote">"env"</span>, <span class="java-quote">"dev"</span>) |
| } |
| } |
| ctx.setAttribute(<span class="java-quote">"foo"</span>, <span class="java-quote">"bar"</span>) |
| }</pre></div><p class="paragraph"/><h4>Generic Per Environment Execution</h4><p class="paragraph"/>The previous <code>BootStrap</code> example uses the <code>grails.util.Environment</code> class internally to execute. You can also use this class yourself to execute your own environment specific logic:<p class="paragraph"/><div class="code"><pre>Environment.executeForCurrentEnvironment { |
| production { |
| // <span class="java-keyword">do</span> something in production |
| } |
| development { |
| // <span class="java-keyword">do</span> something only in development |
| } |
| }</pre></div> |
| <h2><a name="3.3 The DataSource">3.3 The DataSource</a></h2>Since Grails is built on Java technology setting up a data source requires some knowledge of JDBC (the technology that doesn't stand for Java Database Connectivity).<p class="paragraph"/>Essentially, if you are using another database other than HSQLDB you need to have a JDBC driver. For example for MySQL you would need <a href="http://www.mysql.com/downloads/connector/j/" target="blank">Connector/J</a><p class="paragraph"/>Drivers typically come in the form of a JAR archive. Drop the JAR into your project's <code>lib</code> directory.<p class="paragraph"/>Once you have the JAR in place you need to get familiar Grails' DataSource descriptor file located at <code>grails-app/conf/DataSource.groovy</code>. This file contains the dataSource definition which includes the following settings: |
| <ul class="star"> |
| <li><code>driverClassName</code> - The class name of the JDBC driver</li> |
| <li><code>username</code> - The username used to establish a JDBC connection</li> |
| <li><code>password</code> - The password used to establish a JDBC connection</li> |
| <li><code>url</code> - The JDBC URL of the database</li> |
| <li><code>dbCreate</code> - Whether to auto-generate the database from the domain model or not</li> |
| <li><code>pooled</code> - Whether to use a pool of connections (defaults to true)</li> |
| <li><code>logSql</code> - Enable SQL logging to stdout</li> |
| <li><code>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/stable/core/api/org/hibernate/dialect/package-summary.html" target="blank">org.hibernate.dialect</a> package for available dialects.</li> |
| <li><code>properties</code> - Extra properties to set on the DataSource bean. See the <a href="http://commons.apache.org/dbcp/api-1.2.2/org/apache/commons/dbcp/BasicDataSource.html" target="blank">Commons DBCP BasicDataSource</a> documentation.</li> |
| </ul><p class="paragraph"/>A typical configuration for MySQL may be something like:<p class="paragraph"/><div class="code"><pre>dataSource { |
| pooled = <span class="java-keyword">true</span> |
| dbCreate = <span class="java-quote">"update"</span> |
| url = <span class="java-quote">"jdbc:mysql://localhost/yourDB"</span> |
| driverClassName = <span class="java-quote">"com.mysql.jdbc.Driver"</span> |
| dialect = org.hibernate.dialect.MySQL5InnoDBDialect |
| username = <span class="java-quote">"yourUser"</span> |
| password = <span class="java-quote">"yourPassword"</span> |
| }</pre></div><p class="paragraph"/><blockquote class="warning"> |
| When configuring the DataSource do not include the type or the def keyword before any of the configuration settings as Groovy will treat these as local variable definitions and they will not be processed. For example the following is invalid: |
| </blockquote><p class="paragraph"/><div class="code"><pre>dataSource { |
| <span class="java-object">boolean</span> pooled = <span class="java-keyword">true</span> // type declaration results in local variable |
| … |
| }</pre></div><p class="paragraph"/> |
| Example of advanced configuration using extra properties: |
| <div class="code"><pre>dataSource { |
| pooled = <span class="java-keyword">true</span> |
| dbCreate = <span class="java-quote">"update"</span> |
| url = <span class="java-quote">"jdbc:mysql://localhost/yourDB"</span> |
| driverClassName = <span class="java-quote">"com.mysql.jdbc.Driver"</span> |
| dialect = org.hibernate.dialect.MySQL5InnoDBDialect |
| username = <span class="java-quote">"yourUser"</span> |
| password = <span class="java-quote">"yourPassword"</span> |
| properties { |
| maxActive = 50 |
| maxIdle = 25 |
| minIdle = 5 |
| initialSize = 5 |
| minEvictableIdleTimeMillis = 60000 |
| timeBetweenEvictionRunsMillis = 60000 |
| maxWait = 10000 |
| validationQuery = <span class="java-quote">"/* ping */"</span> |
| } |
| }</pre></div> |
| <h2><a name="3.3.1 DataSources and Environments">3.3.1 DataSources and Environments</a></h2>The previous example configuration assumes you want the same config for all environments: production, test, development etc.<p class="paragraph"/>Grails' DataSource definition is "environment aware", however, so you can do:<p class="paragraph"/><div class="code"><pre>dataSource { |
| // common settings here |
| } |
| environments { |
| production { |
| dataSource { |
| url = <span class="java-quote">"jdbc:mysql://liveip.com/liveDb"</span> |
| } |
| } |
| }</pre></div> |
| <h2><a name="3.3.2 JNDI DataSources">3.3.2 JNDI DataSources</a></h2><h4>Referring to a JNDI DataSource</h4><p class="paragraph"/>Since many Java EE containers typically supply <code>DataSource</code> instances via the <a href="http://java.sun.com/products/jndi/" target="blank">Java Naming and Directory Interface</a> (JNDI). Sometimes you are required to look-up a <code>DataSource</code> via JNDI.<p class="paragraph"/>Grails supports the definition of JNDI data sources as follows:<p class="paragraph"/><div class="code"><pre>dataSource { |
| jndiName = <span class="java-quote">"java:comp/env/myDataSource"</span> |
| }</pre></div><p class="paragraph"/>The format on the JNDI name may vary from container to container, but the way you define the <code>DataSource</code> remains the same.<p class="paragraph"/><h4>Configuring a Development time JNDI resource</h4><p class="paragraph"/>The way in which you configure JNDI data sources at development time is plugin dependent. Using the <a href="http://grails.org/plugin/tomcat" target="blank">Tomcat</a> plugin you can define JNDI resources using the <code>grails.naming.entries</code> setting in <code>grails-app/conf/Config.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.naming.entries = [ |
| <span class="java-quote">"bean/MyBeanFactory"</span>: [ |
| auth: <span class="java-quote">"Container"</span>, |
| type: <span class="java-quote">"com.mycompany.MyBean"</span>, |
| factory: <span class="java-quote">"org.apache.naming.factory.BeanFactory"</span>, |
| bar: <span class="java-quote">"23"</span> |
| ], |
| <span class="java-quote">"jdbc/EmployeeDB"</span>: [ |
| type: <span class="java-quote">"javax.sql.DataSource"</span>, //required |
| auth: <span class="java-quote">"Container"</span>, // optional |
| description: <span class="java-quote">"Data source <span class="java-keyword">for</span> Foo"</span>, //optional |
| driverClassName: <span class="java-quote">"org.hsql.jdbcDriver"</span>, |
| url: <span class="java-quote">"jdbc:HypersonicSQL:database"</span>, |
| username: <span class="java-quote">"dbusername"</span>, |
| password: <span class="java-quote">"dbpassword"</span>, |
| maxActive: <span class="java-quote">"8"</span>, |
| maxIdle: <span class="java-quote">"4"</span> |
| ], |
| <span class="java-quote">"mail/session"</span>: [ |
| type: <span class="java-quote">"javax.mail.Session, |
| auth: "</span>Container<span class="java-quote">", |
| "</span>mail.smtp.host<span class="java-quote">": "</span>localhost" |
| ] |
| ]</pre></div> |
| <h2><a name="3.3.3 Automatic Database Migration">3.3.3 Automatic Database Migration</a></h2>The <code>dbCreate</code> property of the <code>DataSource</code> definition is important as it dictates what Grails should do at runtime with regards to automatically generating the database tables from <a href="../guide/single.html#5. Object Relational Mapping (GORM)" class="guide">GORM</a> classes. The options are: |
| <ul class="star"> |
| <li><code>create-drop</code> - Drops and re-creates the database when Grails starts, and drops the schema at the end of a clean shutdown.</li> |
| <li><code>create</code> - Drops and re-creates the database when Grails starts, but doesn't drop the schema at the end of a clean shutdown.</li> |
| <li><code>update</code> - Creates the database if it doesn't exist, and modifies it if it does exist. The modifications are rather basic though, and generally only include adding missing columns and tables. Will not drop or modify anything.</li> |
| <li><code>validate</code> - Makes no changes to your database. Compares the configuration with the existing database schema and reports warnings.</li> |
| <li>any other value - does nothing. Don't specify any value if you want to manage databases yourself or by using a 3rd-party tool.</li> |
| </ul><p class="paragraph"/><blockquote class="warning"> |
| Both <code>create-drop</code> and <code>create</code> will destroy all existing data hence use with caution! |
| </blockquote><p class="paragraph"/>In <a href="../guide/single.html#3.2 Environments" class="guide">development</a> mode <code>dbCreate</code> is by default set to "create-drop":<p class="paragraph"/><div class="code"><pre>dataSource { |
| dbCreate = <span class="java-quote">"create-drop"</span> // one of 'create', 'create-drop','update' |
| }</pre></div><p class="paragraph"/>What this does is automatically drop and re-create the database tables on each restart of the application. Obviously this may not be what you want in production.<p class="paragraph"/><blockquote class="note"> |
| Although Grails does not currently support Rails-style Migrations out of the box, there are currently three plugins that provide similar capabilities to Grails: Autobase (http://wiki.github.com/RobertFischer/autobase), The <a href="http://www.liquibase.org/manual/grails" target="blank">LiquiBase</a> plugin and the <a href="http://code.google.com/p/dbmigrate/wiki/Grails" target="blank">DbMigrate</a> plugin both of which are available via the <code>grails list-plugins</code> command |
| </blockquote> |
| <h2><a name="3.3.4 Transaction-aware DataSource Proxy">3.3.4 Transaction-aware DataSource Proxy</a></h2>The actual <code>dataSource</code> bean is wrapped in a transaction-aware proxy so you will be given the connection that's being used by the current transaction or Hibernate <code>Session</code> if one is active.<p class="paragraph"/>If this were not the case, then retrieving a connection from the <code>dataSource</code> would be a new connection, and you wouldn't be able to see changes that haven't been committed yet (assuming you have a sensible transaction isolation setting, e.g. <code>READ_COMMITTED</code> or better).<p class="paragraph"/>The "real" unproxied <code>dataSource</code> is still available to you if you need access to it; its bean name is <code>dataSourceUnproxied</code>.<p class="paragraph"/>You can access this bean like any other Spring bean, i.e. using dependency injection:<p class="paragraph"/><div class="code"><pre>class MyService {<p class="paragraph"/> def dataSourceUnproxied |
| … |
| }</pre></div><p class="paragraph"/>or by pulling it from the <code>ApplicationContext</code>:<p class="paragraph"/><div class="code"><pre>def dataSourceUnproxied = ctx.dataSourceUnproxied</pre></div> |
| <h2><a name="3.4 Externalized Configuration">3.4 Externalized Configuration</a></h2>The default configuration file <code>Config.groovy</code> in <code>grails-app/conf</code> is fine in the majority of cases, but there may be circumstances where you want to maintain the configuration in a file <em class="italic">outside</em> the main application structure. For example if you are deploying to a WAR some administrators prefer the configuration of the application to be externalized to avoid having to re-package the WAR due to a change of configuration.<p class="paragraph"/>In order to support deployment scenarios such as these the configuration can be externalized. To do so you need to point Grails at the locations of the configuration files Grails should be using by adding a <code>grails.config.locations</code> setting in <code>Config.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.config.locations = [ <span class="java-quote">"classpath:${appName}-config.properties"</span>, |
| <span class="java-quote">"classpath:${appName}-config.groovy"</span>, |
| <span class="java-quote">"file:${userHome}/.grails/${appName}-config.properties"</span>, |
| <span class="java-quote">"file:${userHome}/.grails/${appName}-config.groovy"</span>]</pre></div><p class="paragraph"/>In the above example we're loading configuration files (both Java properties files and <a href="http://groovy.codehaus.org/ConfigSlurper" target="blank">ConfigSlurper</a> configurations) from different places on the classpath and files located in <code>USER_HOME</code>.<p class="paragraph"/>Ultimately all configuration files get merged into the <code>config</code> property of the <a href="../api/org/codehaus/groovy/grails/commons/GrailsApplication.html" class="api">GrailsApplication</a> object and are hence obtainable from there.<p class="paragraph"/><blockquote class="note"> |
| Grails also supports the concept of property place holders and property override configurers as defined in <a href="http://www.springframework.org." target="blank">Spring</a> For more information on these see the section on <a href="../guide/single.html#14. Grails and Spring" class="guide">Grails and Spring</a> |
| </blockquote><h2><a name="3.5 Versioning">3.5 Versioning</a></h2><h4>Versioning Basics</h4><p class="paragraph"/>Grails has built in support for application versioning. When you first create an application with the <a href="../ref/Command Line/create-app.html" class="commandLine">create-app</a> command the version of the application is set to <code>0.1</code>. The version is stored in the application meta data file called <code>application.properties</code> in the root of the project.<p class="paragraph"/>To change the version of your application you can run the <a href="../ref/Command Line/set-version.html" class="commandLine">set-version</a> command:<p class="paragraph"/><div class="code"><pre>grails set-version 0.2</pre></div><p class="paragraph"/>The version is used in various commands including the <a href="../ref/Command Line/war.html" class="commandLine">war</a> command which will append the application version to the end of the created WAR file.<p class="paragraph"/><h4>Detecting Versions at Runtime</h4><p class="paragraph"/>You can detect the application version using Grails' support for application metadata using the <a href="../api/org/codehaus/groovy/grails/commons/GrailsApplication.html" class="api">GrailsApplication</a> class. For example within <a href="../guide/single.html#6.1 Controllers" class="guide">controllers</a> there is an implicit <a href="../ref/Controllers/grailsApplication.html" class="controllers">grailsApplication</a> variable that can be used:<p class="paragraph"/><div class="code"><pre>def version = grailsApplication.metadata['app.version']</pre></div><p class="paragraph"/>If it is the version of Grails you need you can use:<p class="paragraph"/><div class="code"><pre>def grailsVersion = grailsApplication.metadata['app.grails.version']</pre></div><p class="paragraph"/>or the <code>GrailsUtil</code> class:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.util.* |
| def grailsVersion = GrailsUtil.grailsVersion</pre></div><p class="paragraph"/><p class="paragraph"/><h2><a name="3.6 Project Documentation">3.6 Project Documentation</a></h2>Since Grails 1.2, the documentation engine that powers the creation of this documentation is available to your Grails projects.<p class="paragraph"/>The documentation engine uses a variation on the Textile syntax to automatically create project documentation with smart linking, formatting etc.<p class="paragraph"/><h4>Creating project documentation</h4><p class="paragraph"/>To use the engine you need to follow a few conventions. Firstly you need to create a <code>src/docs/guide</code> directory and then have numbered text files using the <code>gdoc</code> format. For example:<p class="paragraph"/><div class="code"><pre>+ src/docs/guide/1. Introduction.gdoc |
| + src/docs/guide/2. Getting Started.gdoc</pre></div><p class="paragraph"/>The title of each chapter is taken from the file name. The order is dictated by the numerical value at the beginning of the file name.<p class="paragraph"/><h4>Creating reference items</h4><p class="paragraph"/>Reference items appear in the left menu on the documentation and are useful for quick reference documentation. Each reference item belongs to a category and a category is a directory located in the <code>src/docs/ref</code> directory. For example say you defined a new method called <code>renderPDF</code>, that belongs to a category called <code>Controllers</code> this can be done by creating a gdoc text file at the following location:<p class="paragraph"/><div class="code"><pre>+ src/ref/Controllers/renderPDF.gdoc</pre></div><p class="paragraph"/><h4>Configuring Output Properties</h4><p class="paragraph"/>There are various properties you can set within your <code>grails-app/conf/Config.groovy</code> file that customize the output of the documentation such as: |
| <ul class="star"> |
| <li><strong class="bold">grails.doc.authors</strong> - The authors of the documentation</li> |
| <li><strong class="bold">grails.doc.license</strong> - The license of the software</li> |
| <li><strong class="bold">grails.doc.copyright</strong> - The copyright message to display</li> |
| <li><strong class="bold">grails.doc.footer</strong> - The footer to use</li> |
| </ul><p class="paragraph"/>Other properties such as the name of the documentation and the version are pulled from your project itself.<p class="paragraph"/><h4>Generating Documentation</h4><p class="paragraph"/>Once you have created some documentation (refer to the syntax guide in the next chapter) you can generate an HTML version of the documentation using the command:<p class="paragraph"/><div class="code"><pre>grails docs</pre></div><p class="paragraph"/>This command will output an <code>docs/manual/index.html</code> which can be opened to view your documentation.<p class="paragraph"/> |
| <h4>Documentation Syntax</h4><p class="paragraph"/>As mentioned the syntax is largely similar to Textile or Confluence style wiki markup. The following sections walk you through the syntax basics.<p class="paragraph"/><h5>Basic Formatting</h5><p class="paragraph"/>Monospace: <code>monospace</code> |
| <div class="code"><pre>@monospace@</pre></div><p class="paragraph"/>Italic: <em class="italic">italic</em> <div class="code"><pre>_italic_</pre></div><p class="paragraph"/>Bold: <strong class="bold">bold</strong> |
| <div class="code"><pre>*bold*</pre></div><p class="paragraph"/>Image: |
| <img border="0" class="center" src="http://grails.org/images/new/grailslogo_topNav.png"></img><p class="paragraph"/><div class="code"><pre>!http://grails.org/images/new/grailslogo_topNav.png!</pre></div><p class="paragraph"/><h5>Linking</h5><p class="paragraph"/>There are several ways to create links with the documentation generator. A basic external link can either be defined using confluence or textile style markup:<p class="paragraph"/><div class="code"><pre>[SpringSource|http://www.springsource.com/] or <span class="java-quote">"SpringSource"</span>:http://www.springsource.com/</pre></div><p class="paragraph"/>For links to other sections inside the user guide you can use the <code>guide:</code> prefix:<p class="paragraph"/><div class="code"><pre>[Intro|guide:1. Introduction]</pre></div><p class="paragraph"/>The documentation engine will warn you if any links to sections in your guide break. Sometimes though it is preferable not to hard code the actual names of guide sections since you may move them around. To get around this you can create an alias inside <code>grails-app/conf/Config.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.doc.alias.intro=<span class="java-quote">"1. Introduction"</span></pre></div><p class="paragraph"/>And then the link becomes:<p class="paragraph"/><div class="code"><pre>[Intro|guide:intro]</pre></div><p class="paragraph"/>This is useful since if you linked the to "1. Introduction" chapter many times you would have to change all of those links.<p class="paragraph"/>To link to reference items you can use a special syntax:<p class="paragraph"/><div class="code"><pre>[controllers|renderPDF]</pre></div><p class="paragraph"/>In this case the category of the reference item is on the left hand side of the | and the name of the reference item on the right.<p class="paragraph"/>Finally, to link to external APIs you can use the <code>api:</code> prefix. For example:<p class="paragraph"/><div class="code"><pre>[<span class="java-object">String</span>|api:java.lang.<span class="java-object">String</span>]</pre></div><p class="paragraph"/>The documentation engine will automatically create the appropriate javadoc link in this case. If you want to add additional APIs to the engine you can configure them in <code>grails-app/conf/Config.groovy</code>. For example:<p class="paragraph"/><div class="code"><pre>grails.doc.api.org.hibernate=<span class="java-quote">"http://docs.jboss.org/hibernate/stable/core/api"</span></pre></div><p class="paragraph"/>The above example configures classes within the <code>org.hibernate</code> package to link to the Hibernate website's API docs.<p class="paragraph"/><h5>Lists and Headings</h5><p class="paragraph"/>Headings can be created by specifying the letter 'h' followed by a number and then a dot:<p class="paragraph"/><div class="code"><pre>h3.<space>Heading3 |
| h4.<space>Heading4</pre></div><p class="paragraph"/>Unordered lists are defined with the use of the * character:<p class="paragraph"/><div class="code"><pre>* item 1 |
| ** subitem 1 |
| ** subitem 2 |
| * item 2</pre></div><p class="paragraph"/>Numbered lists can be defined with the # character:<p class="paragraph"/><div class="code"><pre># item 1</pre></div><p class="paragraph"/>Tables can be created using the <code>table</code> macro:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th><strong class="bold">Name</strong></th><th><strong class="bold">Number</strong></th></tr><tr class="table-odd"><td>Albert</td><td>46</td></tr><tr class="table-even"><td>Wilma</td><td>1348</td></tr><tr class="table-odd"><td>James</td><td>12</td></tr></table><p class="paragraph"/><div class="code"><pre>{table} |
| *Name* | *<span class="java-object">Number</span>* |
| Albert | 46 |
| Wilma | 1348 |
| James | 12 |
| {table}</pre></div><p class="paragraph"/><h5>Code and Notes</h5><p class="paragraph"/>You can define code blocks with the <code>code</code> macro:<p class="paragraph"/><div class="code"><pre>class Book { |
| <span class="java-object">String</span> title |
| }</pre></div><p class="paragraph"/><div class="code"><pre>{code} |
| class Book { |
| <span class="java-object">String</span> title |
| } |
| {code}</pre></div><p class="paragraph"/>The example above provides syntax highlighting for Java and Groovy code, but you can also highlight XML markup:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><hello></span>world<span class="xml-tag"></hello></span></pre></div><p class="paragraph"/><div class="code"><pre>{code:xml} |
| <hello>world</hello> |
| {code}</pre></div><p class="paragraph"/>There are also a couple of macros for displaying notes and warnings:<p class="paragraph"/>Note: |
| <blockquote class="note"> |
| This is a note! |
| </blockquote><p class="paragraph"/><div class="code"><pre>{note} |
| This is a note! |
| {note}</pre></div><p class="paragraph"/>Warning:<p class="paragraph"/><blockquote class="warning"> |
| This is a warning! |
| </blockquote><p class="paragraph"/><div class="code"><pre>{warning} |
| This is a warning! |
| {warning}</pre></div><p class="paragraph"/> |
| <h2><a name="3.7 Dependency Resolution">3.7 Dependency Resolution</a></h2>In order to control how JAR dependencies are resolved Grails features (since version 1.2) a dependency resolution DSL that allows you to control how dependencies for applications and plugins are resolved.<p class="paragraph"/>Inside the <code>grails-app/conf/BuildConfig.groovy</code> file you can specify a <code>grails.project.dependency.resolution</code> property that configures how dependencies are resolved:<p class="paragraph"/><div class="code"><pre>grails.project.dependency.resolution = { |
| // config here |
| }</pre></div><p class="paragraph"/>The default configuration looks like the following:<p class="paragraph"/><div class="code"><pre>grails.project.dependency.resolution = { |
| inherits <span class="java-quote">"global"</span> // inherit Grails' <span class="java-keyword">default</span> dependencies |
| log <span class="java-quote">"warn"</span> // log level of Ivy resolver, either 'error', |
| // 'warn', 'info', 'debug' or 'verbose' |
| repositories { |
| grailsHome()<p class="paragraph"/> // uncomment the below to enable remote dependency resolution |
| // from <span class="java-keyword">public</span> Maven repositories<p class="paragraph"/> //mavenCentral() |
| //mavenRepo <span class="java-quote">"http://snapshots.repository.codehaus.org"</span> |
| //mavenRepo <span class="java-quote">"http://repository.codehaus.org"</span> |
| //mavenRepo <span class="java-quote">"http://download.java.net/maven/2/"</span> |
| //mavenRepo "http://repository.jboss.com/maven2/ |
| } |
| dependencies { |
| // specify dependencies here under either 'build', 'compile', |
| // 'runtime', 'test' or 'provided' scopes, e.g. |
| // runtime 'com.mysql:mysql-connector-java:5.1.5' |
| } |
| }</pre></div><p class="paragraph"/>The details of the above will be explained in the next few sections.<p class="paragraph"/><h2><a name="3.7.1 Configurations and Dependencies">3.7.1 Configurations and Dependencies</a></h2>Grails features 5 dependency resolution configurations (or 'scopes') which you can take advantage of: |
| <ul class="star"> |
| <li> <code>build</code>: Dependencies for the build system only</li> |
| <li> <code>compile</code>: Dependencies for the compile step</li> |
| <li> <code>runtime</code>: Dependencies needed at runtime but not for compilation (see above)</li> |
| <li> <code>test</code>: Dependencies needed for testing but not at runtime (see above)</li> |
| <li> <code>provided</code>: Dependencies needed at development time, but not during WAR deployment</li> |
| </ul><p class="paragraph"/>Within the <code>dependencies</code> block you can specify a dependency that falls into one of these configurations by calling the equivalent method. For example if your application requires the MySQL driver to function at <code>runtime</code> you can specify as such:<p class="paragraph"/><div class="code"><pre>runtime 'com.mysql:mysql-connector-java:5.1.5'</pre></div><p class="paragraph"/>The above uses the string syntax which is <code>group:name:version</code>. You can also use a map-based syntax:<p class="paragraph"/><div class="code"><pre>runtime group:'com.mysql', name:'mysql-connector-java', version:'5.1.5'</pre></div><p class="paragraph"/>Multiple dependencies can be specified by passing multiple arguments:<p class="paragraph"/><div class="code"><pre>runtime 'com.mysql:mysql-connector-java:5.1.5', |
| 'net.sf.ehcache:ehcache:1.6.1'<p class="paragraph"/>// Or<p class="paragraph"/>runtime( |
| [group:'com.mysql', name:'mysql-connector-java', version:'5.1.5'], |
| [group:'net.sf.ehcache', name:'ehcache', version:'1.6.1'] |
| )</pre></div><p class="paragraph"/> |
| <h2><a name="3.7.2 Dependency Repositories">3.7.2 Dependency Repositories</a></h2><h4>Remote Repositories</h4><p class="paragraph"/>Grails, when installed, does not use any remote public repositories. There is a default <code>grailsHome()</code> repository that will locate the JAR files Grails needs from your Grails installation. If you want to take advantage of a public repository you need to specify as such inside the <code>repositories</code> block:<p class="paragraph"/><div class="code"><pre>repositories { |
| mavenCentral() |
| }</pre></div><p class="paragraph"/>In this case the default public Maven repository is specified. To use the SpringSource Enterprise Bundle Repository you can use the <code>ebr()</code> method:<p class="paragraph"/><div class="code"><pre>repositories { |
| ebr() |
| }</pre></div><p class="paragraph"/> |
| You can also specify a specific Maven repository to use by URL:<p class="paragraph"/><div class="code"><pre>repositories { |
| mavenRepo <span class="java-quote">"http://repository.codehaus.org"</span> |
| }</pre></div><p class="paragraph"/><h4>Local Resolvers</h4><p class="paragraph"/>If you do not wish to use a public Maven repository you can specify a flat file repository:<p class="paragraph"/><div class="code"><pre>repositories { |
| flatDir name:'myRepo', dirs:'/path/to/repo' |
| }</pre></div><p class="paragraph"/><h4>Custom Resolvers</h4><p class="paragraph"/>If all else fails since Grails builds on Apache Ivy you can specify an Ivy resolver:<p class="paragraph"/><div class="code"><pre>/* |
| * Configure our resolver. |
| */ |
| def libResolver = <span class="java-keyword">new</span> org.apache.ivy.plugins.resolver.URLResolver() |
| ['libraries', 'builds'].each { |
| libResolver.addArtifactPattern(<span class="java-quote">"http://my.repository/${it}/[organisation]/[module]/[revision]/[type]s/[artifact].[ext]"</span>) |
| libResolver.addIvyPattern(<span class="java-quote">"http://my.repository/${it}/[organisation]/[module]/[revision]/[type]s/[artifact].[ext]"</span>) |
| } |
| libResolver.name = <span class="java-quote">"my-repository"</span> |
| libResolver.settings = ivySettings<p class="paragraph"/>resolver libResolver</pre></div><p class="paragraph"/><h4>Authentication</h4><p class="paragraph"/>If your repository requires some form of authentication you can specify as such using a <code>credentials</code> block:<p class="paragraph"/><div class="code"><pre>credentials { |
| realm = <span class="java-quote">".."</span> |
| host = <span class="java-quote">"localhost"</span> |
| username = <span class="java-quote">"myuser"</span> |
| password = <span class="java-quote">"mypass"</span> |
| }</pre></div><p class="paragraph"/>The above can also be placed in your <code>USER_HOME/.grails/settings.groovy</code> file using the <code>grails.project.ivy.authentication</code> setting:<p class="paragraph"/><div class="code"><pre>grails.project.ivy.authentication = { |
| credentials { |
| realm = <span class="java-quote">".."</span> |
| host = <span class="java-quote">"localhost"</span> |
| username = <span class="java-quote">"myuser"</span> |
| password = <span class="java-quote">"mypass"</span> |
| } |
| }</pre></div><p class="paragraph"/><h2><a name="3.7.3 Debugging Resolution">3.7.3 Debugging Resolution</a></h2>If you are having trouble getting a dependency to resolve you can enable more verbose debugging from the underlying engine using the <code>log</code> method:<p class="paragraph"/><div class="code"><pre>// log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose' |
| log <span class="java-quote">"warn"</span></pre></div><p class="paragraph"/><h2><a name="3.7.4 Inherited Dependencies">3.7.4 Inherited Dependencies</a></h2>By default every Grails application inherits a bunch of framework dependencies. This is done through the line:<p class="paragraph"/><div class="code"><pre>inherits <span class="java-quote">"global"</span></pre></div><p class="paragraph"/>Inside the <code>BuildConfig.groovy</code> file. If you wish exclude certain inherited dependencies then you can do so using the <code>excludes</code> method:<p class="paragraph"/><div class="code"><pre>inherits(<span class="java-quote">"global"</span>) { |
| excludes <span class="java-quote">"oscache"</span>, <span class="java-quote">"ehcache"</span> |
| }</pre></div><p class="paragraph"/><p class="paragraph"/><h2><a name="3.7.5 Providing Default Dependencies">3.7.5 Providing Default Dependencies</a></h2>Most Grails applications will have runtime dependencies on a lot of jar files that are provided by the Grails framework. These |
| include libraries like Spring, Sitemesh, Hibernate etc. When a war file is created, all of these dependencies will be included |
| in it. But, an application may choose to exclude these jar files from the war. This is useful when the jar files will |
| be provided by the container, as would normally be the case if multiple Grails applications are deployed to the same container. |
| The dependency resolution DSL provides a mechanism to express that all of the default dependencies will be provided by the container. |
| This is done by invoking the <code>defaultDependenciesProvided</code> method and passing <code>true</code> as an argument:<p class="paragraph"/><div class="code"><pre>grails.project.dependency.resolution = {<p class="paragraph"/> defaultDependenciesProvided <span class="java-keyword">true</span> // all of the <span class="java-keyword">default</span> dependencies will be <span class="java-quote">"provided"</span> by the container<p class="paragraph"/> inherits <span class="java-quote">"global"</span> // inherit Grails' <span class="java-keyword">default</span> dependencies<p class="paragraph"/> repositories { |
| grailsHome() |
| // … |
| } |
| dependencies { |
| // … |
| } |
| }</pre></div><p class="paragraph"/>Note that <code>defaultDependenciesProvided</code> must come before <code>inherits</code>, otherwise the Grails dependencies will be included in the war. |
| <h2><a name="3.7.6 Dependency Reports">3.7.6 Dependency Reports</a></h2>As mentioned in the previous section a Grails application consists of dependencies inherited from the framework, the plugins installed and the application dependencies itself.<p class="paragraph"/>To obtain a report of an application's dependencies you can run the <a href="../ref/Command Line/dependency-report.html" class="commandLine">dependency-report</a> command:<p class="paragraph"/><div class="code"><pre>grails dependency-report</pre></div><p class="paragraph"/>This will output a report to the <code>target/dependency-report</code> directory by default. You can specify which configuration (scope) you want a report for by passing an argument containing the configuration name:<p class="paragraph"/><div class="code"><pre>grails dependency-report runtime</pre></div> |
| <h2><a name="3.7.7 Plugin JAR Dependencies">3.7.7 Plugin JAR Dependencies</a></h2><h4>Specifying Plugin JAR dependencies</h4><p class="paragraph"/>The way in which you specify dependencies for a <a href="../guide/single.html#12. Plug-ins" class="guide">plugin</a> is identical to how you specify dependencies in an application. When a plugin is installed into an application the application automatically inherits the dependencies of the plugin.<p class="paragraph"/>If you want to define a dependency that is resolved for use with the plugin but not <em class="italic">exported</em> to the application then you can set the <code>exported</code> property of the dependency:<p class="paragraph"/><div class="code"><pre>compile( 'org.hibernate:hibernate-core:3.3.1.GA') { |
| exported = <span class="java-keyword">false</span> |
| }</pre></div><p class="paragraph"/>In this can the <code>hibernate-core</code> dependency will be available only to the plugin and not resolved as an application dependency.<p class="paragraph"/> |
| <h4>Overriding Plugin JAR Dependencies in Your Application</h4><p class="paragraph"/>If a plugin is using a JAR which conflicts with another plugin, or an application dependency then you can override how a plugin resolves its dependencies inside an application using exclusions. For example:<p class="paragraph"/><div class="code"><pre>plugins { |
| runtime( <span class="java-quote">"org.grails.plugins:hibernate:1.3.0"</span> ) { |
| excludes <span class="java-quote">"javassist"</span> |
| } |
| }<p class="paragraph"/>dependencies { |
| runtime <span class="java-quote">"javassist:javassist:3.4.GA"</span> |
| }</pre></div><p class="paragraph"/>In this case the application explicitly declares a dependency on the "hibernate" plugin and specifies an exclusion using the <code>excludes</code> method, effectively excluding the javassist library as a dependency. |
| <h2><a name="3.7.8 Maven Integration">3.7.8 Maven Integration</a></h2>When using the Grails Maven plugin, Grails' dependency resolution mechanics are disabled as it is assumed that you will manage dependencies via Maven's <code>pom.xml</code> file.<p class="paragraph"/>However, if you would like to continue using Grails regular commands like <a href="../ref/Command Line/run-app.html" class="commandLine">run-app</a>, <a href="../ref/Command Line/test-app.html" class="commandLine">test-app</a> and so on then you can tell Grails' command line to load dependencies from the Maven <code>pom.xml</code> file instead.<p class="paragraph"/>To do so simply add the following line to your <code>BuildConfig.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.project.dependency.resolution = { |
| pom <span class="java-keyword">true</span> |
| .. |
| }</pre></div><p class="paragraph"/>The line <code>pom true</code> tells Grails to parse Maven's <code>pom.xml</code> and load dependencies from there. |
| <h2><a name="3.7.9 Deploying to a Maven Repository">3.7.9 Deploying to a Maven Repository</a></h2>If you are using Maven to build your Grails project, you can use the standard Maven targets <code>mvn install</code> and <code>mvn deploy</code>. |
| If not, you can deploy a Grails project or plugin to a Maven repository using the <a href="http://grails.org/plugin/maven-publisher" target="blank">maven-publisher</a> plugin.<p class="paragraph"/>The plugin provides the ability to publish Grails projects and plugins to local and remote Maven repositories. There are two key additional targets added by the plugin: |
| <ul class="star"> |
| <li><strong class="bold">maven-install</strong> - Installs a Grails project or plugin into your local Maven cache</li> |
| <li><strong class="bold">maven-deploy</strong> - Deploys a Grails project or plugin to a remote Maven repository</li> |
| </ul><p class="paragraph"/>By default this plugin will automatically generate a valid <code>pom.xml</code> for you unless a <code>pom.xml</code> is already present in the root of the project, in which case this <code>pom.xml</code> file will be used.<p class="paragraph"/><h4>maven-install</h4><p class="paragraph"/>The <code>maven-install</code> command will install the Grails project or plugin artifact into your local Maven cache:<p class="paragraph"/><div class="code"><pre>grails maven-install</pre></div><p class="paragraph"/>In the case of plugins, the plugin zip file will be installed, whilst for application the application WAR file will be installed.<p class="paragraph"/><h4>maven-deploy</h4><p class="paragraph"/>The <code>maven-deploy</code> command will deploy a Grails project or plugin into a remote Maven repository:<p class="paragraph"/><div class="code"><pre>grails maven-deploy</pre></div><p class="paragraph"/>It is assumed that you have specified the necessary <code><distributionManagement></code> configuration within a <code>pom.xml</code> or that you specify the <code>id</code> of the remote repository to deploy to:<p class="paragraph"/><div class="code"><pre>grails maven-deploy --repository=myRepo</pre></div><p class="paragraph"/>The <code>repository</code> argument specifies the 'id' for the repository. You need to configure the details of the repository specified by this 'id' within your <code>grails-app/conf/BuildConfig.groovy</code> file or in your <code>USER_HOMER/.grails/settings.groovy</code> file:<p class="paragraph"/><div class="code"><pre>grails.project.dependency.distribution = { |
| localRepository = <span class="java-quote">"/path/to/my/local"</span> |
| remoteRepository(id:<span class="java-quote">"myRepo"</span>, url:<span class="java-quote">"http://myserver/path/to/repo"</span>) |
| }</pre></div><p class="paragraph"/>The syntax for configuring remote repositories matches the syntax from the <a href="http://maven.apache.org/ant-tasks/reference.html#remoteRepository" target="blank">remoteRepository</a> element in the Ant Maven tasks. For example the following XML:<p class="paragraph"/><div class="code"><pre><remoteRepository id=<span class="java-quote">"myRepo"</span> url=<span class="java-quote">"scp://localhost/www/repository"</span>> |
| <authentication username=<span class="java-quote">"..."</span> privateKey=<span class="java-quote">"${user.home}/.ssh/id_dsa"</span>/> |
| </remoteRepository></pre></div><p class="paragraph"/>Can be expressed as:<p class="paragraph"/><div class="code"><pre>remoteRepository(id:<span class="java-quote">"myRepo"</span>, url:<span class="java-quote">"scp://localhost/www/repository"</span>) { |
| authentication username:<span class="java-quote">"..."</span>, privateKey:<span class="java-quote">"${userHome}/.ssh/id_dsa"</span> |
| }</pre></div><p class="paragraph"/>By default the plugin will try to detect the protocol to use from the URL of the repository (ie "http" from "http://.." etc.), however if you need to explicitly specify a different protocol you can do:<p class="paragraph"/><div class="code"><pre>grails maven-deploy --repository=myRepo --protocol=webdav</pre></div><p class="paragraph"/>The available protocols are: |
| <ul class="star"> |
| <li>http</li> |
| <li>scp</li> |
| <li>scpexe</li> |
| <li>ftp</li> |
| <li>webdav</li> |
| </ul><p class="paragraph"/><h4>Groups, Artifacts and Versions</h4><p class="paragraph"/>Maven defines the notion of a 'groupId', 'artifactId' and a 'version'. This plugin pulls this information from the Grails project conventions or plugin descriptor.<p class="paragraph"/><h5>Projects</h5><p class="paragraph"/>For applications this plugin will use the Grails application name and version provided by Grails when generating the <code>pom.xml</code> file. To change the version you can run the <code>set-version</code> command:<p class="paragraph"/><div class="code"><pre>grails set-version 0.2</pre></div><p class="paragraph"/>The Maven <code>groupId</code> will be the same as the project name, unless you specify a different one in Config.groovy:<p class="paragraph"/><div class="code"><pre>grails.project.groupId=<span class="java-quote">"com.mycompany"</span></pre></div><p class="paragraph"/><h5>Plugins</h5><p class="paragraph"/>With a Grails plugin the <code>groupId</code> and <code>version</code> are taken from the following properties in the *GrailsPlugin.groovy descriptor:<p class="paragraph"/><div class="code"><pre><span class="java-object">String</span> groupId = 'myOrg' |
| <span class="java-object">String</span> version = '0.1'</pre></div><p class="paragraph"/>The 'artifactId' is taken from the plugin name. For example if you have a plugin called <code>FeedsGrailsPlugin</code> the <code>artifactId</code> will be "feeds". If your plugin does not specify a <code>groupId</code> then this defaults to "org.grails.plugins". |
| <h2><a name="3.7.10 Plugin Dependencies">3.7.10 Plugin Dependencies</a></h2>As of Grails 1.3 you can declaratively specify dependencies on plugins rather than using the <a href="../ref/Command Line/install-plugin.html" class="commandLine">install-plugin</a> command:<p class="paragraph"/><div class="code"><pre>plugins { |
| runtime ':hibernate:1.2.1' |
| }</pre></div><p class="paragraph"/>If you don't specify a group id the default plugin group id of <code>org.grails.plugins</code> is used. You can specify to use the latest version of a particular plugin by using "latest.integration" as the version number:<p class="paragraph"/><div class="code"><pre>plugins { |
| runtime ':hibernate:latest.integration' |
| }</pre></div><p class="paragraph"/><h4>Integration vs. Release</h4><p class="paragraph"/>The "latest.integration" version label will also include resolving snapshot versions. If you don't want to include snapshot versions then you can use the "latest.release" label:<p class="paragraph"/><div class="code"><pre>plugins { |
| runtime ':hibernate:latest.release' |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| The "latest.release" label only works with Maven compatible repositories. If you have a regular SVN-based Grails repository then you should use "latest.integration". |
| </blockquote><p class="paragraph"/>And of course if you are using a Maven repository with an alternative group id you can specify a group id:<p class="paragraph"/><div class="code"><pre>plugins { |
| runtime 'mycompany:hibernate:latest.integration' |
| }</pre></div><p class="paragraph"/> |
| <h4>Plugin Exclusions</h4><p class="paragraph"/>You can control how plugins transitively resolves both plugin and JAR dependencies using exclusions. For example:<p class="paragraph"/><div class="code"><pre>plugins { |
| runtime( ':weceem:0.8' ) { |
| excludes <span class="java-quote">"searchable"</span> |
| } |
| }</pre></div><p class="paragraph"/>Here we have defined a dependency on the "weceem" plugin which transitively depends on the "searchable" plugin. By using the <code>excludes</code> method you can tell Grails <em class="italic">not</em> to transitively install the searchable plugin. You can combine this technique to specify an alternative version of a plugin:<p class="paragraph"/><div class="code"><pre>plugins { |
| runtime( ':weceem:0.8' ) { |
| excludes <span class="java-quote">"searchable"</span> // excludes most recent version |
| } |
| runtime ':searchable:0.5.4' // specifies a fixed searchable version |
| }</pre></div><p class="paragraph"/>You can also completely disable transitive plugin installs, in which case no transitive dependencies will be resolved:<p class="paragraph"/><div class="code"><pre>plugins { |
| runtime( ':weceem:0.8' ) { |
| transitive = <span class="java-keyword">false</span> |
| } |
| runtime ':searchable:0.5.4' // specifies a fixed searchable version |
| }</pre></div> |
| <h1><a name="4. The Command Line">4. The Command Line</a></h1>Grails' command line system is built on <a href="http://gant.codehaus.org/" target="blank">Gant</a> - a simple Groovy wrapper around <a href="http://ant.apache.org" target="blank">Apache Ant</a>.<p class="paragraph"/>However, Grails takes it a bit further through the use of convention and the <code>grails</code> command. When you type: |
| <div class="code"><pre>grails [command name]</pre></div> |
| Grails does a search in the following directories for Gant scripts to execute: |
| <ul class="star"> |
| <li><code>USER_HOME/.grails/scripts</code></li> |
| <li><code>PROJECT_HOME/scripts</code></li> |
| <li><code>PROJECT_HOME/plugins/*/scripts</code></li> |
| <li><code>GRAILS_HOME/scripts</code></li> |
| </ul><p class="paragraph"/>Grails will also convert command names that are in lower case form such as run-app into camel case. So typing<p class="paragraph"/><div class="code"><pre>grails run-app</pre></div><p class="paragraph"/>Results in a search for the following files: |
| <ul class="star"> |
| <li><code>USER_HOME/.grails/scripts/RunApp.groovy</code></li> |
| <li><code>PROJECT_HOME/scripts/RunApp.groovy</code></li> |
| <li><code>PLUGINS_HOME/*/scripts/RunApp.groovy</code></li> |
| <li><code>GLOBAL_PLUGINS_HOME/*/scripts/RunApp.groovy</code></li> |
| <li><code>GRAILS_HOME/scripts/RunApp.groovy</code></li> |
| </ul><p class="paragraph"/>If multiple matches are found Grails will give you a choice of which one to execute. When Grails executes a Gant script, it invokes the "default" target defined in that script. If there is no default, Grails will quit with an error.<p class="paragraph"/>To get a list and some help about the available commands type:<p class="paragraph"/><div class="code"><pre>grails help</pre></div><p class="paragraph"/>Which outputs usage instructions and the list of commands Grails is aware of: |
| <div class="code"><pre>Usage (optionals marked with *): |
| grails [environment]* [target] [arguments]*<p class="paragraph"/>Examples: |
| grails dev run-app |
| grails create-app books<p class="paragraph"/>Available Targets (type grails help 'target-name' <span class="java-keyword">for</span> more info): |
| grails bootstrap |
| grails bug-report |
| grails clean |
| grails compile |
| ...</pre></div><p class="paragraph"/><blockquote class="note"> |
| Refer to the Command Line reference in left menu of the reference guide for more information about individual commands |
| </blockquote> |
| <h2><a name="4.1 Creating Gant Scripts">4.1 Creating Gant Scripts</a></h2>You can create your own Gant scripts by running the <a href="../ref/Command Line/create-script.html" class="commandLine">create-script</a> command from the root of your project. For example the following command:<p class="paragraph"/><div class="code"><pre>grails create-script compile-sources</pre></div><p class="paragraph"/>Will create a script called <code>scripts/CompileSources.groovy</code>. A Gant script itself is similar to a regular Groovy script except that it supports the concept of "targets" and dependencies between them:<p class="paragraph"/><div class="code"><pre>target(<span class="java-keyword">default</span>:<span class="java-quote">"The <span class="java-keyword">default</span> target is the one that gets executed by Grails"</span>) { |
| depends(clean, compile) |
| } |
| target(clean:<span class="java-quote">"Clean out things"</span>) { |
| ant.delete(dir:<span class="java-quote">"output"</span>) |
| } |
| target(compile:<span class="java-quote">"Compile some sources"</span>) { |
| ant.mkdir(dir:<span class="java-quote">"mkdir"</span>) |
| ant.javac(srcdir:<span class="java-quote">"src/java"</span>, destdir:<span class="java-quote">"output"</span>) |
| }</pre></div><p class="paragraph"/>As demonstrated in the script above, there is an implicit <code>ant</code> variable that allows access to the <a href="http://ant.apache.org/manual/index.html" target="blank">Apache Ant API</a>. |
| <blockquote class="note"> |
| In previous versions of Grails (1.0.3 and below), the variable was <code>Ant</code>, i.e. with a capital first letter. |
| </blockquote><p class="paragraph"/>You can also "depend" on other targets using the <code>depends</code> method demonstrated in the <code>default</code> target above.<p class="paragraph"/><h3>The default target</h3><p class="paragraph"/>In the example above, we specified a target with the explicit name "default". This is one way of defining the default target for a script. An alternative approach is to use the <code>setDefaultTarget()</code> method:<p class="paragraph"/><div class="code"><pre>target(<span class="java-quote">"clean-compile"</span>: <span class="java-quote">"Performs a clean compilation on the app's source files."</span>) { |
| depends(clean, compile) |
| } |
| target(clean:<span class="java-quote">"Clean out things"</span>) { |
| ant.delete(dir:<span class="java-quote">"output"</span>) |
| } |
| target(compile:<span class="java-quote">"Compile some sources"</span>) { |
| ant.mkdir(dir:<span class="java-quote">"mkdir"</span>) |
| ant.javac(srcdir:<span class="java-quote">"src/java"</span>, destdir:<span class="java-quote">"output"</span>) |
| }<p class="paragraph"/>setDefaultTarget(<span class="java-quote">"clean-compile"</span>)</pre></div><p class="paragraph"/>This allows you to call the default target directly from other scripts if you wish. Also, although we have put the call to <code>setDefaultTarget()</code> at the end of the script in this example, it can go anywhere as long as it comes <em class="italic">after</em> the target it refers to ("clean-compile" in this case).<p class="paragraph"/>Which approach is better? To be honest, you can use whichever you prefer - there don't seem to be any major advantages in either case. One thing we would say is that if you want to allow other scripts to call your "default" target, you should move it into a shared script that doesn't have a default target at all. We'll talk some more about this in the next section. |
| <h2><a name="4.2 Re-using Grails scripts">4.2 Re-using Grails scripts</a></h2>Grails ships with a lot of command line functionality out of the box that you may find useful in your own scripts (See the command line reference in the reference guide for info on all the commands). Of particular use are the <a href="../ref/Command Line/compile.html" class="commandLine">compile</a>, <a href="../ref/Command Line/package.html" class="commandLine">package</a> and <a href="../ref/Command Line/bootstrap.html" class="commandLine">bootstrap</a> scripts.<p class="paragraph"/>The <a href="../ref/Command Line/bootstrap.html" class="commandLine">bootstrap</a> script for example allows you to bootstrap a Spring <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/ApplicationContext.html" class="api">ApplicationContext</a> instance to get access to the data source and so on (the integration tests use this):<p class="paragraph"/><div class="code"><pre>includeTargets << grailsScript(<span class="java-quote">"_GrailsBootstrap"</span>)<p class="paragraph"/>target ('<span class="java-keyword">default</span>': <span class="java-quote">"Load the Grails interactive shell"</span>) { |
| depends( configureProxy, packageApp, classpath, loadApp, configureApp )<p class="paragraph"/> Connection c |
| <span class="java-keyword">try</span> { |
| // <span class="java-keyword">do</span> something with connection |
| c = appCtx.getBean('dataSource').getConnection() |
| } |
| <span class="java-keyword">finally</span> { |
| c?.close() |
| } |
| }</pre></div><p class="paragraph"/><h3>Pulling in targets from other scripts</h3><p class="paragraph"/>Gant allows you to pull in all targets (except "default") from another Gant script. You can then depend upon or invoke those targets as if they had been defined in the current script. The mechanism for doing this is the <code>includeTargets</code> property. Simply "append" a file or class to it using the left-shift operator: |
| <div class="code"><pre>includeTargets << <span class="java-keyword">new</span> File(<span class="java-quote">"/path/to/my/script.groovy"</span>) |
| includeTargets << gant.tools.Ivy</pre></div> |
| Don't worry too much about the syntax using a class, it's quite specialised. If you're interested, look into the Gant documentation.<p class="paragraph"/><h3>Core Grails targets</h3><p class="paragraph"/>As you saw in the example at the beginning of this section, you use neither the File- nor the class-based syntax for <code>includeTargets</code> when including core Grails targets. Instead, you should use the special <code>grailsScript()</code> method that is provided by the Grails command launcher (note that this is not available in normal Gant scripts, just Grails ones).<p class="paragraph"/>The syntax for the <code>grailsScript()</code> method is pretty straightforward: simply pass it the name of the Grails script you want to include, without any path information. Here is a list of Grails scripts that you may want to re-use: |
| <table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th><strong class="bold">Script</strong></th><th><strong class="bold">Description</strong></th></tr><tr class="table-odd"><td>_GrailsSettings</td><td>You really should include this! Fortunately, it is included automatically by all other Grails scripts bar one (_GrailsProxy), so you usually don't have to include it explicitly.</td></tr><tr class="table-even"><td>_GrailsEvents</td><td>If you want to fire events, you need to include this. Adds an <code>event(String eventName, List args)</code> method. Again, included by almost all other Grails scripts.</td></tr><tr class="table-odd"><td>_GrailsClasspath</td><td>Sets up compilation, test, and runtime classpaths. If you want to use or play with them, include this script. Again, included by almost all other Grails scripts.</td></tr><tr class="table-even"><td>_GrailsProxy</td><td>If you want to access the internet, include this script so that you don't run into problems with proxies.</td></tr><tr class="table-odd"><td>_GrailsArgParsing</td><td>Provides a <code>parseArguments</code> target that does what it says on the tin: parses the arguments provided by the user when they run your script. Adds them to the <code>argsMap</code> property.</td></tr><tr class="table-even"><td>_GrailsTest</td><td>Contains all the shared test code. Useful if you want to add any extra tests.</td></tr><tr class="table-odd"><td>_GrailsRun</td><td>Provides all you need to run the application in the configured servlet container, either normally (<code>runApp</code>/<code>runAppHttps</code>) or from a WAR file (<code>runWar</code>/<code>runWarHttps</code>).</td></tr></table><p class="paragraph"/>There are many more scripts provided by Grails, so it is worth digging into the scripts themselves to find out what kind of targets are available. Anything that starts with an "_" is designed for re-use.<p class="paragraph"/> <blockquote class="note"> |
| In pre-1.1 versions of Grails, the "_Grails..." scripts were not available. Instead, you typically include the corresponding command script, for example "Init.groovy" or "Bootstrap.groovy".<p class="paragraph"/>Also, in pre-1.0.4 versions of Grails you cannot use the <code>grailsScript()</code> method. Instead, you must use <code>includeTargets << new File(...)</code> and specify the script's location in full (i.e. $GRAILS_HOME/scripts). |
| </blockquote><p class="paragraph"/><h3>Script architecture</h3><p class="paragraph"/>You maybe wondering what those underscores are doing in the names of the Grails scripts. That is Grails' way of determining that a script is _internal_, or in other words that it has not corresponding "command". So you can't run "grails _grails-settings" for example. That is also why they don't have a default target.<p class="paragraph"/>Internal scripts are all about code sharing and re-use. In fact, we recommend you take a similar approach in your own scripts: put all your targets into an internal script that can be easily shared, and provide simple command scripts that parse any command line arguments and delegate to the targets in the internal script. Say you have a script that runs some functional tests - you can split it like this: |
| <div class="code"><pre>./scripts/FunctionalTests.groovy:<p class="paragraph"/>includeTargets << <span class="java-keyword">new</span> File(<span class="java-quote">"${basedir}/scripts/_FunctionalTests.groovy"</span>)<p class="paragraph"/>target(<span class="java-keyword">default</span>: <span class="java-quote">"Runs the functional tests <span class="java-keyword">for</span> <span class="java-keyword">this</span> project."</span>) { |
| depends(runFunctionalTests) |
| }<p class="paragraph"/>./scripts/_FunctionalTests.groovy:<p class="paragraph"/>includeTargets << grailsScript(<span class="java-quote">"_GrailsTest"</span>)<p class="paragraph"/>target(runFunctionalTests: <span class="java-quote">"Run functional tests."</span>) { |
| depends(...) |
| … |
| }</pre></div><p class="paragraph"/>Here are a few general guidelines on writing scripts: |
| <ul class="star"> |
| <li>Split scripts into a "command" script and an internal one.</li> |
| <li>Put the bulk of the implementation in the internal script.</li> |
| <li>Put argument parsing into the "command" script.</li> |
| <li>To pass arguments to a target, create some script variables and initialise them before calling the target.</li> |
| <li>Avoid name clashes by using closures assigned to script variables instead of targets. You can then pass arguments direct to the closures.</li> |
| </ul><p class="paragraph"/><h2><a name="4.3 Hooking into Events">4.3 Hooking into Events</a></h2>Grails provides the ability to hook into scripting events. These are events triggered during execution of Grails target and plugin scripts.<p class="paragraph"/>The mechanism is deliberately simple and loosely specified. The list of possible events is not fixed in any way, so it is possible to hook into events triggered by plugin scripts, for which there is no equivalent event in the core target scripts.<p class="paragraph"/><h4>Defining event handlers</h4><p class="paragraph"/>Event handlers are defined in scripts called <code>_Events.groovy</code>. Grails searches for these scripts in the following locations: |
| <ul class="star"> |
| <li><code>USER_HOME/.grails/scripts</code> - user-specific event handlers</li> |
| <li><code>PROJECT_HOME/scripts</code> - applicaton-specific event handlers</li> |
| <li><code>PLUGINS_HOME/*/scripts</code> - plugin-specific event handlers</li> |
| <li><code>GLOBAL_PLUGINS_HOME/*/scripts</code> - event handlers provided by global plugins</li> |
| </ul><p class="paragraph"/>Whenever an event is fired, <em class="italic">all</em> the registered handlers for that event are executed. Note that the registration of handlers is performed automatically by Grails, so you just need to declare them in the relevant <code>_Events.groovy</code> file.<p class="paragraph"/><blockquote class="note"> |
| In versions of Grails prior to 1.0.4, the script was called <code>Events.groovy</code>, that is without the leading underscore. |
| </blockquote><p class="paragraph"/>Event handlers are blocks defined in <code>_Events.groovy</code>, with a name beginning with "event". The following example can be put in your /scripts directory to demonstrate the feature:<p class="paragraph"/><div class="code"><pre>eventCreatedArtefact = { type, name -> |
| println <span class="java-quote">"Created $type $name"</span> |
| }<p class="paragraph"/>eventStatusUpdate = { msg -> |
| println msg |
| }<p class="paragraph"/>eventStatusFinal = { msg -> |
| println msg |
| }</pre></div><p class="paragraph"/>You can see here the three handlers <code>eventCreatedArtefact</code>, <code>eventStatusUpdate</code>, <code>eventStatusFinal</code>. Grails provides some standard events, which are documented in the command line reference guide. For example the <a href="../ref/Command Line/compile.html" class="commandLine">compile</a> command fires the following events: |
| <ul class="star"> |
| <li><code>CompileStart</code> - Called when compilation starts, passing the kind of compile - source or tests</li> |
| <li><code>CompileEnd</code> - Called when compilation is finished, passing the kind of compile - source or tests</li> |
| </ul><p class="paragraph"/><h4>Triggering events</h4><p class="paragraph"/>To trigger an event simply include the Init.groovy script and call the event() closure:<p class="paragraph"/><div class="code"><pre>includeTargets << grailsScript(<span class="java-quote">"_GrailsEvents"</span>)<p class="paragraph"/>event(<span class="java-quote">"StatusFinal"</span>, [<span class="java-quote">"Super duper plugin action complete!"</span>])</pre></div><p class="paragraph"/><h4>Common Events</h4><p class="paragraph"/>Below is a table of some of the common events that can be leveraged:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Event</th><th>Parameters</th><th>Description</th></tr><tr class="table-odd"><td>StatusUpdate</td><td>message</td><td>Passed a string indicating current script status/progress</td></tr><tr class="table-even"><td>StatusError</td><td>message</td><td>Passed a string indicating an error message from the current script</td></tr><tr class="table-odd"><td>StatusFinal</td><td>message</td><td>Passed a string indicating the final script status message, i.e. when completing a target, even if the target does not exit the scripting environment</td></tr><tr class="table-even"><td>CreatedArtefact</td><td>artefactType,artefactName</td><td>Called when a create-xxxx script has completed and created an artefact</td></tr><tr class="table-odd"><td>CreatedFile</td><td>fileName</td><td>Called whenever a project source filed is created, not including files constantly managed by Grails</td></tr><tr class="table-even"><td>Exiting</td><td>returnCode</td><td>Called when the scripting environment is about to exit cleanly</td></tr><tr class="table-odd"><td>PluginInstalled</td><td>pluginName</td><td>Called after a plugin has been installed</td></tr><tr class="table-even"><td>CompileStart</td><td>kind</td><td>Called when compilation starts, passing the kind of compile - source or tests</td></tr><tr class="table-odd"><td>CompileEnd</td><td>kind</td><td>Called when compilation is finished, passing the kind of compile - source or tests</td></tr><tr class="table-even"><td>DocStart</td><td>kind</td><td>Called when documentation generation is about to start - javadoc or groovydoc</td></tr><tr class="table-odd"><td>DocEnd</td><td>kind</td><td>Called when documentation generation has ended - javadoc or groovydoc</td></tr><tr class="table-even"><td>SetClasspath</td><td>rootLoader</td><td>Called during classpath initialization so plugins can augment the classpath with rootLoader.addURL(...). Note that this augments the classpath <strong class="bold">after</strong> event scripts are loaded so you cannot use this to load a class that your event script needs to import, although you can do this if you load the class by name.</td></tr><tr class="table-odd"><td>PackagingEnd</td><td>none</td><td>Called at the end of packaging (which is called prior to the Tomcat server being started and after web.xml is generated)</td></tr></table> |
| <h2><a name="4.4 Customising the build">4.4 Customising the build</a></h2>Grails is most definitely an opinionated framework and it prefers convention to configuration, but this doesn't mean you <em class="italic">can't</em> configure it. In this section, we look at how you can influence and modify the standard Grails build.<p class="paragraph"/><h3>The defaults</h3><p class="paragraph"/>In order to customise a build, you first need to know <em class="italic">what</em> you can customise. The core of the Grails build configuration is the <code>grails.util.BuildSettings</code> class, which contains quite a bit of useful information. It controls where classes are compiled to, what dependencies the application has, and other such settings.<p class="paragraph"/>Here is a selection of the configuration options and their default values: |
| <table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th><strong class="bold">Property</strong></th><th><strong class="bold">Config option</strong></th><th><strong class="bold">Default value</strong></th></tr><tr class="table-odd"><td>grailsWorkDir</td><td>grails.work.dir</td><td>$USER_HOME/.grails/<grailsVersion></td></tr><tr class="table-even"><td>projectWorkDir</td><td>grails.project.work.dir</td><td><grailsWorkDir>/projects/<baseDirName></td></tr><tr class="table-odd"><td>classesDir</td><td>grails.project.class.dir</td><td><projectWorkDir>/classes</td></tr><tr class="table-even"><td>testClassesDir</td><td>grails.project.test.class.dir</td><td><projectWorkDir>/test-classes</td></tr><tr class="table-odd"><td>testReportsDir</td><td>grails.project.test.reports.dir</td><td><projectWorkDir>/test/reports</td></tr><tr class="table-even"><td>resourcesDir</td><td>grails.project.resource.dir</td><td><projectWorkDir>/resources</td></tr><tr class="table-odd"><td>projectPluginsDir</td><td>grails.project.plugins.dir</td><td><projectWorkDir>/plugins</td></tr><tr class="table-even"><td>globalPluginsDir</td><td>grails.global.plugins.dir</td><td><grailsWorkDir>/global-plugins</td></tr><tr class="table-odd"><td>verboseCompile</td><td>grails.project.compile.verbose</td><td>false</td></tr></table><p class="paragraph"/>The <code>BuildSettings</code> class has some other properties too, but they should be treated as read-only: |
| <table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th><strong class="bold">Property</strong></th><th><strong class="bold">Description</strong></th></tr><tr class="table-odd"><td>baseDir</td><td>The location of the project.</td></tr><tr class="table-even"><td>userHome</td><td>The user's home directory.</td></tr><tr class="table-odd"><td>grailsHome</td><td>The location of the Grails installation in use (may be null).</td></tr><tr class="table-even"><td>grailsVersion</td><td>The version of Grails being used by the project.</td></tr><tr class="table-odd"><td>grailsEnv</td><td>The current Grails environment.</td></tr><tr class="table-even"><td>compileDependencies</td><td>A list of compile-time project dependencies as <code>File</code> instances.</td></tr><tr class="table-odd"><td>testDependencies</td><td>A list of test-time project dependencies as <code>File</code> instances.</td></tr><tr class="table-even"><td>runtimeDependencies</td><td>A list of runtime-time project dependencies as <code>File</code> instances.</td></tr></table><p class="paragraph"/>Of course, these properties aren't much good if you can't get hold of them. Fortunately that's easy to do: an instance of <code>BuildSettings</code> is available to your scripts via the <code>grailsSettings</code> script variable. You can also access it from your code by using the <code>grails.util.BuildSettingsHolder</code> class, but this isn't recommended.<p class="paragraph"/><h3>Overriding the defaults</h3><p class="paragraph"/>All of the properties in the first table can be overridden by a system property or a configuration option - simply use the "config option" name. For example, to change the project working directory, you could either run this command: |
| <div class="code"><pre>grails -Dgrails.project.work.dir=work compile</pre></div> |
| or add this option to your <code>grails-app/conf/BuildConfig.groovy</code> file: |
| <div class="code"><pre>grails.project.work.dir = <span class="java-quote">"work"</span></pre></div> |
| Note that the default values take account of the property values they depend on, so setting the project working directory like this would also relocate the compiled classes, test classes, resources, and plugins.<p class="paragraph"/>What happens if you use both a system property and a configuration option? Then the system property wins because it takes precedence over the <code>BuildConfig.groovy</code> file, which in turn takes precedence over the default values.<p class="paragraph"/>The <code>BuildConfig.groovy</code> file is a sibling of <code>grails-app/conf/Config.groovy</code> - the former contains options that only affect the build, whereas the latter contains those that affect the application at runtime. It's not limited to the options in the first table either: you will find build configuration options dotted around the documentation, such as ones for specifying the port that the embedded servlet container runs on or for determining what files get packaged in the WAR file.<p class="paragraph"/><h3>Available build settings</h3><p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Name</th><th>Description</th></tr><tr class="table-odd"><td>grails.server.port.http</td><td>Port to run the embedded servlet container on ("run-app" and "run-war"). Integer.</td></tr><tr class="table-even"><td>grails.server.port.https</td><td>Port to run the embedded servlet container on for HTTPS ("run-app --https" and "run-war --https"). Integer.</td></tr><tr class="table-odd"><td>grails.config.base.webXml</td><td>Path to a custom web.xml file to use for the application (alternative to using the web.xml template).</td></tr><tr class="table-even"><td>grails.compiler.dependencies</td><td>Legacy approach to adding extra dependencies to the compiler classpath. Set it to a closure containing "fileset()" entries.</td></tr><tr class="table-odd"><td>grails.testing.patterns</td><td>A list of Ant path patterns that allow you to control which files are included in the tests. The patterns should not include the test case suffix, which is set by the next property.</td></tr><tr class="table-even"><td>grails.testing.nameSuffix</td><td>By default, tests are assumed to have a suffix of "Tests". You can change it to anything you like but setting this option. For example, another common suffix is "Test".</td></tr><tr class="table-odd"><td>grails.project.war.file</td><td>A string containing the file path of the generated WAR file, along with its full name (include extension). For example, "target/my-app.war".</td></tr><tr class="table-even"><td>grails.war.dependencies</td><td>A closure containing "fileset()" entries that allows you complete control over what goes in the WAR's "WEB-INF/lib" directory.</td></tr><tr class="table-odd"><td>grails.war.copyToWebApp</td><td>A closure containing "fileset()" entries that allows you complete control over what goes in the root of the WAR. It overrides the default behaviour of including everything under "web-app".</td></tr><tr class="table-even"><td>grails.war.resources</td><td>A closure that takes the location of the staging directory as its first argument. You can use any Ant tasks to do anything you like. It is typically used to remove files from the staging directory before that directory is jar'd up into a WAR.</td></tr><tr class="table-odd"><td>grails.project.web.xml</td><td>The location to generate Grails' web.xml to</td></tr></table> |
| <h2><a name="4.5 Ant and Maven">4.5 Ant and Maven</a></h2>If all the other projects in your team or company are built using a standard build tool such as Ant or Maven, you become the black sheep of the family when you use the Grails command line to build your application. Fortunately, you can easily integrate the Grails build system into the main build tools in use today (well, the ones in use in Java projects at least).<p class="paragraph"/><h3>Ant Integration</h3><p class="paragraph"/>When you create a Grails application via the <a href="../ref/Command Line/create-app.html" class="commandLine">create-app</a> command, Grails automatically creates an <a href="http://ant.apache.org/" target="blank">Apache Ant</a> <code>build.xml</code> file for you containing the following targets: |
| <ul class="star"> |
| <li><code>clean</code> - Cleans the Grails application</li> |
| <li><code>compile</code> - Compiles your application's source code</li> |
| <li><code>test</code> - Runs the unit tests</li> |
| <li><code>run</code> - Equivalent to "grails run-app"</li> |
| <li><code>war</code> - Creates a WAR file</li> |
| <li><code>deploy</code> - Empty by default, but can be used to implement automatic deployment</li> |
| </ul><p class="paragraph"/>Each of these can be run by Ant, for example:<p class="paragraph"/><div class="code"><pre>ant war</pre></div><p class="paragraph"/>The build file is all geared up to use <a href="http://ant.apache.org/ivy/" target="blank">Apache Ivy</a> for dependency management, which means that it will automatically download all the requisite Grails JAR files and other dependencies on demand. You don't even have to install Grails locally to use it! That makes it particularly useful for continuous integration systems such as <a href="http://cruisecontrol.sourceforge.net/" target="blank">CruiseControl</a> or <a href="https://hudson.dev.java.net/." target="blank">Hudson</a><p class="paragraph"/>It uses the Grails <a href="../api/grails/ant/GrailsTask.html" class="api">Ant task</a> to hook into the existing Grails build system. The task allows you to run any Grails script that's available, not just the ones used by the generated build file. To use the task, you must first declare it: |
| <div class="code"><pre><taskdef name=<span class="java-quote">"grailsTask"</span> |
| classname=<span class="java-quote">"grails.ant.GrailsTask"</span> |
| classpathref=<span class="java-quote">"grails.classpath"</span>/></pre></div><p class="paragraph"/>This raises the question: what should be in "grails.classpath"? The task itself is in the "grails-bootstrap" JAR artifact, so that needs to be on the classpath at least. You should also include the "groovy-all" JAR. With the task defined, you just need to use it! The following table shows you what attributes are available: |
| <table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Attribute</th><th>Description</th><th>Required</th></tr><tr class="table-odd"><td>home</td><td>The location of the Grails installation directory to use for the build.</td><td>Yes, unless classpath is specified.</td></tr><tr class="table-even"><td>classpathref</td><td>Classpath to load Grails from. Must include the "grails-bootstrap" artifact and should include "grails-scripts".</td><td>Yes, unless <code>home</code> is set or you use a <code>classpath</code> element.</td></tr><tr class="table-odd"><td>script</td><td>The name of the Grails script to run, e.g. "TestApp".</td><td>Yes.</td></tr><tr class="table-even"><td>args</td><td>The arguments to pass to the script, e.g. "-unit -xml".</td><td>No. Defaults to "".</td></tr><tr class="table-odd"><td>environment</td><td>The Grails environment to run the script in.</td><td>No. Defaults to the script default.</td></tr><tr class="table-even"><td>includeRuntimeClasspath</td><td>Advanced setting: adds the application's runtime classpath to the build classpath if true.</td><td>No. Defaults to true.</td></tr></table><p class="paragraph"/>The task also supports the following nested elements, all of which are standard Ant path structures: |
| <ul class="star"> |
| <li><code>classpath</code> - The build classpath (used to load Gant and the Grails scripts).</li> |
| <li><code>compileClasspath</code> - Classpath used to compile the application's classes.</li> |
| <li><code>runtimeClasspath</code> - Classpath used to run the application and package the WAR. Typically includes everything in @compileClasspath.</li> |
| <li><code>testClasspath</code> - Classpath used to compile and run the tests. Typically includes everything in <code>runtimeClasspath</code>.</li> |
| </ul><p class="paragraph"/>How you populate these paths is up to you. If you are using the <code>home</code> attribute and put your own dependencies in the <code>lib</code> directory, then you don't even need to use any of them. For an example of their use, take a look at the generated Ant build file for new apps.<p class="paragraph"/><h3>Maven Integration</h3><p class="paragraph"/>From 1.1 onwards, Grails provides integration with <a href="http://maven.apache.org" target="blank">Maven 2</a> via a Maven plugin. The current Maven plugin is based on, but effectively supersedes, the version created by <a href="http://forge.octo.com/" target="blank">Octo</a>, who did a great job.<p class="paragraph"/><h4>Preparation</h4><p class="paragraph"/>In order to use the new plugin, all you need is Maven 2 installed and set up. This is because <strong class="bold">you no longer need to install Grails separately to use it with Maven!</strong><p class="paragraph"/><blockquote class="note"> |
| The Maven 2 integration for Grails has been designed and tested for Maven 2.0.9 and above. It will not work with earlier versions. |
| </blockquote><p class="paragraph"/><blockquote class="note"> |
| The default mvn setup DOES NOT supply sufficient memory to run the Grails environment. We recommend that you add the following environment variable setting to prevent poor performance:<p class="paragraph"/><code>export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=192m"</code> |
| </blockquote><p class="paragraph"/><h4>Creating a Grails Maven Project</h4><p class="paragraph"/>To create a Mavenized Grails project simply run the following command:<p class="paragraph"/><div class="code"><pre>mvn archetype:generate -DarchetypeGroupId=org.grails \ |
| -DarchetypeArtifactId=grails-maven-archetype \ |
| -DarchetypeVersion=1.3.2 \ |
| -DgroupId=example -DartifactId=my-app</pre></div><p class="paragraph"/>Choose whichever grails version, group ID and artifact ID you want for your application, but everything else must be as written. This will create a new Maven project with a POM and a couple of other files. What you won't see is anything that looks like a Grails application. So, the next step is to create the project structure that you're used to. |
| But first, if you want to set target JDK to Java 6, do that now. Open my-app/pom.xml and change |
| <div class="code"><pre><plugin> |
| <artifactId>maven-compiler-plugin</artifactId> |
| <configuration> |
| <source>1.5</source> |
| <target>1.5</target> |
| </configuration> |
| </plugin></pre></div> |
| to |
| <div class="code"><pre><plugin> |
| <artifactId>maven-compiler-plugin</artifactId> |
| <configuration> |
| <source>1.6</source> |
| <target>1.6</target> |
| </configuration> |
| </plugin></pre></div><p class="paragraph"/>Then you're ready to create the project structure:<p class="paragraph"/><div class="code"><pre>cd my-app |
| mvn initialize</pre></div><p class="paragraph"/><blockquote class="note"> |
| if you see a message similar to this:<p class="paragraph"/><div class="code"><pre>Resolving plugin JAR dependencies … |
| :: problems summary :: |
| :::: WARNINGS |
| module not found: org.hibernate#hibernate-core;3.3.1.GA</pre></div><p class="paragraph"/>you need to add the plugins manually to application.properties:<p class="paragraph"/><div class="code"><pre>plugins.hibernate=1.3.2 |
| plugins.tomcat=1.3.2</pre></div><p class="paragraph"/>then run<p class="paragraph"/><div class="code"><pre>mvn compile</pre></div><p class="paragraph"/>and the hibernate and tomcat plugins will be installed. |
| </blockquote><p class="paragraph"/>Now you have a Grails application all ready to go. The plugin integrates into the standard build cycle, so you can use the standard Maven phases to build and package your app: <code>mvn clean</code> , <code>mvn compile</code> , <code>mvn test</code> , <code>mvn package</code> , <code>mvn install</code> .<p class="paragraph"/>You can also take advantage of some of the Grails commands that have been wrapped as Maven goals: |
| <ul class="star"> |
| <li><code>grails:create-controller</code> - Calls the <a href="../ref/Command Line/create-controller.html" class="commandLine">create-controller</a> command</li> |
| <li><code>grails:create-domain-class</code> - Calls the <a href="../ref/Command Line/create-domain-class.html" class="commandLine">create-domain-class</a> command</li> |
| <li><code>grails:create-integration-test</code> - Calls the <a href="../ref/Command Line/create-integration-test.html" class="commandLine">create-integration-test</a> command</li> |
| <li><code>grails:create-pom</code> - Creates a new Maven POM for an existing Grails project</li> |
| <li><code>grails:create-script</code> - Calls the <a href="../ref/Command Line/create-script.html" class="commandLine">create-script</a> command</li> |
| <li><code>grails:create-service</code> - Calls the <a href="../ref/Command Line/create-service.html" class="commandLine">create-service</a> command</li> |
| <li><code>grails:create-taglib</code> - Calls the <a href="../ref/Command Line/create-tag-lib.html" class="commandLine">create-tag-lib</a> command</li> |
| <li><code>grails:create-unit-test</code> - Calls the <a href="../ref/Command Line/create-unit-test.html" class="commandLine">create-unit-test</a> command</li> |
| <li><code>grails:exec</code> - Executes an arbitrary Grails command line script</li> |
| <li><code>grails:generate-all</code> - Calls the <a href="../ref/Command Line/generate-all.html" class="commandLine">generate-all</a> command</li> |
| <li><code>grails:generate-controller</code> - Calls the <a href="../ref/Command Line/generate-controller.html" class="commandLine">generate-controller</a> command</li> |
| <li><code>grails:generate-views</code> - Calls the <a href="../ref/Command Line/generate-views.html" class="commandLine">generate-views</a> command</li> |
| <li><code>grails:install-plugin</code> - Calls the <a href="../ref/Command Line/install-plugin.html" class="commandLine">install-plugin</a> command</li> |
| <li><code>grails:install-templates</code> - Calls the <a href="../ref/Command Line/install-templates.html" class="commandLine">install-templates</a> command</li> |
| <li><code>grails:list-plugins</code> - Calls the <a href="../ref/Command Line/list-plugins.html" class="commandLine">list-plugins</a> command</li> |
| <li><code>grails:package</code> - Calls the <a href="../ref/Command Line/package.html" class="commandLine">package</a> command</li> |
| <li><code>grails:run-app</code> - Calls the <a href="../ref/Command Line/run-app.html" class="commandLine">run-app</a> command</li> |
| <li><code>grails:uninstall-plugin</code> - Calls the <a href="../ref/Command Line/uninstall-plugin.html" class="commandLine">uninstall-plugin</a> command</li> |
| </ul><p class="paragraph"/>For a complete, up to date list, run <code>mvn grails:help</code><p class="paragraph"/><h4>Mavenizing an existing project</h4><p class="paragraph"/>Creating a new project is great way to start, but what if you already have one? You don't want to create a new project and then copy the contents of the old one over. The solution is to create a POM for the existing project using this Maven command (substitute the version number with the grails version of your existing project): |
| <div class="code"><pre>mvn org.grails:grails-maven-plugin:1.3.2:create-pom -DgroupId=com.mycompany</pre></div> |
| When this command has finished, you can immediately start using the standard phases, such as <code>mvn package</code>. Note that you have to specify a group ID when creating the POM.<p class="paragraph"/>You may also want to set target JDK to Java 6, see above.<p class="paragraph"/><h4>Adding Grails commands to phases</h4><p class="paragraph"/>The standard POM created for you by Grails already attaches the appropriate core Grails commands to their corresponding build phases, so "compile" goes in the "compile" phase and "war" goes in the "package" phase. That doesn't help though when you want to attach a plugin's command to a particular phase. The classic example is functional tests. How do you make sure that your functional tests (using which ever plugin you have decided on) are run during the "integration-test" phase?<p class="paragraph"/>Fear not: all things are possible. In this case, you can associate the command to a phase using an extra "execution" block: |
| <div class="code"><pre><span class="xml-tag"><plugin></span> |
| <span class="xml-tag"><groupId></span>org.grails<span class="xml-tag"></groupId></span> |
| <span class="xml-tag"><artifactId></span>grails-maven-plugin<span class="xml-tag"></artifactId></span> |
| <span class="xml-tag"><version></span>1.3.2<span class="xml-tag"></version></span> |
| <span class="xml-tag"><extensions></span>true<span class="xml-tag"></extensions></span> |
| <span class="xml-tag"><executions></span> |
| <span class="xml-tag"><execution></span> |
| <span class="xml-tag"><goals></span> |
| … |
| <span class="xml-tag"></goals></span> |
| <span class="xml-tag"></execution></span> |
| <span class="xml-comment"><!-- Add the <span class="xml-quote">"functional-tests"</span> command to the <span class="xml-quote">"integration-test"</span> phase --></span> |
| <span class="xml-tag"><execution></span> |
| <span class="xml-tag"><id></span>functional-tests<span class="xml-tag"></id></span> |
| <span class="xml-tag"><phase></span>integration-test<span class="xml-tag"></phase></span> |
| <span class="xml-tag"><goals></span> |
| <span class="xml-tag"><goal></span>exec<span class="xml-tag"></goal></span> |
| <span class="xml-tag"></goals></span> |
| <span class="xml-tag"><configuration></span> |
| <span class="xml-tag"><command></span>functional-tests<span class="xml-tag"></command></span> |
| <span class="xml-tag"></configuration></span> |
| <span class="xml-tag"></execution></span> |
| <span class="xml-tag"></executions></span> |
| <span class="xml-tag"></plugin></span></pre></div><p class="paragraph"/>This also demonstrates the <code>grails:exec</code> goal, which can be used to run any Grails command. Simply pass the name of the command as the <code>command</code> system property, and optionally specify the arguments via the <code>args</code> property: |
| <div class="code"><pre>mvn grails:exec -Dcommand=create-webtest -Dargs=Book</pre></div><p class="paragraph"/><h4>Debugging a Grails Maven Project</h4><p class="paragraph"/>Maven can be launched in debug mode using the "mvnDebug" command. To launch your Grails application in debug, simply run:<p class="paragraph"/><div class="code"><pre>mvnDebug grails:run-app</pre></div><p class="paragraph"/>The process will be suspended on startup and listening for a debugger on port 8000.<p class="paragraph"/>If you need more control of the debugger, this can be specified using the MAVEN_OPTS environment variable, and launch Maven via the default "mvn" command:<p class="paragraph"/><div class="code"><pre>MAVEN_OPTS=<span class="java-quote">"-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"</span> |
| mvn grails:run-app</pre></div><p class="paragraph"/><h4>Raising issues</h4><p class="paragraph"/>If you come across any problems with the Maven integration, please raise a JIRA issue as a sub-task of <a href="http://jira.codehaus.org/browse/GRAILS-3547" target="blank">GRAILS-3547</a>. |
| <h1><a name="5. Object Relational Mapping (GORM)">5. Object Relational Mapping (GORM)</a></h1>Domain classes are core to any business application. They hold state about business processes and hopefully also implement behavior. They are linked together through relationships, either one-to-one or one-to-many.<p class="paragraph"/>GORM is Grails' object relational mapping (ORM) implementation. Under the hood it uses Hibernate 3 (an extremely popular and flexible open source ORM solution) but because of the dynamic nature of Groovy, the fact that it supports both static and dynamic typing, and the convention of Grails there is less configuration involved in creating Grails domain classes.<p class="paragraph"/>You can also write Grails domain classes in Java. See the section on Hibernate Integration for how to write Grails domain classes in Java but still use dynamic persistent methods. Below is a preview of GORM in action:<p class="paragraph"/><div class="code"><pre>def book = Book.findByTitle(<span class="java-quote">"Groovy in Action"</span>)<p class="paragraph"/>book |
| .addToAuthors(name:<span class="java-quote">"Dierk Koenig"</span>) |
| .addToAuthors(name:<span class="java-quote">"Guillaume LaForge"</span>) |
| .save()</pre></div><p class="paragraph"/><h2><a name="5.1 Quick Start Guide">5.1 Quick Start Guide</a></h2>A domain class can be created with the <a href="../ref/Command Line/create-domain-class.html" class="commandLine">create-domain-class</a> command:<p class="paragraph"/><div class="code"><pre>grails create-domain-class Person</pre></div><p class="paragraph"/>This will create a class at the location <code>grails-app/domain/Person.groovy</code> such as the one below:<p class="paragraph"/><div class="code"><pre>class Person { |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| If you have the <code>dbCreate</code> property set to "update", "create" or "create-drop" on your <a href="../guide/single.html#3.3 The DataSource" class="guide">DataSource</a>, Grails will automatically generated/modify the database tables for you. |
| </blockquote><p class="paragraph"/>You can customize the class by adding properties:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> name |
| <span class="java-object">Integer</span> age |
| Date lastVisit |
| }</pre></div><p class="paragraph"/>Once you have a domain class try and manipulate it via the <a href="../ref/Command Line/shell.html" class="commandLine">shell</a> or <a href="../ref/Command Line/console.html" class="commandLine">console</a> by typing:<p class="paragraph"/><div class="code"><pre>grails console</pre></div><p class="paragraph"/>This loads an interactive GUI where you can type Groovy commands. |
| <h2><a name="5.1.1 Basic CRUD">5.1.1 Basic CRUD</a></h2>Try performing some basic CRUD (Create/Read/Update/Delete) operations.<p class="paragraph"/><h4>Create</h4><p class="paragraph"/>To create a domain class use the Groovy new operator, set its properties and call <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a>:<p class="paragraph"/><div class="code"><pre>def p = <span class="java-keyword">new</span> Person(name:<span class="java-quote">"Fred"</span>, age:40, lastVisit:<span class="java-keyword">new</span> Date()) |
| p.save()</pre></div><p class="paragraph"/>The <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> method will persist your class to the database using the underlying Hibernate ORM layer.<p class="paragraph"/><h4>Read</h4><p class="paragraph"/>Grails transparently adds an implicit <code>id</code> property to your domain class which you can use for retrieval:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1) |
| assert 1 == p.id</pre></div><p class="paragraph"/>This uses the <a href="../ref/Domain Classes/get.html" class="domainClasses">get</a> method that expects a database identifier to read the <code>Person</code> object back from the db. |
| You can also load an object in a read-only state by using the <a href="../ref/Domain Classes/read.html" class="domainClasses">read</a> method:<p class="paragraph"/><div class="code"><pre>def p = Person.read(1)</pre></div><p class="paragraph"/>In this case the underlying Hibernate engine will not do any dirty checking and the object will not be persisted. Note that |
| if you explicitly call the <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> method then the object is placed back into a read-write state.<p class="paragraph"/>In addition, you can also load an proxy for an instance by using the <a href="../ref/Domain Classes/load.html" class="domainClasses">load</a> method:<p class="paragraph"/><div class="code"><pre>def p = Person.load(1)</pre></div><p class="paragraph"/>This incurs no database access until a method other than getId() is called. Hibernate then initializes the proxied instance, or |
| throws an exception if no record is found for the specified id.<p class="paragraph"/><h4>Update</h4><p class="paragraph"/>To update an instance, set some properties and then simply call <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> again:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1) |
| p.name = <span class="java-quote">"Bob"</span> |
| p.save()</pre></div><p class="paragraph"/><h4>Delete</h4><p class="paragraph"/>To delete an instance use the <a href="../ref/Domain Classes/delete.html" class="domainClasses">delete</a> method:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1) |
| p.delete()</pre></div><p class="paragraph"/><h2><a name="5.2 Domain Modelling in GORM">5.2 Domain Modelling in GORM</a></h2>When building Grails applications you have to consider the problem domain you are trying to solve. For example if you were building an <a href="http://www.amazon.com/" target="blank">Amazon</a> bookstore you would be thinking about books, authors, customers and publishers to name a few.<p class="paragraph"/>These are modeled in GORM as Groovy classes so a <code>Book</code> class may have a title, a release date, an ISBN number and so on. The next few sections show how to model the domain in GORM.<p class="paragraph"/>To create a domain class you can run the <a href="../ref/Command Line/create-domain-class.html" class="commandLine">create-domain-class</a> target as follows:<p class="paragraph"/><div class="code"><pre>grails create-domain-class Book</pre></div><p class="paragraph"/>The result will be a class at <code>grails-app/domain/Book.groovy</code>:<p class="paragraph"/><div class="code"><pre>class Book { |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| If you wish to use packages you can move the Book.groovy class into a sub directory under the domain directory and add the appropriate <code>package</code> declaration as per Groovy (and Java's) packaging rules. |
| </blockquote><p class="paragraph"/>The above class will map automatically to a table in the database called <code>book</code> (the same name as the class). This behaviour is customizable through the <a href="../guide/single.html#5.5.2 Custom ORM Mapping" class="guide">ORM Domain Specific Language</a><p class="paragraph"/>Now that you have a domain class you can define its properties as Java types. For example:<p class="paragraph"/><div class="code"><pre>class Book { |
| <span class="java-object">String</span> title |
| Date releaseDate |
| <span class="java-object">String</span> ISBN |
| }</pre></div><p class="paragraph"/>Each property is mapped to a column in the database, where the convention for column names is all lower case separated by underscores. For example <code>releaseDate</code> maps onto a column <code>release_date</code>. The SQL types are auto-detected from the Java types, but can be customized via <a href="../guide/single.html#7.1 Declaring Constraints" class="guide">Constraints</a> or the <a href="../guide/single.html#5.5.2 Custom ORM Mapping" class="guide">ORM DSL</a>. |
| <h2><a name="5.2.1 Association in GORM">5.2.1 Association in GORM</a></h2>Relationships define how domain classes interact with each other. Unless specified explicitly at both ends, a relationship exists only in the direction it is defined.<p class="paragraph"/><h2><a name="5.2.1.1 One-to-one">5.2.1.1 One-to-one</a></h2>A one-to-one relationship is the simplest kind, and is defined trivially using a property of the type of another domain class. Consider this example:<p class="paragraph"/><h5>Example A</h5><p class="paragraph"/><div class="code"><pre>class Face { |
| Nose nose |
| } |
| class Nose { |
| }</pre></div><p class="paragraph"/>In this case we have unidirectional many-to-one relationship from <code>Face</code> to <code>Nose</code>. To make it a true one-to-one you should make <code>nose</code> unique:<p class="paragraph"/><div class="code"><pre>class Face { |
| Nose nose |
| <span class="java-keyword">static</span> constraints = { |
| nose unique: <span class="java-keyword">true</span> |
| } |
| } |
| class Nose { |
| }</pre></div><p class="paragraph"/>To make this relationship bidirectional define the other side as follows:<p class="paragraph"/><h5>Example B</h5><p class="paragraph"/><div class="code"><pre>class Face { |
| Nose nose |
| } |
| class Nose { |
| <span class="java-keyword">static</span> belongsTo = [face:Face] |
| }</pre></div><p class="paragraph"/>In this case we use the <code>belongsTo</code> setting to say that <code>Nose</code> "belongs to" Face. The result of this is that we can create a Face and save it and the database updates/inserts will be <em class="italic">cascaded</em> down to <code>Nose</code>:<p class="paragraph"/> |
| <div class="code"><pre><span class="java-keyword">new</span> Face(nose:<span class="java-keyword">new</span> Nose()).save()</pre></div><p class="paragraph"/>The example above will save both face and nose. Note that the inverse <em class="italic">is not</em> true and will result in an error due to a transient <code>Face</code>:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">new</span> Nose(face:<span class="java-keyword">new</span> Face()).save() // will cause an error</pre></div><p class="paragraph"/>Another important implication of <code>belongsTo</code> is that if you delete a <code>Face</code> instance the <code>Nose</code> will be deleted too:<p class="paragraph"/><div class="code"><pre>def f = Face.get(1) |
| f.delete() // both Face and Nose deleted</pre></div><p class="paragraph"/>In the previous example the foreign key associated the <code>Face</code> with the <code>Nose</code> is stored in the parent as column called <code>nose_id</code>. If you want the foreign key to be stored in the child you need a <code>hasOne</code> association:<p class="paragraph"/><h5>Example C</h5><p class="paragraph"/><div class="code"><pre>class Face { |
| <span class="java-keyword">static</span> hasOne = [nose:Nose] |
| } |
| class Nose { |
| Face face |
| }</pre></div><p class="paragraph"/>In this example you get a bidirectional one-to-one where the foreign key column is stored in the <code>nose</code> table inside a column called <code>face_id</code>.<h2><a name="5.2.1.2 One-to-many">5.2.1.2 One-to-many</a></h2>A one-to-many relationship is when one class, example <code>Author</code>, has many instances of a another class, example <code>Book</code>. With Grails you define such a relationship with the <code>hasMany</code> setting:<p class="paragraph"/><div class="code"><pre>class Author { |
| <span class="java-keyword">static</span> hasMany = [ books : Book ]<p class="paragraph"/> <span class="java-object">String</span> name |
| } |
| class Book { |
| <span class="java-object">String</span> title |
| }</pre></div><p class="paragraph"/>In this case we have a unidirectional one-to-many. Grails will, by default, map this kind of relationship with a join table.<p class="paragraph"/><blockquote class="note"> |
| The <a href="../guide/single.html#5.5.2 Custom ORM Mapping" class="guide">ORM DSL</a> allows mapping unidirectional relationships using a foreign key association instead |
| </blockquote><p class="paragraph"/>Grails will automatically inject a property of type <code>java.util.Set</code> into the domain class based on the <code>hasMany</code> setting. This can be used to iterate over the collection:<p class="paragraph"/><div class="code"><pre>def a = Author.get(1)<p class="paragraph"/>a.books.each { |
| println it.title |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| The default fetch strategy used by Grails is "lazy", which means that the collection will be lazily initialized. This can lead to the <a href="http://www.javalobby.org/java/forums/t20533.html" target="blank">n+1 problem</a> if you are not careful.<p class="paragraph"/>If you need "eager" fetching you can use the <a href="../guide/single.html#5.5.2 Custom ORM Mapping" class="guide">ORM DSL</a> or specify eager fetching as part of a <a href="../guide/single.html#5.4 Querying with GORM" class="guide">query</a> |
| </blockquote><p class="paragraph"/>The default cascading behaviour is to cascade saves and updates, but not deletes unless a <code>belongsTo</code> is also specified:<p class="paragraph"/><div class="code"><pre>class Author { |
| <span class="java-keyword">static</span> hasMany = [ books : Book ]<p class="paragraph"/> <span class="java-object">String</span> name |
| } |
| class Book { |
| <span class="java-keyword">static</span> belongsTo = [author:Author] |
| <span class="java-object">String</span> title |
| }</pre></div><p class="paragraph"/>If you have two properties of the same type on the many side of a one-to-many you have to use <code>mappedBy</code> to specify which the collection is mapped:<p class="paragraph"/><div class="code"><pre>class Airport { |
| <span class="java-keyword">static</span> hasMany = [flights:Flight] |
| <span class="java-keyword">static</span> mappedBy = [flights:<span class="java-quote">"departureAirport"</span>] |
| } |
| class Flight { |
| Airport departureAirport |
| Airport destinationAirport |
| }</pre></div><p class="paragraph"/>This is also true if you have multiple collections that map to different properties on the many side:<p class="paragraph"/><div class="code"><pre>class Airport { |
| <span class="java-keyword">static</span> hasMany = [outboundFlights:Flight, inboundFlights:Flight] |
| <span class="java-keyword">static</span> mappedBy = [outboundFlights:<span class="java-quote">"departureAirport"</span>, inboundFlights:<span class="java-quote">"destinationAirport"</span>] |
| } |
| class Flight { |
| Airport departureAirport |
| Airport destinationAirport |
| }</pre></div><p class="paragraph"/><h2><a name="5.2.1.3 Many-to-many">5.2.1.3 Many-to-many</a></h2>Grails supports many-to-many relationships by defining a <code>hasMany</code> on both sides of the relationship and having a <code>belongsTo</code> on the owned side of the relationship:<p class="paragraph"/><div class="code"><pre>class Book { |
| <span class="java-keyword">static</span> belongsTo = Author |
| <span class="java-keyword">static</span> hasMany = [authors:Author] |
| <span class="java-object">String</span> title |
| } |
| class Author { |
| <span class="java-keyword">static</span> hasMany = [books:Book] |
| <span class="java-object">String</span> name |
| }</pre></div><p class="paragraph"/>Grails maps a many-to-many using a join table at the database level. The owning side of the relationship, in this case <code>Author</code>, takes responsibility for persisting the relationship and is the only side that can cascade saves across.<p class="paragraph"/>For example this will work and cascade saves:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">new</span> Author(name:<span class="java-quote">"Stephen King"</span>) |
| .addToBooks(<span class="java-keyword">new</span> Book(title:<span class="java-quote">"The Stand"</span>)) |
| .addToBooks(<span class="java-keyword">new</span> Book(title:<span class="java-quote">"The Shining"</span>)) |
| .save()</pre></div><p class="paragraph"/>However the below will only save the <code>Book</code> and not the authors!<p class="paragraph"/><div class="code"><pre><span class="java-keyword">new</span> Book(name:<span class="java-quote">"Groovy in Action"</span>) |
| .addToAuthors(<span class="java-keyword">new</span> Author(name:<span class="java-quote">"Dierk Koenig"</span>)) |
| .addToAuthors(<span class="java-keyword">new</span> Author(name:<span class="java-quote">"Guillaume Laforge"</span>)) |
| .save()</pre></div><p class="paragraph"/>This is the expected behaviour as, just like Hibernate, only one side of a many-to-many can take responsibility for managing the relationship.<p class="paragraph"/><blockquote class="warning"> |
| Grails' <a href="../guide/single.html#16. Scaffolding" class="guide">Scaffolding</a> feature <strong class="bold">does not</strong> currently support many-to-many relationship and hence you must write the code to manage the relationship yourself |
| </blockquote><h2><a name="5.2.1.4 Basic Collection Types">5.2.1.4 Basic Collection Types</a></h2>As well as associations between different domain classes, GORM also supports mapping of basic collection types. |
| For example, the following class creates a <code>nicknames</code> association that is a <code>Set</code> of <code>String</code> instances:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-keyword">static</span> hasMany = [nicknames:<span class="java-object">String</span>] |
| }</pre></div><p class="paragraph"/>GORM will map an association like the above using a join table. You can alter various aspects of how the join table is mapped using the <code>joinTable</code> argument:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-keyword">static</span> hasMany = [nicknames:<span class="java-object">String</span>]<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| hasMany joinTable: [name: 'bunch_o_nicknames', |
| key: 'person_id', |
| column: 'nickname', |
| type: <span class="java-quote">"text"</span>] |
| } |
| }</pre></div><p class="paragraph"/>The example above will map to a table that looks like the following:<p class="paragraph"/><strong class="bold">bunch_o_nicknames Table</strong> |
| <div class="code"><pre>--------------------------------------------- |
| | person_id | nickname | |
| --------------------------------------------- |
| | 1 | Fred | |
| ---------------------------------------------</pre></div><h2><a name="5.2.2 Composition in GORM">5.2.2 Composition in GORM</a></h2>As well as <a href="../guide/single.html#5.2.1 Association in GORM" class="guide">association</a>, Grails supports the notion of composition. In this case instead of mapping classes onto separate tables a class can be "embedded" within the current table. For example:<p class="paragraph"/><div class="code"><pre>class Person { |
| Address homeAddress |
| Address workAddress |
| <span class="java-keyword">static</span> embedded = ['homeAddress', 'workAddress'] |
| } |
| class Address { |
| <span class="java-object">String</span> number |
| <span class="java-object">String</span> code |
| }</pre></div><p class="paragraph"/>The resulting mapping would looking like this:<p class="paragraph"/><img border="0" class="center" src="../img/5.2.2-composition.jpg"></img><p class="paragraph"/><blockquote class="note"> |
| If you define the <code>Address</code> class in a separate Groovy file in the <code>grails-app/domain</code> directory you will also get an <code>address</code> table. If you don't want this to happen use Groovy's ability to define multiple classes per file and include the <code>Address</code> class below the <code>Person</code> class in the <code>grails-app/domain/Person.groovy</code> file |
| </blockquote><h2><a name="5.2.3 Inheritance in GORM">5.2.3 Inheritance in GORM</a></h2>GORM supports inheritance both from abstract base classes and concrete persistent GORM entities. For example:<p class="paragraph"/><div class="code"><pre>class Content { |
| <span class="java-object">String</span> author |
| } |
| class BlogEntry <span class="java-keyword">extends</span> Content { |
| URL url |
| } |
| class Book <span class="java-keyword">extends</span> Content { |
| <span class="java-object">String</span> ISBN |
| } |
| class PodCast <span class="java-keyword">extends</span> Content { |
| <span class="java-object">byte</span>[] audioStream |
| }</pre></div><p class="paragraph"/>In the above example we have a parent <code>Content</code> class and then various child classes with more specific behaviour.<p class="paragraph"/><h4>Considerations</h4><p class="paragraph"/>At the database level Grails by default uses table-per-hierarchy mapping with a discriminator column called <code>class</code> so the parent class (<code>Content</code>) and its sub classes (<code>BlogEntry</code>, <code>Book</code> etc.), share the <strong class="bold">same</strong> table.<p class="paragraph"/>Table-per-hierarchy mapping has a down side in that you <strong class="bold">cannot</strong> have non-nullable properties with inheritance mapping. An alternative is to use table-per-subclass which can be enabled via the <a href="../guide/single.html#5.5.2 Custom ORM Mapping" class="guide">ORM DSL</a><p class="paragraph"/>However, excessive use of inheritance and table-per-subclass can result in poor query performance due to the excessive use of join queries. In general our advice is if you're going to use inheritance, don't abuse it and don't make your inheritance hierarchy too deep.<p class="paragraph"/><h4>Polymorphic Queries</h4><p class="paragraph"/>The upshot of inheritance is that you get the ability to polymorphically query. For example using the <a href="../ref/Domain Classes/list.html" class="domainClasses">list</a> method on the <code>Content</code> super class will return all sub classes of <code>Content</code>:<p class="paragraph"/><div class="code"><pre>def content = Content.list() // list all blog entries, books and pod casts |
| content = Content.findAllByAuthor('Joe Bloggs') // find all by author<p class="paragraph"/>def podCasts = PodCast.list() // list only pod casts</pre></div><h2><a name="5.2.4 Sets, Lists and Maps">5.2.4 Sets, Lists and Maps</a></h2><h4>Sets of objects</h4><p class="paragraph"/>By default when you define a relationship with GORM it is a <code>java.util.Set</code> which is an unordered collection that cannot contain duplicates. In other words when you have:<p class="paragraph"/><div class="code"><pre>class Author { |
| <span class="java-keyword">static</span> hasMany = [books:Book] |
| }</pre></div><p class="paragraph"/>The books property that GORM injects is a <code>java.util.Set</code>. The problem with this is there is no ordering when accessing the collection, which may not be what you want. To get custom ordering you can say that the set is a <code>SortedSet</code>:<p class="paragraph"/><div class="code"><pre>class Author { |
| SortedSet books |
| <span class="java-keyword">static</span> hasMany = [books:Book] |
| }</pre></div><p class="paragraph"/>In this case a <code>java.util.SortedSet</code> implementation is used which means you have to implement <code>java.lang.Comparable</code> in your Book class:<p class="paragraph"/><div class="code"><pre>class Book <span class="java-keyword">implements</span> Comparable { |
| <span class="java-object">String</span> title |
| Date releaseDate = <span class="java-keyword">new</span> Date()<p class="paragraph"/> <span class="java-object">int</span> compareTo(obj) { |
| releaseDate.compareTo(obj.releaseDate) |
| } |
| }</pre></div><p class="paragraph"/>The result of the above class is that the Book instances in the books collections of the Author class will be ordered by their release date.<p class="paragraph"/><h4>Lists of objects</h4><p class="paragraph"/>If you simply want to be able to keep objects in the order which they were added and to be able to reference them by index like an array you can define your collection type as a <code>List</code>:<p class="paragraph"/><div class="code"><pre>class Author { |
| List books |
| <span class="java-keyword">static</span> hasMany = [books:Book] |
| }</pre></div><p class="paragraph"/>In this case when you add new elements to the books collection the order is retained in a sequential list indexed from 0 so you can do:<p class="paragraph"/><div class="code"><pre>author.books[0] // get the first book</pre></div><p class="paragraph"/>The way this works at the database level is Hibernate creates a <code>books_idx</code> column where it saves the index of the elements in the collection in order to retain this order at the db level.<p class="paragraph"/>When using a <code>List</code>, elements must be added to the collection before being saved, otherwise Hibernate will throw an exception (<code>org.hibernate.HibernateException</code>: null index column for collection):<p class="paragraph"/><div class="code"><pre>// This won't work! |
| def book = <span class="java-keyword">new</span> Book(title: 'The Shining') |
| book.save() |
| author.addToBooks(book)<p class="paragraph"/>// Do it <span class="java-keyword">this</span> way instead. |
| def book = <span class="java-keyword">new</span> Book(title: 'Misery') |
| author.addToBooks(book) |
| author.save()</pre></div><p class="paragraph"/><h4>Maps of Objects</h4><p class="paragraph"/>If you want a simple map of string/value pairs GORM can map this with the following:<p class="paragraph"/><div class="code"><pre>class Author { |
| Map books // map of ISBN:book names |
| }<p class="paragraph"/>def a = <span class="java-keyword">new</span> Author() |
| a.books = [<span class="java-quote">"1590597583"</span>:<span class="java-quote">"Grails Book"</span>] |
| a.save()</pre></div> |
| In this case the key and value of the map MUST be strings.<p class="paragraph"/>If you want a Map of objects then you can do this:<p class="paragraph"/><div class="code"><pre>class Book { |
| Map authors |
| <span class="java-keyword">static</span> hasMany = [authors:Author] |
| }<p class="paragraph"/>def a = <span class="java-keyword">new</span> Author(name:<span class="java-quote">"Stephen King"</span>)<p class="paragraph"/>def book = <span class="java-keyword">new</span> Book() |
| book.authors = [stephen:a] |
| book.save()</pre></div><p class="paragraph"/>The static <code>hasMany</code> property defines the type of the elements within the Map. The keys for the map <strong class="bold">must</strong> be strings.<p class="paragraph"/><h4>A Note on Collection Types and Performance</h4><p class="paragraph"/>The Java <code>Set</code> type is a collection that doesn't allow duplicates. In order to ensure uniqueness when adding an entry to a <code>Set</code> association Hibernate has to load the entire associations from the database. If you have a large numbers of entries in the association this can be costly in terms of performance.<p class="paragraph"/>The same behavior is required for <code>List</code> types, since Hibernate needs to load the entire association in-order to maintain order. Therefore it is recommended that if you anticipate a large numbers of records in the association that you make the association bidirectional so that the link can be created on the inverse side. For example consider the following code:<p class="paragraph"/><div class="code"><pre>def book = <span class="java-keyword">new</span> Book(title:<span class="java-quote">"New Grails Book"</span>) |
| def author = Author.get(1) |
| book.author = author |
| book.save()</pre></div><p class="paragraph"/>In this example the association link is being created by the child (Book) and hence it is not necessary to manipulate the collection directly resulting in fewer queries and more efficient code. Given an <code>Author</code> with a large number of associated <code>Book</code> instances if you were to write code like the following you would see an impact on performance:<p class="paragraph"/><div class="code"><pre>def book = <span class="java-keyword">new</span> Book(title:<span class="java-quote">"New Grails Book"</span>) |
| def author = Author.get(1) |
| author.addToBooks(book) |
| author.save()</pre></div><h2><a name="5.3 Persistence Basics">5.3 Persistence Basics</a></h2>A key thing to remember about Grails is that under the surface Grails is using <a href="http://www.hibernate.org/" target="blank">Hibernate</a> for persistence. If you are coming from a background of using <a href="http://wiki.rubyonrails.org/rails/pages/ActiveRecord" target="blank">ActiveRecord</a> or <a href="http://ibatis.apache.org/," target="blank">iBatis</a> Hibernate's "session" model may feel a little strange.<p class="paragraph"/>Essentially, Grails automatically binds a Hibernate session to the currently executing request. This allows you to use the <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> and <a href="../ref/Domain Classes/delete.html" class="domainClasses">delete</a> methods as well as other GORM methods transparently.<p class="paragraph"/><p class="paragraph"/><h2><a name="5.3.1 Saving and Updating">5.3.1 Saving and Updating</a></h2>An example of using the <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> method can be seen below:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1) |
| p.save()</pre></div><p class="paragraph"/>A major difference with Hibernate is when you call <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> it does not necessarily perform any SQL operations <strong class="bold">at that point</strong>. Hibernate typically batches up SQL statements and executes them at the end. This is typically done for you automatically by Grails, which manages your Hibernate session.<p class="paragraph"/>There are occasions, however, when you may want to control when those statements are executed or, in Hibernate terminology, when the session is "flushed". To do so you can use the flush argument to the save method:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1) |
| p.save(flush:<span class="java-keyword">true</span>)</pre></div><p class="paragraph"/>Note that in this case all pending SQL statements including previous saves will be synchronized with the db. This also allows you to catch any exceptions thrown, which is typically useful in highly concurrent scenarios involving <a href="../guide/single.html#5.3.5 Pessimistic and Optimistic Locking" class="guide">optimistic locking</a>:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1) |
| <span class="java-keyword">try</span> { |
| p.save(flush:<span class="java-keyword">true</span>) |
| } |
| <span class="java-keyword">catch</span>(Exception e) { |
| // deal with exception |
| }</pre></div><p class="paragraph"/>You can find out more about the subtleties of saving data in <a href="http://blog.springsource.com/2010/06/23/gorm-gotchas-part-1/" target="blank">this article</a> - a must read! |
| <h2><a name="5.3.2 Deleting Objects">5.3.2 Deleting Objects</a></h2>An example of the <a href="../ref/Domain Classes/delete.html" class="domainClasses">delete</a> method can be seen below:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1) |
| p.delete()</pre></div><p class="paragraph"/>By default Grails will use transactional write behind to perform the delete, if you want to perform the delete in place then you can use the <code>flush</code> argument:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1) |
| p.delete(flush:<span class="java-keyword">true</span>)</pre></div><p class="paragraph"/>Using the <code>flush</code> argument will also allow you to catch any errors that may potentially occur during a delete. A common error that may occur is if you violate a database constraint, although this is normally down to a programming or schema error. The following example shows how to catch a <code>DataIntegrityViolationException</code> that is thrown when you violate the database constraints:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1)<p class="paragraph"/><span class="java-keyword">try</span> { |
| p.delete(flush:<span class="java-keyword">true</span>) |
| } |
| <span class="java-keyword">catch</span>(org.springframework.dao.DataIntegrityViolationException e) { |
| flash.message = <span class="java-quote">"Could not delete person ${p.name}"</span> |
| redirect(action:<span class="java-quote">"show"</span>, id:p.id) |
| }</pre></div><p class="paragraph"/>Note that Grails does not supply a <code>deleteAll</code> method as deleting data is discouraged and can often be avoided through boolean flags/logic.<p class="paragraph"/>If you really need to batch delete data you can use the <a href="../ref/Domain Classes/executeUpdate.html" class="domainClasses">executeUpdate</a> method to do batch DML statements:<p class="paragraph"/><div class="code"><pre>Customer.executeUpdate(<span class="java-quote">"delete Customer c where c.name = :oldName"</span>, [oldName:<span class="java-quote">"Fred"</span>])</pre></div><p class="paragraph"/><h2><a name="5.3.3 Understanding Cascading Updates and Deletes">5.3.3 Understanding Cascading Updates and Deletes</a></h2>It is critical that you understand how cascading updates and deletes work when using GORM. The key part to remember is the <code>belongsTo</code> setting which controls which class "owns" a relationship.<p class="paragraph"/>Whether it is a one-to-one, one-to-many or many-to-many if you define <code>belongsTo</code> updates and deletes will cascade from the owning class to its possessions (the other side of the relationship).<p class="paragraph"/>If you <em class="italic">do not</em> define <code>belongsTo</code> then no cascades will happen and you will have to manually save each object.<p class="paragraph"/>Here is an example:<p class="paragraph"/><div class="code"><pre>class Airport { |
| <span class="java-object">String</span> name |
| <span class="java-keyword">static</span> hasMany = [flights:Flight] |
| } |
| class Flight { |
| <span class="java-object">String</span> number |
| <span class="java-keyword">static</span> belongsTo = [airport:Airport] |
| }</pre></div><p class="paragraph"/>If I now create an <code>Airport</code> and add some <code>Flight</code>s to it I can save the <code>Airport</code> and have the updates cascaded down to each flight, hence saving the whole object graph:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">new</span> Airport(name:<span class="java-quote">"Gatwick"</span>) |
| .addToFlights(<span class="java-keyword">new</span> Flight(number:<span class="java-quote">"BA3430"</span>)) |
| .addToFlights(<span class="java-keyword">new</span> Flight(number:<span class="java-quote">"EZ0938"</span>)) |
| .save()</pre></div><p class="paragraph"/>Conversely if I later delete the <code>Airport</code> all <code>Flight</code>s associated with it will also be deleted:<p class="paragraph"/><div class="code"><pre>def airport = Airport.findByName(<span class="java-quote">"Gatwick"</span>) |
| airport.delete()</pre></div><p class="paragraph"/>However, if I were to remove <code>belongsTo</code> then the above cascading deletion code <strong class="bold">would not work</strong>. To understand this better take a look at the summaries below that describe the default behaviour of GORM with regards to specific associations. Also read <a href="http://blog.springsource.com/2010/07/02/gorm-gotchas-part-2/" target="blank">part 2</a> of the GORM Gotchas series of articles to get a deeper understanding of relationships and cascading.<p class="paragraph"/><h5>Bidirectional one-to-many with belongsTo</h5><p class="paragraph"/><div class="code"><pre>class A { <span class="java-keyword">static</span> hasMany = [bees:B] } |
| class B { <span class="java-keyword">static</span> belongsTo = [a:A] }</pre></div><p class="paragraph"/>In the case of a bidirectional one-to-many where the many side defines a <code>belongsTo</code> then the cascade strategy is set to "ALL" for the one side and "NONE" for the many side.<p class="paragraph"/><h5>Unidirectional one-to-many</h5><p class="paragraph"/><div class="code"><pre>class A { <span class="java-keyword">static</span> hasMany = [bees:B] } |
| class B { }</pre></div><p class="paragraph"/>In the case of a unidirectional one-to-many where the many side defines no belongsTo then the cascade strategy is set to "SAVE-UPDATE".<p class="paragraph"/><h5>Bidirectional one-to-many no belongsTo</h5><p class="paragraph"/><div class="code"><pre>class A { <span class="java-keyword">static</span> hasMany = [bees:B] } |
| class B { A a }</pre></div><p class="paragraph"/>In the case of a bidirectional one-to-many where the many side does not define a <code>belongsTo</code> then the cascade strategy is set to "SAVE-UPDATE" for the one side and "NONE" for the many side.<p class="paragraph"/><h5>Unidirectional One-to-one with belongsTo</h5><p class="paragraph"/><div class="code"><pre>class A { } |
| class B { <span class="java-keyword">static</span> belongsTo = [a:A] }</pre></div><p class="paragraph"/>In the case of a unidirectional one-to-one association that defines a <code>belongsTo</code> then the cascade strategy is set to "ALL" for the owning side of the relationship (A->B) and "NONE" from the side that defines the <code>belongsTo</code> (B->A)<p class="paragraph"/>Note that if you need further control over cascading behaviour, you can use the <a href="../guide/single.html#5.5.2 Custom ORM Mapping" class="guide">ORM DSL</a>. |
| <h2><a name="5.3.4 Eager and Lazy Fetching">5.3.4 Eager and Lazy Fetching</a></h2>Associations in GORM are by default lazy. This is best explained by example:<p class="paragraph"/><div class="code"><pre>class Airport { |
| <span class="java-object">String</span> name |
| <span class="java-keyword">static</span> hasMany = [flights:Flight] |
| } |
| class Flight { |
| <span class="java-object">String</span> number |
| Location destination |
| <span class="java-keyword">static</span> belongsTo = [airport:Airport] |
| } |
| class Location { |
| <span class="java-object">String</span> city |
| <span class="java-object">String</span> country |
| }</pre></div><p class="paragraph"/>Given the above domain classes and the following code:<p class="paragraph"/><div class="code"><pre>def airport = Airport.findByName(<span class="java-quote">"Gatwick"</span>) |
| airport.flights.each { |
| println it.destination.city |
| }</pre></div><p class="paragraph"/>GORM will execute a single SQL query to fetch the <code>Airport</code> instance, another to get its flights, and then 1 extra query for <em class="italic">each iteration</em> over the <code>flights</code> association to get the current flight's destination. In other words you get N+1 queries (if you exclude the original one to get the airport).<p class="paragraph"/><h3>Configuring Eager Fetching</h3><p class="paragraph"/>An alternative approach that avoids the N+1 queries is to use eager fetching, which can be specified as follows:<p class="paragraph"/><div class="code"><pre>class Airport { |
| <span class="java-object">String</span> name |
| <span class="java-keyword">static</span> hasMany = [flights:Flight] |
| <span class="java-keyword">static</span> mapping = { |
| flights lazy: <span class="java-keyword">false</span> |
| } |
| }</pre></div><p class="paragraph"/>In this case the <code>flights</code> association will be loaded at the same time as its <code>Airport</code> instance, although a second query will be executed to fetch the collection. You can also use <code>fetch: 'join'</code> instead of <code>lazy: false</code> , in which case GORM will only execute a single query to get the airports and their flights. This works well for single-ended associations, but you need to be careful with one-to-manys. Queries will work as you'd expect right up to the moment you add a limit to the number of results you want. At that point, you will likely end up with fewer results than you were expecting. The reason for this is quite technical but ultimately the problem arises from GORM using a left outer join.<p class="paragraph"/>So, the recommendation is currently to use <code>fetch: 'join'</code> for single-ended associations and <code>lazy: false</code> for one-to-manys.<p class="paragraph"/>Be careful how and where you use eager loading because you could load your entire database into memory with too many eager associations. You can find more information on the mapping options in the <a href="../guide/single.html#5.5.2.8 Eager and Lazy Fetching" class="guide">section on the ORM DSL</a>.<p class="paragraph"/><h3>Using Batch Fetching</h3><p class="paragraph"/>Although eager fetching is appropriate for some cases, it is not always desirable. If you made everything eager you could quite possibly load your entire database into memory resulting in performance and memory problems. An alternative to eager fetching is to use batch fetching. Essentially, you can configure Hibernate to lazily fetch results in "batches". For example:<p class="paragraph"/><div class="code"><pre>class Airport { |
| <span class="java-object">String</span> name |
| <span class="java-keyword">static</span> hasMany = [flights:Flight] |
| <span class="java-keyword">static</span> mapping = { |
| flights batchSize:10 |
| } |
| }</pre></div><p class="paragraph"/>In this case, due to the <code>batchSize</code> argument, when you iterate over the <code>flights</code> association, Hibernate will fetch results in batches of 10. For example if you had an <code>Airport</code> that had 30 flights, if you didn't configure batch fetching you would get 1 query to fetch the <code>Airport</code> and then <code>30</code> queries to fetch each flight. With batch fetching you get 1 query to fetch the <code>Airport</code> and 3 queries to fetch each <code>Flight</code> in batches of 10. In other words, batch fetching is an optimization of the lazy fetching strategy. Batch fetching can also be configured at the class level as follows:<p class="paragraph"/><div class="code"><pre>class Flight { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| batchSize 10 |
| } |
| }</pre></div><p class="paragraph"/>Check out <a href="http://blog.springsource.com/2010/07/28/gorm-gotchas-part-3/" target="blank">part 3</a> of the GORM Gotchas series for more in-depth coverage of this tricky topic. |
| <h2><a name="5.3.5 Pessimistic and Optimistic Locking">5.3.5 Pessimistic and Optimistic Locking</a></h2><h4>Optimistic Locking</h4><p class="paragraph"/>By default GORM classes are configured for optimistic locking. Optimistic locking essentially is a feature of Hibernate which involves storing a version number in a special <code>version</code> column in the database.<p class="paragraph"/>The <code>version</code> column gets read into a <code>version</code> property that contains the current versioned state of persistent instance which you can access:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10)<p class="paragraph"/>println airport.version</pre></div><p class="paragraph"/>When you perform updates Hibernate will automatically check the version property against the version column in the database and if they differ will throw a <a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/StaleObjectStateException.html" class="api">StaleObjectException</a> and the transaction will be rolled back.<p class="paragraph"/>This is useful as it allows a certain level of atomicity without resorting to pessimistic locking that has an inherit performance penalty. The downside is that you have to deal with this exception if you have highly concurrent writes. This requires flushing the session:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10)<p class="paragraph"/><span class="java-keyword">try</span> { |
| airport.name = <span class="java-quote">"Heathrow"</span> |
| airport.save(flush:<span class="java-keyword">true</span>) |
| } |
| <span class="java-keyword">catch</span>(org.springframework.dao.OptimisticLockingFailureException e) { |
| // deal with exception |
| }</pre></div><p class="paragraph"/>The way you deal with the exception depends on the application. You could attempt a programmatic merge of the data or go back to the user and ask them to resolve the conflict.<p class="paragraph"/>Alternatively, if it becomes a problem you can resort to pessimistic locking.<p class="paragraph"/><h4>Pessimistic Locking</h4><p class="paragraph"/>Pessimistic locking is equivalent to doing a SQL "SELECT * FOR UPDATE" statement and locking a row in the database. This has the implication that other read operations will be blocking until the lock is released.<p class="paragraph"/>In Grails pessimistic locking is performed on an existing instance via the <a href="../ref/Domain Classes/lock.html" class="domainClasses">lock</a> method:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10) |
| airport.lock() // lock <span class="java-keyword">for</span> update |
| airport.name = <span class="java-quote">"Heathrow"</span> |
| airport.save()</pre></div><p class="paragraph"/>Grails will automatically deal with releasing the lock for you once the transaction has been committed. However, in the above case what we are doing is "upgrading" from a regular SELECT to a SELECT..FOR UPDATE and another thread could still have updated the record in between the call to get() and the call to lock().<p class="paragraph"/>To get around this problem you can use the static <a href="../ref/Domain Classes/lock.html" class="domainClasses">lock</a> method that takes an id just like <a href="../ref/Domain Classes/get.html" class="domainClasses">get</a>:<p class="paragraph"/><div class="code"><pre>def airport = Airport.lock(10) // lock <span class="java-keyword">for</span> update |
| airport.name = <span class="java-quote">"Heathrow"</span> |
| airport.save()</pre></div><p class="paragraph"/>In this case only SELECT..FOR UPDATE is issued.<p class="paragraph"/><blockquote class="warning"> |
| Though Grails, through Hibernate, supports pessimistic locking, the embedded HSQLDB shipped with Grails which is used as the default in-memory database <strong class="bold">does not</strong>. If you need to test pessimistic locking you will need to do so against a database that does have support such as MySQL. |
| </blockquote><p class="paragraph"/>As well as the <a href="../ref/Domain Classes/lock.html" class="domainClasses">lock</a> method you can also obtain a pessimistic locking using queries. For example using a dynamic finder:<p class="paragraph"/><div class="code"><pre>def airport = Airport.findByName(<span class="java-quote">"Heathrow"</span>, [lock:<span class="java-keyword">true</span>])</pre></div><p class="paragraph"/>Or using criteria:<p class="paragraph"/><div class="code"><pre>def airport = Airport.createCriteria().get { |
| eq('name', 'Heathrow') |
| lock <span class="java-keyword">true</span> |
| }</pre></div><p class="paragraph"/><h2><a name="5.3.6 Modification Checking">5.3.6 Modification Checking</a></h2>Once you have loaded and possibly modified a persistent domain class instance, it isn't straightforward to retrieve the original values. If you try to reload the instance using <a href="../ref/Domain Classes/get.html" class="domainClasses">get</a> Hibernate will return the current modified instance from its Session cache. Reloading using another query would trigger a flush which could cause problems if your data isn't ready to be flushed yet. So GORM provides some methods to retrieve the original values that Hibernate caches when it loads the instance (which it uses for dirty checking).<p class="paragraph"/><h4>isDirty</h4><p class="paragraph"/>You can use the <a href="../ref/Domain Classes/isDirty.html" class="domainClasses">isDirty</a> method to check if any field has been modified:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10) |
| assert !airport.isDirty()<p class="paragraph"/>airport.properties = params |
| <span class="java-keyword">if</span> (airport.isDirty()) { |
| // <span class="java-keyword">do</span> something based on changed state |
| }</pre></div><p class="paragraph"/>You can also check if individual fields have been modified:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10) |
| assert !airport.isDirty()<p class="paragraph"/>airport.properties = params |
| <span class="java-keyword">if</span> (airport.isDirty('name')) { |
| // <span class="java-keyword">do</span> something based on changed name |
| }</pre></div><p class="paragraph"/><h4>getDirtyPropertyNames</h4><p class="paragraph"/>You can use the <a href="../ref/Domain Classes/getDirtyPropertyNames.html" class="domainClasses">getDirtyPropertyNames</a> method to retrieve the names of modified fields; this may be empty but will not be null:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10) |
| assert !airport.isDirty()<p class="paragraph"/>airport.properties = params |
| def modifiedFieldNames = airport.getDirtyPropertyNames() |
| <span class="java-keyword">for</span> (fieldName in modifiedFieldNames) { |
| // <span class="java-keyword">do</span> something based on changed value |
| }</pre></div><p class="paragraph"/><h4>getPersistentValue</h4><p class="paragraph"/>You can use the <a href="../ref/Domain Classes/getPersistentValue.html" class="domainClasses">getPersistentValue</a> method to retrieve the value of a modified field:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10) |
| assert !airport.isDirty()<p class="paragraph"/>airport.properties = params |
| def modifiedFieldNames = airport.getDirtyPropertyNames() |
| <span class="java-keyword">for</span> (fieldName in modifiedFieldNames) { |
| def currentValue = airport.<span class="java-quote">"$fieldName"</span> |
| def originalValue = airport.getPersistentValue(fieldName) |
| <span class="java-keyword">if</span> (currentValue != originalValue) { |
| // <span class="java-keyword">do</span> something based on changed value |
| } |
| }</pre></div><p class="paragraph"/><h2><a name="5.4 Querying with GORM">5.4 Querying with GORM</a></h2>GORM supports a number of powerful ways to query from dynamic finders, to criteria to Hibernate's object oriented query language HQL.<p class="paragraph"/>Groovy's ability to manipulate collections via <a href="http://groovy.codehaus.org/GPath" target="blank">GPath</a> and methods like sort, findAll and so on combined with GORM results in a powerful combination.<p class="paragraph"/>However, let's start with the basics.<p class="paragraph"/><h4>Listing instances</h4><p class="paragraph"/>If you simply need to obtain all the instances of a given class you can use the <a href="../ref/Domain Classes/list.html" class="domainClasses">list</a> method:<p class="paragraph"/><div class="code"><pre>def books = Book.list()</pre></div><p class="paragraph"/>The <a href="../ref/Domain Classes/list.html" class="domainClasses">list</a> method supports arguments to perform pagination:<p class="paragraph"/><div class="code"><pre>def books = Book.list(offset:10, max:20)</pre></div><p class="paragraph"/>as well as sorting:<p class="paragraph"/><div class="code"><pre>def books = Book.list(sort:<span class="java-quote">"title"</span>, order:<span class="java-quote">"asc"</span>)</pre></div><p class="paragraph"/>Here, the <code>sort</code> argument is the name of the domain class property that you wish to sort on, and the <code>order</code> argument is either <code>asc</code> for <strong class="bold">asc</strong>ending or <code>desc</code> for <strong class="bold">desc</strong>ending.<p class="paragraph"/><h4>Retrieval by Database Identifier</h4><p class="paragraph"/>The second basic form of retrieval is by database identifier using the <a href="../ref/Domain Classes/get.html" class="domainClasses">get</a> method:<p class="paragraph"/><div class="code"><pre>def book = Book.get(23)</pre></div><p class="paragraph"/>You can also obtain a list of instances for a set of identifiers using <a href="../ref/Domain Classes/getAll.html" class="domainClasses">getAll</a>:<p class="paragraph"/><div class="code"><pre>def books = Book.getAll(23, 93, 81)</pre></div> |
| <h2><a name="5.4.1 Dynamic Finders">5.4.1 Dynamic Finders</a></h2>GORM supports the concept of <strong class="bold">dynamic finders</strong>. A dynamic finder looks like a static method invocation, but the methods themselves don't actually exist in any form at the code level.<p class="paragraph"/>Instead, a method is auto-magically generated using code synthesis at runtime, based on the properties of a given class. Take for example the <code>Book</code> class:<p class="paragraph"/><div class="code"><pre>class Book { |
| <span class="java-object">String</span> title |
| Date releaseDate |
| Author author |
| } |
| class Author { |
| <span class="java-object">String</span> name |
| }</pre></div><p class="paragraph"/>The <code>Book</code> class has properties such as <code>title</code>, <code>releaseDate</code> and <code>author</code>. These can be used by the <a href="../ref/Domain Classes/findBy.html" class="domainClasses">findBy</a> and <a href="../ref/Domain Classes/findAllBy.html" class="domainClasses">findAllBy</a> methods in the form of "method expressions":<p class="paragraph"/><div class="code"><pre>def book = Book.findByTitle(<span class="java-quote">"The Stand"</span>)<p class="paragraph"/>book = Book.findByTitleLike(<span class="java-quote">"Harry Pot%"</span>)<p class="paragraph"/>book = Book.findByReleaseDateBetween( firstDate, secondDate )<p class="paragraph"/>book = Book.findByReleaseDateGreaterThan( someDate )<p class="paragraph"/>book = Book.findByTitleLikeOrReleaseDateLessThan( <span class="java-quote">"%Something%"</span>, someDate )</pre></div><p class="paragraph"/><h4>Method Expressions</h4><p class="paragraph"/>A method expression in GORM is made up of the prefix such as <a href="../ref/Domain Classes/findBy.html" class="domainClasses">findBy</a> followed by an expression that combines one or more properties. The basic form is:<p class="paragraph"/><div class="code"><pre>Book.findBy([Property][Comparator][<span class="java-object">Boolean</span> Operator])?[Property][Comparator]</pre></div><p class="paragraph"/>The tokens marked with a '?' are optional. Each comparator changes the nature of the query. For example:<p class="paragraph"/><div class="code"><pre>def book = Book.findByTitle(<span class="java-quote">"The Stand"</span>)<p class="paragraph"/>book = Book.findByTitleLike(<span class="java-quote">"Harry Pot%"</span>)</pre></div><p class="paragraph"/>In the above example the first query is equivalent to equality whilst the latter, due to the <code>Like</code> comparator, is equivalent to a SQL <code>like</code> expression.<p class="paragraph"/>The possible comparators include: |
| <ul class="star"> |
| <li><code>InList</code> - In the list of given values</li> |
| <li><code>LessThan</code> - less than the given value</li> |
| <li><code>LessThanEquals</code> - less than or equal a give value</li> |
| <li><code>GreaterThan</code> - greater than a given value</li> |
| <li><code>GreaterThanEquals</code> - greater than or equal a given value</li> |
| <li><code>Like</code> - Equivalent to a SQL like expression</li> |
| <li><code>Ilike</code> - Similar to a <code>Like</code>, except case insensitive</li> |
| <li><code>NotEqual</code> - Negates equality</li> |
| <li><code>Between</code> - Between two values (requires two arguments)</li> |
| <li><code>IsNotNull</code> - Not a null value (doesn't require an argument)</li> |
| <li><code>IsNull</code> - Is a null value (doesn't require an argument)</li> |
| </ul><p class="paragraph"/>Notice that the last 3 require different numbers of method arguments compared to the rest, as demonstrated in the following example:<p class="paragraph"/><div class="code"><pre>def now = <span class="java-keyword">new</span> Date() |
| def lastWeek = now - 7 |
| def book = Book.findByReleaseDateBetween( lastWeek, now )<p class="paragraph"/>books = Book.findAllByReleaseDateIsNull() |
| books = Book.findAllByReleaseDateIsNotNull()</pre></div><p class="paragraph"/><h4>Boolean logic (AND/OR) </h4><p class="paragraph"/>Method expressions can also use a boolean operator to combine two criteria:<p class="paragraph"/><div class="code"><pre>def books = |
| Book.findAllByTitleLikeAndReleaseDateGreaterThan(<span class="java-quote">"%Java%"</span>, <span class="java-keyword">new</span> Date()-30)</pre></div><p class="paragraph"/>In this case we're using <code>And</code> in the middle of the query to make sure both conditions are satisfied, but you could equally use <code>Or</code>:<p class="paragraph"/><div class="code"><pre>def books = |
| Book.findAllByTitleLikeOrReleaseDateGreaterThan(<span class="java-quote">"%Java%"</span>, <span class="java-keyword">new</span> Date()-30)</pre></div><p class="paragraph"/>At the moment, you can only use dynamic finders with a maximum of two criteria, i.e. the method name can only have one boolean operator. If you need to use more, you should consider using either <a href="../guide/single.html#5.4.2 Criteria" class="guide">Criteria</a> or the <a href="../guide/single.html#5.4.3 Hibernate Query Language (HQL)" class="guide">HQL</a>.<p class="paragraph"/><h4>Querying Associations</h4><p class="paragraph"/>Associations can also be used within queries:<p class="paragraph"/><div class="code"><pre>def author = Author.findByName(<span class="java-quote">"Stephen King"</span>)<p class="paragraph"/>def books = author ? Book.findAllByAuthor(author) : []</pre></div><p class="paragraph"/>In this case if the <code>Author</code> instance is not null we use it in a query to obtain all the <code>Book</code> instances for the given <code>Author</code>.<p class="paragraph"/><h4>Pagination & Sorting</h4><p class="paragraph"/>The same pagination and sorting parameters available on the <a href="../ref/Domain Classes/list.html" class="domainClasses">list</a> method can also be used with dynamic finders by supplying a map as the final parameter:<p class="paragraph"/><div class="code"><pre>def books = |
| Book.findAllByTitleLike(<span class="java-quote">"Harry Pot%"</span>, [max:3, |
| offset:2, |
| sort:<span class="java-quote">"title"</span>, |
| order:<span class="java-quote">"desc"</span>])</pre></div> |
| <h2><a name="5.4.2 Criteria">5.4.2 Criteria</a></h2>Criteria is a type safe, advanced way to query that uses a Groovy builder to construct potentially complex queries. It is a much better alternative to using StringBuffer.<p class="paragraph"/>Criteria can be used either via the <a href="../ref/Domain Classes/createCriteria.html" class="domainClasses">createCriteria</a> or <a href="../ref/Domain Classes/withCriteria.html" class="domainClasses">withCriteria</a> methods. The builder uses Hibernate's Criteria API, the nodes on this builder map the static methods found in the <a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/criterion/Restrictions.html" class="api">Restrictions</a> class of the Hibernate Criteria API. Example Usage:<p class="paragraph"/><div class="code"><pre>def c = Account.createCriteria() |
| def results = c { |
| between(<span class="java-quote">"balance"</span>, 500, 1000) |
| eq(<span class="java-quote">"branch"</span>, <span class="java-quote">"London"</span>) |
| or { |
| like(<span class="java-quote">"holderFirstName"</span>, <span class="java-quote">"Fred%"</span>) |
| like(<span class="java-quote">"holderFirstName"</span>, <span class="java-quote">"Barney%"</span>) |
| } |
| maxResults(10) |
| order(<span class="java-quote">"holderLastName"</span>, <span class="java-quote">"desc"</span>) |
| }</pre></div><p class="paragraph"/>This criteria will select up to 10 <code>Account</code> objects matching the following criteria: |
| <ul class="star"> |
| <li><code>balance</code> is between 500 and 1000</li> |
| <li><code>branch</code> is 'London'</li> |
| <li><code>holderFirstName</code> starts with 'Fred' or 'Barney'</li> |
| </ul><p class="paragraph"/>The results will be sorted in descending ordery by <code>holderLastName</code>.<p class="paragraph"/><h4>Conjunctions and Disjunctions</h4><p class="paragraph"/>As demonstrated in the previous example you can group criteria in a logical OR using a <code>or { }</code> block:<p class="paragraph"/><div class="code"><pre>or { |
| between(<span class="java-quote">"balance"</span>, 500, 1000) |
| eq(<span class="java-quote">"branch"</span>, <span class="java-quote">"London"</span>) |
| }</pre></div><p class="paragraph"/>This also works with logical AND:<p class="paragraph"/><div class="code"><pre>and { |
| between(<span class="java-quote">"balance"</span>, 500, 1000) |
| eq(<span class="java-quote">"branch"</span>, <span class="java-quote">"London"</span>) |
| }</pre></div><p class="paragraph"/>And you can also negate using logical NOT:<p class="paragraph"/><div class="code"><pre>not { |
| between(<span class="java-quote">"balance"</span>, 500, 1000) |
| eq(<span class="java-quote">"branch"</span>, <span class="java-quote">"London"</span>) |
| }</pre></div><p class="paragraph"/>All top level conditions are implied to be AND'd together.<p class="paragraph"/><h4>Querying Associations</h4><p class="paragraph"/>Associations can be queried by having a node that matches the property name. For example say the <code>Account</code> class had many <code>Transaction</code> objects:<p class="paragraph"/><div class="code"><pre>class Account { |
| … |
| <span class="java-keyword">static</span> hasMany = [transactions:Transaction] |
| … |
| }</pre></div><p class="paragraph"/> |
| We can query this association by using the property name <code>transaction</code> as a builder node:<p class="paragraph"/><div class="code"><pre>def c = Account.createCriteria() |
| def now = <span class="java-keyword">new</span> Date() |
| def results = c.list { |
| transactions { |
| between('date',now-10, now) |
| } |
| }</pre></div><p class="paragraph"/> |
| The above code will find all the <code>Account</code> instances that have performed <code>transactions</code> within the last 10 days. |
| You can also nest such association queries within logical blocks:<p class="paragraph"/><div class="code"><pre>def c = Account.createCriteria() |
| def now = <span class="java-keyword">new</span> Date() |
| def results = c.list { |
| or { |
| between('created',now-10,now) |
| transactions { |
| between('date',now-10, now) |
| } |
| } |
| }</pre></div><p class="paragraph"/> |
| Here we find all accounts that have either performed transactions in the last 10 days OR have been recently created in the last 10 days.<p class="paragraph"/> |
| <h4>Querying with Projections</h4><p class="paragraph"/>Projections may be used to customise the results. To use projections you need to define a "projections" node within the criteria builder tree. There are equivalent methods within the projections node to the methods found in the Hibernate <a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/criterion/Projections.html" class="api">Projections</a> class:<p class="paragraph"/><div class="code"><pre>def c = Account.createCriteria()<p class="paragraph"/>def numberOfBranches = c.get { |
| projections { |
| countDistinct('branch') |
| } |
| }</pre></div><p class="paragraph"/><h4>Using SQL Restrictions</h4><p class="paragraph"/>You can access Hibernate's SQL Restrictions capabilities.<p class="paragraph"/><div class="code"><pre>def c = Person.createCriteria()<p class="paragraph"/>def peopleWithShortFirstNames = c.list { |
| sqlRestriction <span class="java-quote">"char_length( first_name ) <= 4"</span> |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| Note that the parameter there is SQL. The <code>first_name</code> attribute referenced in the example relates to the persistence model, |
| not the object model. The <code>Person</code> class may have a property named <code>firstName</code> which is mapped to a column in the database |
| named <code>first_name</code>.<p class="paragraph"/>Also note that the SQL used here is not necessarily portable across databases. |
| </blockquote><p class="paragraph"/><h4>Using Scrollable Results</h4><p class="paragraph"/>You can use Hibernate's <a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/ScrollableResults.html" class="api">ScrollableResults</a> feature by calling the scroll method:<p class="paragraph"/><div class="code"><pre>def results = crit.scroll { |
| maxResults(10) |
| } |
| def f = results.first() |
| def l = results.last() |
| def n = results.next() |
| def p = results.previous()<p class="paragraph"/>def <span class="java-keyword">future</span> = results.scroll(10) |
| def accountNumber = results.getLong('number')</pre></div><p class="paragraph"/> |
| To quote the documentation of Hibernate ScrollableResults:<p class="paragraph"/><blockquote class="quote"> |
| A result iterator that allows moving around within the results by arbitrary increments. The Query / ScrollableResults pattern is very similar to the JDBC PreparedStatement/ ResultSet pattern and the semantics of methods of this interface are similar to the similarly named methods on ResultSet. |
| </blockquote><p class="paragraph"/>Contrary to JDBC, columns of results are numbered from zero.<p class="paragraph"/><h4>Setting properties in the Criteria instance</h4><p class="paragraph"/>If a node within the builder tree doesn't match a particular criterion it will attempt to set a property on the Criteria object itself. Thus allowing full access to all the properties in this class. The below example calls <code>setMaxResults</code> and <code>setFirstResult</code> on the <a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/Criteria.html" class="api">Criteria</a> instance:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.hibernate.FetchMode as FM |
| … |
| def results = c.list { |
| maxResults(10) |
| firstResult(50) |
| fetchMode(<span class="java-quote">"aRelationship"</span>, FM.JOIN) |
| }</pre></div><p class="paragraph"/><h4>Querying with Eager Fetching</h4><p class="paragraph"/>In the section on <a href="../guide/single.html#5.3.4 Eager and Lazy Fetching" class="guide">Eager and Lazy Fetching</a> we discussed how to declaratively specify fetching to avoid the N+1 SELECT problem. However, this can also be achieved using a criteria query:<p class="paragraph"/><div class="code"><pre>def criteria = Task.createCriteria() |
| def tasks = criteria.list{ |
| eq <span class="java-quote">"assignee.id"</span>, task.assignee.id |
| join 'assignee' |
| join 'project' |
| order 'priority', 'asc' |
| }</pre></div><p class="paragraph"/>Notice the usage of the <code>join</code> method: it tells the criteria API to use a <code>JOIN</code> to fetch the named associations with the <code>Task</code> instances. It's probably best not to use this for one-to-many associations though, because you will most likely end up with duplicate results. Instead, use the 'select' fetch mode: |
| <div class="code"><pre><span class="java-keyword">import</span> org.hibernate.FetchMode as FM |
| … |
| def results = Airport.withCriteria { |
| eq(<span class="java-quote">"region"</span>, <span class="java-quote">"EMEA"</span>) |
| fetchMode <span class="java-quote">"flights"</span>, FM.SELECT |
| }</pre></div> |
| Although this approach triggers a second query to get the <code>flights</code> association, you will get reliable results - even with the <code>maxResults</code> option.<p class="paragraph"/><h4>Method Reference</h4><p class="paragraph"/>If you invoke the builder with no method name such as:<p class="paragraph"/><div class="code"><pre>c { … }</pre></div><p class="paragraph"/>The build defaults to listing all the results and hence the above is equivalent to:<p class="paragraph"/><div class="code"><pre>c.list { … }</pre></div><p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Method</th><th>Description</th></tr><tr class="table-odd"></tr><tr class="table-even"><td><strong class="bold">list</strong></td><td>This is the default method. It returns all matching rows.</td></tr><tr class="table-odd"><td><strong class="bold">get</strong></td><td>Returns a unique result set, i.e. just one row. The criteria has to be formed that way, that it only queries one row. This method is not to be confused with a limit to just the first row.</td></tr><tr class="table-even"><td><strong class="bold">scroll</strong></td><td>Returns a scrollable result set.</td></tr><tr class="table-odd"><td><strong class="bold">listDistinct</strong></td><td>If subqueries or associations are used, one may end up with the same row multiple times in the result set, this allows listing only distinct entities and is equivalent to <code>DISTINCT_ROOT_ENTITY</code> of the <a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/criterion/CriteriaSpecification.html" class="api">CriteriaSpecification</a> class.</td></tr><tr class="table-even"><td><strong class="bold">count</strong></td><td>Returns the number of matching rows.</td></tr></table><p class="paragraph"/><h2><a name="5.4.3 Hibernate Query Language (HQL)">5.4.3 Hibernate Query Language (HQL)</a></h2>GORM classes also support Hibernate's query language HQL, a very complete reference for which can be found <a href="http://docs.jboss.org/hibernate/stable/core/reference/en/html/queryhql.html" target="blank">Chapter 14. HQL: The Hibernate Query Language</a> of the Hibernate documentation.<p class="paragraph"/>GORM provides a number of methods that work with HQL including <a href="../ref/Domain Classes/find.html" class="domainClasses">find</a>, <a href="../ref/Domain Classes/findAll.html" class="domainClasses">findAll</a> and <a href="../ref/Domain Classes/executeQuery.html" class="domainClasses">executeQuery</a>. An example of a query can be seen below:<p class="paragraph"/><div class="code"><pre>def results = |
| Book.findAll(<span class="java-quote">"from Book as b where b.title like 'Lord of the%'"</span>)</pre></div><p class="paragraph"/><h4>Positional and Named Parameters</h4><p class="paragraph"/>In this case the value passed to the query is hard coded, however you can equally use positional parameters:<p class="paragraph"/><div class="code"><pre>def results = |
| Book.findAll(<span class="java-quote">"from Book as b where b.title like ?"</span>, [<span class="java-quote">"The Shi%"</span>])</pre></div><p class="paragraph"/><div class="code"><pre>def author = Author.findByName(<span class="java-quote">"Stephen King"</span>) |
| def books = Book.findAll(<span class="java-quote">"from Book as book where book.author = ?"</span>, [author])</pre></div><p class="paragraph"/>Or even named parameters:<p class="paragraph"/><div class="code"><pre>def results = |
| Book.findAll(<span class="java-quote">"from Book as b where b.title like :search or b.author like :search"</span>, |
| [search:<span class="java-quote">"The Shi%"</span>])</pre></div><p class="paragraph"/><div class="code"><pre>def author = Author.findByName(<span class="java-quote">"Stephen King"</span>) |
| def books = Book.findAll(<span class="java-quote">"from Book as book where book.author = :author"</span>, |
| [author: author])</pre></div><p class="paragraph"/><h4>Multiline Queries</h4><p class="paragraph"/>If you need to separate the query across multiple lines you can use a line continuation character:<p class="paragraph"/><div class="code"><pre>def results = Book.findAll(<span class="java-quote">"\ |
| from Book as b, \ |
| Author as a \ |
| where b.author = a and a.surname = ?"</span>, ['Smith'])</pre></div><p class="paragraph"/><blockquote class="note"> |
| Groovy multiline strings will NOT work with HQL queries |
| </blockquote><p class="paragraph"/><h4>Pagination and Sorting</h4><p class="paragraph"/>You can also perform pagination and sorting whilst using HQL queries. To do so simply specify the pagination options as a map at the end of the method call and include an "ORDER BY" clause in the HQL:<p class="paragraph"/><div class="code"><pre>def results = |
| Book.findAll(<span class="java-quote">"from Book as b where b.title like 'Lord of the%' order by b.title asc"</span>, |
| [max:10, offset:20])</pre></div> |
| <h2><a name="5.5 Advanced GORM Features">5.5 Advanced GORM Features</a></h2>The following sections cover more advanced usages of GORM including caching, custom mapping and events.<h2><a name="5.5.1 Events and Auto Timestamping">5.5.1 Events and Auto Timestamping</a></h2>GORM supports the registration of events as methods that get fired when certain events occurs such as deletes, inserts and updates. The following is a list of supported events: |
| <ul class="star"> |
| <li><code>beforeInsert</code> - Executed before an object is initially persisted to the database</li> |
| <li><code>beforeUpdate</code> - Executed before an object is updated</li> |
| <li><code>beforeDelete</code> - Executed before an object is deleted</li> |
| <li><code>afterInsert</code> - Executed after an object is persisted to the database</li> |
| <li><code>afterUpdate</code> - Executed after an object has been updated</li> |
| <li><code>afterDelete</code> - Executed after an object has been updated</li> |
| <li><code>onLoad</code> - Executed when an object is loaded from the database</li> |
| </ul><p class="paragraph"/>To add an event simply register the relevant closure with your domain class.<p class="paragraph"/><blockquote class="warning"> |
| Do not attempt to flush the session within an event (such as with obj.save(flush:true)). Since events are fired during flushing this will cause a StackOverflowError. |
| </blockquote><p class="paragraph"/><h3>Event types</h3><p class="paragraph"/><h4>The beforeInsert event</h4><p class="paragraph"/>Fired before an object is saved to the db<p class="paragraph"/><div class="code"><pre>class Person { |
| Date dateCreated<p class="paragraph"/> def beforeInsert() { |
| dateCreated = <span class="java-keyword">new</span> Date() |
| } |
| }</pre></div><p class="paragraph"/><h4>The beforeUpdate event</h4><p class="paragraph"/>Fired before an existing object is updated<p class="paragraph"/><div class="code"><pre>class Person { |
| Date dateCreated |
| Date lastUpdated<p class="paragraph"/> def beforeInsert() { |
| dateCreated = <span class="java-keyword">new</span> Date() |
| } |
| def beforeUpdate() { |
| lastUpdated = <span class="java-keyword">new</span> Date() |
| } |
| }</pre></div><p class="paragraph"/><h4>The beforeDelete event</h4><p class="paragraph"/>Fired before an object is deleted.<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> name |
| Date dateCreated |
| Date lastUpdated<p class="paragraph"/> def beforeDelete() { |
| ActivityTrace.withNewSession { |
| <span class="java-keyword">new</span> ActivityTrace(eventName:<span class="java-quote">"Person Deleted"</span>,data:name).save() |
| } |
| } |
| }</pre></div><p class="paragraph"/>Notice the usage of <code>withNewSession</code> method above. Since events are triggered whilst Hibernate is flushing using persistence methods like <code>save()</code> and <code>delete()</code> won't result in objects being saved unless you run your operations with a new <code>Session</code>.<p class="paragraph"/>Fortunately the <code>withNewSession</code> method allows you to share the same transactional JDBC connection even though you're using a different underlying <code>Session</code>.<p class="paragraph"/><h4>The onLoad event</h4><p class="paragraph"/>Fired when an object is loaded from the db:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> name |
| Date dateCreated |
| Date lastUpdated<p class="paragraph"/> def onLoad() { |
| name = <span class="java-quote">"I'm loaded"</span> |
| } |
| }</pre></div><p class="paragraph"/><h4>Custom Event Listeners</h4><p class="paragraph"/>You can also register event handler classes in an application's <code>grails-app/conf/spring/resources.groovy</code> or in the <code>doWithSpring</code> closure in a plugin descriptor by registering a Spring bean named <code>hibernateEventListeners</code>. This bean has one property, <code>listenerMap</code> which specifies the listeners to register for various Hibernate events.<p class="paragraph"/>The values of the map are instances of classes that implement one or more Hibernate listener interfaces. You can use one class that implements all of the required interfaces, or one concrete class per interface, or any combination. The valid map keys and corresponding interfaces are listed here:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th><strong class="bold">Name</strong></th><th><strong class="bold">Interface</strong></th></tr><tr class="table-odd"><td>auto-flush</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/AutoFlushEventListener.html" class="api">AutoFlushEventListener</a></td></tr><tr class="table-even"><td>merge</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/MergeEventListener.html" class="api">MergeEventListener</a></td></tr><tr class="table-odd"><td>create</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/PersistEventListener.html" class="api">PersistEventListener</a></td></tr><tr class="table-even"><td>create-onflush</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/PersistEventListener.html" class="api">PersistEventListener</a></td></tr><tr class="table-odd"><td>delete</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/DeleteEventListener.html" class="api">DeleteEventListener</a></td></tr><tr class="table-even"><td>dirty-check</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/DirtyCheckEventListener.html" class="api">DirtyCheckEventListener</a></td></tr><tr class="table-odd"><td>evict</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/EvictEventListener.html" class="api">EvictEventListener</a></td></tr><tr class="table-even"><td>flush</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/FlushEventListener.html" class="api">FlushEventListener</a></td></tr><tr class="table-odd"><td>flush-entity</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/FlushEntityEventListener.html" class="api">FlushEntityEventListener</a></td></tr><tr class="table-even"><td>load</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/LoadEventListener.html" class="api">LoadEventListener</a></td></tr><tr class="table-odd"><td>load-collection</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/InitializeCollectionEventListener.html" class="api">InitializeCollectionEventListener</a></td></tr><tr class="table-even"><td>lock</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/LockEventListener.html" class="api">LockEventListener</a></td></tr><tr class="table-odd"><td>refresh</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/RefreshEventListener.html" class="api">RefreshEventListener</a></td></tr><tr class="table-even"><td>replicate</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/ReplicateEventListener.html" class="api">ReplicateEventListener</a></td></tr><tr class="table-odd"><td>save-update</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/SaveOrUpdateEventListener.html" class="api">SaveOrUpdateEventListener</a></td></tr><tr class="table-even"><td>save</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/SaveOrUpdateEventListener.html" class="api">SaveOrUpdateEventListener</a></td></tr><tr class="table-odd"><td>update</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/SaveOrUpdateEventListener.html" class="api">SaveOrUpdateEventListener</a></td></tr><tr class="table-even"><td>pre-load</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/PreLoadEventListener.html" class="api">PreLoadEventListener</a></td></tr><tr class="table-odd"><td>pre-update</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/PreUpdateEventListener.html" class="api">PreUpdateEventListener</a></td></tr><tr class="table-even"><td>pre-delete</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/PreDeleteEventListener.html" class="api">PreDeleteEventListener</a></td></tr><tr class="table-odd"><td>pre-insert</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/PreInsertEventListener.html" class="api">PreInsertEventListener</a></td></tr><tr class="table-even"><td>pre-collection-recreate</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/PreCollectionRecreateEventListener.html" class="api">PreCollectionRecreateEventListener</a></td></tr><tr class="table-odd"><td>pre-collection-remove</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/PreCollectionRemoveEventListener.html" class="api">PreCollectionRemoveEventListener</a></td></tr><tr class="table-even"><td>pre-collection-update</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/PreCollectionUpdateEventListener.html" class="api">PreCollectionUpdateEventListener</a></td></tr><tr class="table-odd"><td>post-load</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/PostLoadEventListener.html" class="api">PostLoadEventListener</a></td></tr><tr class="table-even"><td>post-update</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/PostUpdateEventListener.html" class="api">PostUpdateEventListener</a></td></tr><tr class="table-odd"><td>post-delete</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/PostDeleteEventListener.html" class="api">PostDeleteEventListener</a></td></tr><tr class="table-even"><td>post-insert</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/PostInsertEventListener.html" class="api">PostInsertEventListener</a></td></tr><tr class="table-odd"><td>post-commit-update</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/PostUpdateEventListener.html" class="api">PostUpdateEventListener</a></td></tr><tr class="table-even"><td>post-commit-delete</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/PostDeleteEventListener.html" class="api">PostDeleteEventListener</a></td></tr><tr class="table-odd"><td>post-commit-insert</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/PostInsertEventListener.html" class="api">PostInsertEventListener</a></td></tr><tr class="table-even"><td>post-collection-recreate</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/PostCollectionRecreateEventListener.html" class="api">PostCollectionRecreateEventListener</a></td></tr><tr class="table-odd"><td>post-collection-remove</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/PostCollectionRemoveEventListener.html" class="api">PostCollectionRemoveEventListener</a></td></tr><tr class="table-even"><td>post-collection-update</td><td><a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/event/PostCollectionUpdateEventListener.html" class="api">PostCollectionUpdateEventListener</a></td></tr></table><p class="paragraph"/>For example, you could register a class <code>AuditEventListener</code> which implements <code>PostInsertEventListener</code>, <code>PostUpdateEventListener</code>, and <code>PostDeleteEventListener</code> using the following in an application:<p class="paragraph"/><div class="code"><pre>beans = {<p class="paragraph"/> auditListener(AuditEventListener)<p class="paragraph"/> hibernateEventListeners(HibernateEventListeners) { |
| listenerMap = ['post-insert':auditListener, |
| 'post-update':auditListener, |
| 'post-delete':auditListener] |
| } |
| }</pre></div><p class="paragraph"/>or use this in a plugin:<p class="paragraph"/><div class="code"><pre>def doWithSpring = {<p class="paragraph"/> auditListener(AuditEventListener)<p class="paragraph"/> hibernateEventListeners(HibernateEventListeners) { |
| listenerMap = ['post-insert':auditListener, |
| 'post-update':auditListener, |
| 'post-delete':auditListener] |
| } |
| }</pre></div><p class="paragraph"/> |
| <h4>Automatic timestamping</h4><p class="paragraph"/>The examples above demonstrated using events to update a <code>lastUpdated</code> and <code>dateCreated</code> property to keep track of updates to objects. However, this is actually not necessary. By merely defining a <code>lastUpdated</code> and <code>dateCreated</code> property these will be automatically updated for you by GORM.<p class="paragraph"/>If this is not the behaviour you want you can disable this feature with:<p class="paragraph"/><div class="code"><pre>class Person { |
| Date dateCreated |
| Date lastUpdated |
| <span class="java-keyword">static</span> mapping = { |
| autoTimestamp <span class="java-keyword">false</span> |
| } |
| }</pre></div><p class="paragraph"/><h2><a name="5.5.2 Custom ORM Mapping">5.5.2 Custom ORM Mapping</a></h2>Grails domain classes can be mapped onto many legacy schemas via an Object Relational Mapping Domain Specify Language. The following sections takes you through what is possible with the ORM DSL.<p class="paragraph"/><blockquote class="note"> |
| None if this is necessary if you are happy to stick to the conventions defined by GORM for table, column names and so on. You only needs this functionality if you need to in anyway tailor the way GORM maps onto legacy schemas or performs caching |
| </blockquote><p class="paragraph"/>Custom mappings are defined using a a static <code>mapping</code> block defined within your domain class:<p class="paragraph"/><div class="code"><pre>class Person { |
| .. |
| <span class="java-keyword">static</span> mapping = {<p class="paragraph"/> } |
| }</pre></div> |
| <h2><a name="5.5.2.1 Table and Column Names">5.5.2.1 Table and Column Names</a></h2><h4>Table names</h4><p class="paragraph"/>The database table name which the class maps to can be customized using a call to <code>table</code>:<p class="paragraph"/><div class="code"><pre>class Person { |
| .. |
| <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| } |
| }</pre></div><p class="paragraph"/>In this case the class would be mapped to a table called <code>people</code> instead of the default name of <code>person</code>.<p class="paragraph"/><h4>Column names</h4><p class="paragraph"/>It is also possible to customize the mapping for individual columns onto the database. For example if its the name you want to change you can do:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> firstName |
| <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| firstName column:'First_Name' |
| } |
| }</pre></div><p class="paragraph"/>In this case we define method calls that match each property name (in this case <code>firstName</code>). We then use the named parameter <code>column</code>, to specify the column name to map onto.<p class="paragraph"/><h4>Column type</h4><p class="paragraph"/>GORM supports configuration of Hibernate types via the DSL using the type attribute. This includes specifing user types that subclass the Hibernate <a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/usertype/UserType.html" class="api">org.hibernate.usertype.UserType</a> class, which allows complete customization of how a type is persisted. As an example |
| if you had a <code>PostCodeType</code> you could use it as follows:<p class="paragraph"/><div class="code"><pre>class Address { |
| <span class="java-object">String</span> number |
| <span class="java-object">String</span> postCode |
| <span class="java-keyword">static</span> mapping = { |
| postCode type:PostCodeType |
| } |
| }</pre></div><p class="paragraph"/>Alternatively if you just wanted to map it to one of Hibernate's basic types other than the default chosen by Grails you could use:<p class="paragraph"/><div class="code"><pre>class Address { |
| <span class="java-object">String</span> number |
| <span class="java-object">String</span> postCode |
| <span class="java-keyword">static</span> mapping = { |
| postCode type:'text' |
| } |
| }</pre></div><p class="paragraph"/>This would make the <code>postCode</code> column map to the SQL TEXT or CLOB type depending on which database is being used.<p class="paragraph"/>See the Hibernate documentation regarding <a href="http://docs.jboss.org/hibernate/stable/core/reference/en/html/mapping.html#mapping-types-basictypes" target="blank">Basic Types</a> for further information.<p class="paragraph"/><h4>One-to-One Mapping</h4><p class="paragraph"/>In the case of associations it is also possible to change the foreign keys used to map associations. In the case of a one-to-one association this is exactly the same as any regular column. For example consider the below:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> firstName |
| Address address |
| <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| firstName column:'First_Name' |
| address column:'Person_Adress_Id' |
| } |
| }</pre></div><p class="paragraph"/>By default the <code>address</code> association would map to a foreign key column called <code>address_id</code>. By using the above mapping we have changed the name of the foreign key column to <code>Person_Adress_Id</code>.<p class="paragraph"/><h4>One-to-Many Mapping</h4><p class="paragraph"/>With a bidirectional one-to-many you can change the foreign key column used simple by changing the column name on the many side of the association as per the example in the previous section on one-to-one associations. However, with unidirectional association the foreign key needs to be specified on the association itself. For example given a unidirectional one-to-many relationship between <code>Person</code> and <code>Address</code> the following code will change the foreign key in the <code>address</code> table:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> firstName |
| <span class="java-keyword">static</span> hasMany = [addresses:Address] |
| <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| firstName column:'First_Name' |
| addresses column:'Person_Address_Id' |
| } |
| }</pre></div><p class="paragraph"/>If you don't want the column to be in the <code>address</code> table, but instead some intermediate join table you can use the <code>joinTable</code> parameter:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> firstName |
| <span class="java-keyword">static</span> hasMany = [addresses:Address] |
| <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| firstName column:'First_Name' |
| addresses joinTable:[name:'Person_Addresses', key:'Person_Id', column:'Address_Id'] |
| } |
| }</pre></div><p class="paragraph"/><h4>Many-to-Many Mapping</h4><p class="paragraph"/>Grails, by default maps a many-to-many association using a join table. For example consider the below many-to-many association:<p class="paragraph"/><div class="code"><pre>class Group { |
| … |
| <span class="java-keyword">static</span> hasMany = [people:Person] |
| } |
| class Person { |
| … |
| <span class="java-keyword">static</span> belongsTo = Group |
| <span class="java-keyword">static</span> hasMany = [groups:Group] |
| }</pre></div><p class="paragraph"/>In this case Grails will create a join table called <code>group_person</code> containing foreign keys called <code>person_id</code> and <code>group_id</code> referencing the <code>person</code> and <code>group</code> tables. If you need to change the column names you can specify a column within the mappings for each class.<p class="paragraph"/><div class="code"><pre>class Group { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| people column:'Group_Person_Id' |
| } |
| } |
| class Person { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| groups column:'Group_Group_Id' |
| } |
| }</pre></div><p class="paragraph"/>You can also specify the name of the join table to use:<p class="paragraph"/><div class="code"><pre>class Group { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| people column:'Group_Person_Id',joinTable:'PERSON_GROUP_ASSOCIATIONS' |
| } |
| } |
| class Person { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| groups column:'Group_Group_Id',joinTable:'PERSON_GROUP_ASSOCIATIONS' |
| } |
| }</pre></div><h2><a name="5.5.2.2 Caching Strategy">5.5.2.2 Caching Strategy</a></h2><h4>Setting up caching</h4><p class="paragraph"/><a href="http://www.hibernate.org/" target="blank">Hibernate</a> features a second-level cache with a customizable cache provider. This needs to be configured in the <code>grails-app/conf/DataSource.groovy</code> file as follows:<p class="paragraph"/><div class="code"><pre>hibernate { |
| cache.use_second_level_cache=<span class="java-keyword">true</span> |
| cache.use_query_cache=<span class="java-keyword">true</span> |
| cache.provider_class='org.hibernate.cache.EhCacheProvider' |
| }</pre></div><p class="paragraph"/>You can of course customize these settings how you desire, for example if you want to use a distributed caching mechanism.<p class="paragraph"/><blockquote class="note"> |
| For further reading on caching and in particular Hibernate's second-level cache, refer to the <a href="http://docs.jboss.org/hibernate/stable/core/reference/en/html/performance.html#performance-cache" target="blank">Hibernate documentation</a> on the subject. |
| </blockquote><p class="paragraph"/><h4>Caching instances</h4><p class="paragraph"/>In your mapping block to enable caching with the default settings use a call to the <code>cache</code> method:<p class="paragraph"/><div class="code"><pre>class Person { |
| .. |
| <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| cache <span class="java-keyword">true</span> |
| } |
| }</pre></div><p class="paragraph"/>This will configure a 'read-write' cache that includes both lazy and non-lazy properties. If you need to customize this further you can do:<p class="paragraph"/><div class="code"><pre>class Person { |
| .. |
| <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| cache usage:'read-only', include:'non-lazy' |
| } |
| }</pre></div><p class="paragraph"/><h4>Caching associations</h4><p class="paragraph"/>As well as the ability to use Hibernate's second level cache to cache instances you can also cache collections (associations) of objects. For example:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> firstName |
| <span class="java-keyword">static</span> hasMany = [addresses:Address] |
| <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| version <span class="java-keyword">false</span> |
| addresses column:'Address', cache:<span class="java-keyword">true</span> |
| } |
| } |
| class Address { |
| <span class="java-object">String</span> number |
| <span class="java-object">String</span> postCode |
| }</pre></div><p class="paragraph"/>This will enable a 'read-write' caching mechanism on the addresses collection. You can also use:<p class="paragraph"/><div class="code"><pre>cache:'read-write' // or 'read-only' or 'transactional'</pre></div><p class="paragraph"/>To further configure the cache usage.<p class="paragraph"/><h4>Caching Queries</h4><p class="paragraph"/>You can cache queries such as dynamic finders and criteria. To do so using a dynamic finder you can pass the <code>cache</code> argument:<p class="paragraph"/><div class="code"><pre>def person = Person.findByFirstName(<span class="java-quote">"Fred"</span>, [cache:<span class="java-keyword">true</span>])</pre></div><p class="paragraph"/><blockquote class="note"> |
| Note that in order for the results of the query to be cached, you still need to enable caching in your mapping as discussed in the previous section. |
| </blockquote><p class="paragraph"/>You can also cache criteria queries:<p class="paragraph"/><div class="code"><pre>def people = Person.withCriteria { |
| like('firstName', 'Fr%') |
| cache <span class="java-keyword">true</span> |
| }</pre></div><p class="paragraph"/><h4>Cache usages</h4><p class="paragraph"/>Below is a description of the different cache settings and their usages: |
| <ul class="star"> |
| <li><code>read-only</code> - If your application needs to read but never modify instances of a persistent class, a read-only cache may be used.</li> |
| <li><code>read-write</code> - If the application needs to update data, a read-write cache might be appropriate.</li> |
| <li><code>nonstrict-read-write</code> - If the application only occasionally needs to update data (ie. if it is extremely unlikely that two transactions would try to update the same item simultaneously) and strict transaction isolation is not required, a <code>nonstrict-read-write</code> cache might be appropriate.</li> |
| <li><code>transactional</code> - The <code>transactional</code> cache strategy provides support for fully transactional cache providers such as JBoss TreeCache. Such a cache may only be used in a JTA environment and you must specify <code>hibernate.transaction.manager_lookup_class</code> in the <code>grails-app/conf/DataSource.groovy</code> file's <code>hibernate</code> config.</li> |
| </ul><p class="paragraph"/><h2><a name="5.5.2.3 Inheritance Strategies">5.5.2.3 Inheritance Strategies</a></h2>By default GORM classes uses <code>table-per-hierarchy</code> inheritance mapping. This has the disadvantage that columns cannot have a <code>NOT-NULL</code> constraint applied to them at the db level. If you would prefer to use a <code>table-per-subclass</code> inheritance strategy you can do so as follows:<p class="paragraph"/><div class="code"><pre>class Payment { |
| <span class="java-object">Long</span> id |
| <span class="java-object">Long</span> version |
| <span class="java-object">Integer</span> amount<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| tablePerHierarchy <span class="java-keyword">false</span> |
| } |
| } |
| class CreditCardPayment <span class="java-keyword">extends</span> Payment { |
| <span class="java-object">String</span> cardNumber |
| }</pre></div><p class="paragraph"/>The mapping of the root <code>Payment</code> class specifies that it will not be using <code>table-per-hierarchy</code> mapping for all child classes.<h2><a name="5.5.2.4 Custom Database Identity">5.5.2.4 Custom Database Identity</a></h2>You can customize how GORM generates identifiers for the database using the DSL. By default GORM relies on the native database mechanism for generating ids. This is by far the best approach, but there are still many schemas that have different approaches to identity.<p class="paragraph"/>To deal with this Hibernate defines the concept of an id generator. You can customize the id generator and the column it maps to as follows:<p class="paragraph"/><div class="code"><pre>class Person { |
| .. |
| <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| version <span class="java-keyword">false</span> |
| id generator:'hilo', params:[table:'hi_value',column:'next_value',max_lo:100] |
| } |
| }</pre></div><p class="paragraph"/>In this case we're using one of Hibernate's built in 'hilo' generators that uses a separate table to generate ids.<p class="paragraph"/><blockquote class="note"> |
| For more information on the different Hibernate generators refer to the <a href="http://docs.jboss.org/hibernate/stable/core/reference/en/html/mapping.html#mapping-declaration-id-generator" target="blank">Hibernate reference documentation</a> |
| </blockquote><p class="paragraph"/>Note that if you want to merely customise the column that the id lives on you can do:<p class="paragraph"/><div class="code"><pre>class Person { |
| .. |
| <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| version <span class="java-keyword">false</span> |
| id column:'person_id' |
| } |
| }</pre></div> |
| <h2><a name="5.5.2.5 Composite Primary Keys">5.5.2.5 Composite Primary Keys</a></h2>GORM supports the concept of composite identifiers (identifiers composed from 2 or more properties). It is not an approach we recommend, but is available to you if you need it:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> firstName |
| <span class="java-object">String</span> lastName<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| id composite:['firstName', 'lastName'] |
| } |
| }</pre></div><p class="paragraph"/>The above will create a composite id of the <code>firstName</code> and <code>lastName</code> properties of the Person class. When you later need to retrieve an instance by id you have to use a prototype of the object itself:<p class="paragraph"/><div class="code"><pre>def p = Person.get(<span class="java-keyword">new</span> Person(firstName:<span class="java-quote">"Fred"</span>, lastName:<span class="java-quote">"Flintstone"</span>)) |
| println p.firstName</pre></div> |
| <h2><a name="5.5.2.6 Database Indices">5.5.2.6 Database Indices</a></h2>To get the best performance out of your queries it is often necessary to tailor the table index definitions. How you tailor them is domain specific and a matter of monitoring usage patterns of your queries. With GORM's DSL you can specify which columns need to live in which indexes:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> firstName |
| <span class="java-object">String</span> address |
| <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| version <span class="java-keyword">false</span> |
| id column:'person_id' |
| firstName column:'First_Name', index:'Name_Idx' |
| address column:'Address', index:'Name_Idx,Address_Index' |
| } |
| }</pre></div><p class="paragraph"/>Note that you cannot have any spaces in the value of the <code>index</code> attribute; in this example <code>index:'Name_Idx, Address_Index'</code> will cause an error. |
| <h2><a name="5.5.2.7 Optimistic Locking and Versioning">5.5.2.7 Optimistic Locking and Versioning</a></h2>As discussed in the section on <a href="../guide/single.html#5.3.5 Pessimistic and Optimistic Locking" class="guide">Optimistic and Pessimistic Locking</a>, by default GORM uses optimistic locking and automatically injects a <code>version</code> property into every class which is in turn mapped to a <code>version</code> column at the database level.<p class="paragraph"/>If you're mapping to a legacy schema this can be problematic, so you can disable this feature by doing the following:<p class="paragraph"/><div class="code"><pre>class Person { |
| .. |
| <span class="java-keyword">static</span> mapping = { |
| table 'people' |
| version <span class="java-keyword">false</span> |
| } |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| If you disable optimistic locking you are essentially on your own with regards to concurrent updates and are open to the risk of users losing (due to data overriding) data unless you use <a href="../guide/single.html#5.3.5 Pessimistic and Optimistic Locking" class="guide">pessimistic locking</a> |
| </blockquote> |
| <h2><a name="5.5.2.8 Eager and Lazy Fetching">5.5.2.8 Eager and Lazy Fetching</a></h2><h4>Lazy Collections</h4><p class="paragraph"/>As discussed in the section on <a href="../guide/single.html#5.3.4 Eager and Lazy Fetching" class="guide">Eager and Lazy fetching</a>, GORM collections are lazily loaded by default but you can change this behaviour via the ORM DSL. There are several options available to you, but the most common ones are: |
| <ul class="star"> |
| <li>lazy: false</li> |
| <li>fetch: 'join'</li> |
| </ul><p class="paragraph"/>and they're used like this:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> firstName |
| Pet pet |
| <span class="java-keyword">static</span> hasMany = [addresses:Address] |
| <span class="java-keyword">static</span> mapping = { |
| addresses lazy:<span class="java-keyword">false</span> |
| pet fetch: 'join' |
| } |
| }<p class="paragraph"/>class Address { |
| <span class="java-object">String</span> street |
| <span class="java-object">String</span> postCode |
| }<p class="paragraph"/>class Pet { |
| <span class="java-object">String</span> name |
| }</pre></div><p class="paragraph"/>The first option, <code>lazy: false</code> , ensures that when a <code>Person</code> instance is loaded, its <code>addresses</code> collection is loaded at the same time with a second SELECT. The second option is basically the same, except the collection is loaded via a JOIN rather than another SELECT. Typically you will want to reduce the number of queries, so <code>fetch: 'join'</code> will be the more appropriate option. On the other hand, it could feasibly be the more expensive approach if your domain model and data result in more and larger results than would otherwise be necessary.<p class="paragraph"/>For more advanced users, the other settings available are: |
| <ol> |
| <li>batchSize: N</li> |
| <li>lazy: false, batchSize: N</li> |
| </ol><p class="paragraph"/>where N is an integer. These allow you to fetch results in batches, with one query per batch. As a simple example, consider this mapping for <code>Person</code>:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> firstName |
| Pet pet<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| pet batchSize: 5 |
| } |
| }</pre></div> |
| If a query returns multiple <code>Person</code> instances, then when we access the first <code>pet</code> property, Hibernate will fetch that <code>Pet</code> plus the four next ones. You can get the same behaviour with eager loading by combining <code>batchSize</code> with the <code>lazy: false</code> option. You can find out more about these options in the <a href="http://docs.jboss.org/hibernate/core/3.3/reference/en/html/performance.html#performance-fetching" target="blank">Hibernate user guide</a> and this <a href="http://community.jboss.org/wiki/AShortPrimerOnFetchingStrategies" target="blank">primer on fetching strategies</a>. Note that ORM DSL does not currently support the "subselect" fetching strategy.<p class="paragraph"/><h4>Lazy Single-Ended Associations</h4><p class="paragraph"/>In GORM, one-to-one and many-to-one associations are by default lazy. Non-lazy single ended associations can be problematic when you load many entities because each non-lazy association will result in an extra SELECT statement. If the associated entities also have non-lazy associations, the number of queries grows exponentially!<p class="paragraph"/>If you want to make a one-to-one or many-to-one association non-lazy/eager, you can use the same technique as for lazy collections:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> firstName |
| }<p class="paragraph"/>class Address { |
| <span class="java-object">String</span> street |
| <span class="java-object">String</span> postCode |
| <span class="java-keyword">static</span> belongsTo = [person:Person] |
| <span class="java-keyword">static</span> mapping = { |
| person lazy:<span class="java-keyword">false</span> |
| } |
| }</pre></div><p class="paragraph"/>Here we configure GORM to load the associated <code>Person</code> instance (through the <code>person</code> property) whenever an <code>Address</code> is loaded.<p class="paragraph"/><h4>Lazy Single-Ended Associations and Proxies</h4><p class="paragraph"/>In order to facilitate single-ended lazy associations Hibernate uses runtime generated proxies. The way this works is that Hibernate dynamically subclasses the proxied entity to create the proxy.<p class="paragraph"/>Consider the previous example but with a lazily-loaded <code>person</code> association: Hibernate will set the <code>person</code> property to a proxy that is a subclass of <code>Person</code>. When you call any of the getters or setters on that proxy, Hibernate will load the entity from the database.<p class="paragraph"/>Unfortunately this technique can produce surprising results. Consider the following example classes:<p class="paragraph"/><div class="code"><pre>class Pet { |
| <span class="java-object">String</span> name |
| } |
| class Dog <span class="java-keyword">extends</span> Pet { |
| } |
| class Person { |
| <span class="java-object">String</span> name |
| Pet pet |
| }</pre></div><p class="paragraph"/>and assume that we have a single <code>Person</code> instance with a <code>Dog</code> as his or her <code>pet</code>. The following code will work as you would expect: |
| <div class="code"><pre>def person = Person.get(1) |
| assert person.pet <span class="java-keyword">instanceof</span> Dog |
| assert Pet.get(person.petId) <span class="java-keyword">instanceof</span> Dog</pre></div> |
| But this won't: |
| <div class="code"><pre>def person = Person.get(1) |
| assert person.pet <span class="java-keyword">instanceof</span> Dog |
| assert Pet.list()[0] <span class="java-keyword">instanceof</span> Dog</pre></div> |
| For some reason, the second assertion fails. To add to the confusion, this will work: |
| <div class="code"><pre>assert Pet.list()[0] <span class="java-keyword">instanceof</span> Dog</pre></div> |
| What's going on here? It's down to a combination of how proxies work and the guarantees that the Hibernate session makes. When you load the <code>Person</code> instance, Hibernate creates a proxy for its <code>pet</code> relation and attaches it to the session. Once that happens, whenever you retrieve that <code>Pet</code> instance via a query, a <code>get()</code>, or the <code>pet</code> relation <em class="italic">within the same session</em> , Hibernate gives you the proxy.<p class="paragraph"/>Fortunately for us, GORM automatically unwraps the proxy when you use <code>get()</code> and <code>findBy*()</code>, or when you directly access the relation. That means you don't have to worry at all about proxies in the majority of cases. But GORM doesn't do that for objects returned via a query that returns a list, such as <code>list()</code> and <code>findAllBy*()</code>. However, if Hibernate hasn't attached the proxy to the session, those queries will return the real instances - hence why the last example works.<p class="paragraph"/>You can protect yourself to a degree from this problem by using the <code>instanceOf</code> method by GORM: |
| <div class="code"><pre>def person = Person.get(1) |
| assert Pet.list()[0].instanceOf(Dog)</pre></div><p class="paragraph"/>However, it won't help here casting is involved. For example, the following code will throw a <code>ClassCastException</code> because the first pet in the list is a proxy instance with a class that is neither <code>Dog</code> nor a sub-class of <code>Dog</code>:<p class="paragraph"/><div class="code"><pre>def person = Person.get(1) |
| Dog pet = Pet.list()[0]</pre></div><p class="paragraph"/>Of course, it's best not to use static types in this situation. If you use an untyped variable for the pet instead, you can access any <code>Dog</code> properties or methods on the instance without any problems.<p class="paragraph"/>These days it's rare that you will come across this issue, but it's best to be aware of it just in case. At least you will know why such an error occurs and be able to work around it. |
| <h2><a name="5.5.2.9 Custom Cascade Behaviour">5.5.2.9 Custom Cascade Behaviour</a></h2>As describes in the section on <a href="../guide/single.html#5.3.3 Understanding Cascading Updates and Deletes" class="guide">cascading updates</a>, the primary mechanism to control the way updates and deletes are cascading from one association to another is the <a href="../ref/Domain Classes/belongsTo.html" class="domainClasses">belongsTo</a> static property.<p class="paragraph"/>However, the ORM DSL gives you complete access to Hibernate's <a href="http://www.hibernate.org/http://docs.jboss.org/hibernate/stable/core/reference/en/html/objectstate.html#objectstate-transitive" target="blank">transitive persistence</a> capabilities via the <code>cascade</code> attribute.<p class="paragraph"/>Valid settings for the cascade attribute include: |
| <ul class="star"> |
| <li>merge - merges the state of a detached association</li> |
| <li>save-update - cascades only saves and updates to an association</li> |
| <li>delete - cascades only deletes to an association</li> |
| <li>lock - useful if a pessimistic lock should be cascaded to its associations</li> |
| <li>refresh - cascades refreshes to an association</li> |
| <li>evict - cascades evictions (equivalent to discard() in GORM) to associations if set</li> |
| <li>all - cascade ALL operations to associations</li> |
| <li>all-delete-orphan - Applies only to one-to-many associations and indicates that when a child is removed from an association then it should be automatically deleted. Children are also deleted when the parent is.</li> |
| </ul><p class="paragraph"/><blockquote class="note"> |
| It is advisable to read the section in the Hibernate documentation on <a href="http://docs.jboss.org/hibernate/stable/core/reference/en/html/objectstate.html#objectstate-transitive" target="blank">transitive persistence</a> to obtain a better understanding of the different cascade styles and recommendation for their usage |
| </blockquote><p class="paragraph"/>To specific the cascade attribute simply define one or many (comma-separated) of the aforementioned settings as its value:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">String</span> firstName |
| <span class="java-keyword">static</span> hasMany = [addresses:Address] |
| <span class="java-keyword">static</span> mapping = { |
| addresses cascade:<span class="java-quote">"all-delete-orphan"</span> |
| } |
| } |
| class Address { |
| <span class="java-object">String</span> street |
| <span class="java-object">String</span> postCode |
| }</pre></div><p class="paragraph"/><h2><a name="5.5.2.10 Custom Hibernate Types">5.5.2.10 Custom Hibernate Types</a></h2>You saw in an earlier section that you can use composition (via the <code>embedded</code> property) to break a table into multiple objects. You can achieve a similar effect via Hibernate's custom user types. These are not domain classes themselves, but plain Java or Groovy classes with associated. Each of these types also has a corresponding "meta-type" class that implements <a href="http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/usertype/UserType.html" class="api">org.hibernate.usertype.UserType</a>.<p class="paragraph"/>The <a href="http://docs.jboss.org/hibernate/stable/core/reference/en/html/mapping.html#mapping-types-custom" target="blank">Hibernate reference manual</a> has some information on custom types, but here we will focus on how to map them in Grails. Let's start by taking a look at a simple domain class that uses an old-fashioned (pre-Java 1.5) type-safe enum class:<p class="paragraph"/><div class="code"><pre>class Book { |
| <span class="java-object">String</span> title |
| <span class="java-object">String</span> author |
| Rating rating<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| rating type: RatingUserType |
| } |
| }</pre></div><p class="paragraph"/>All we have done is declare the <code>rating</code> field the enum type and set the property's type in the custom mapping to the corresponding <code>UserType</code> implementation. That's all you have to do to start using your custom type. If you want, you can also use the other column settings such as "column" to change the column name and "index" to add it to an index.<p class="paragraph"/>Custom types aren't limited to just a single column - they can be mapped to as many columns as you want. In such cases you need to explicitly define in the mapping what columns to use, since Hibernate can only use the property name for a single column. Fortunately, Grails allows you to map multiple columns to a property using this syntax:<p class="paragraph"/><div class="code"><pre>class Book { |
| <span class="java-object">String</span> title |
| Name author |
| Rating rating<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| name type: NameUserType, { |
| column name: <span class="java-quote">"first_name"</span> |
| column name: <span class="java-quote">"last_name"</span> |
| } |
| rating type: RatingUserType |
| } |
| }</pre></div><p class="paragraph"/>The above example will create "first_name" and "last_name" columns for the <code>author</code> property. You'll be pleased to know that you can also use some of the normal column/property mapping attributes in the column definitions. For example:<p class="paragraph"/><div class="code"><pre>column name: <span class="java-quote">"first_name"</span>, index: <span class="java-quote">"my_idx"</span>, unique: <span class="java-keyword">true</span></pre></div><p class="paragraph"/>The column definitions do <em class="italic">not</em> support the following attributes: <code>type</code>, <code>cascade</code>, <code>lazy</code>, <code>cache</code>, and <code>joinTable</code>.<p class="paragraph"/>One thing to bear in mind with custom types is that they define the <em class="italic">SQL types</em> for the corresponding database columns. That helps take the burden of configuring them yourself, but what happens if you have a legacy database that uses a different SQL type for one of the columns? In that case, you need to override column's SQL type using the <code>sqlType</code> attribute:<p class="paragraph"/><div class="code"><pre>class Book { |
| <span class="java-object">String</span> title |
| Name author |
| Rating rating<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| name type: NameUserType, { |
| column name: <span class="java-quote">"first_name"</span>, sqlType: <span class="java-quote">"text"</span> |
| column name: <span class="java-quote">"last_name"</span>, sqlType: <span class="java-quote">"text"</span> |
| } |
| rating type: RatingUserType, sqlType: <span class="java-quote">"text"</span> |
| } |
| }</pre></div><p class="paragraph"/>Mind you, the SQL type you specify needs to still work with the custom type. So overriding a default of "varchar" with "text" is fine, but overriding "text" with "yes_no" isn't going to work. |
| <h2><a name="5.5.2.11 Derived Properties">5.5.2.11 Derived Properties</a></h2>A derived property is a property that takes its value from a SQL expression, |
| often but not necessarily based on the value of some other persistent |
| property. Consider a Product class like this:<p class="paragraph"/><div class="code"><pre>class Product { |
| <span class="java-object">Float</span> price |
| <span class="java-object">Float</span> taxRate |
| <span class="java-object">Float</span> tax |
| }</pre></div><p class="paragraph"/>If the <code>tax</code> property is derived based on the value of <code>price</code> and <code>taxRate</code> |
| properties then there may be no need to persist the <code>tax</code> property in the |
| database. The SQL used to derive the value of a derived property may be |
| expressed in the ORM DSL like this:<p class="paragraph"/><div class="code"><pre>class Product { |
| <span class="java-object">Float</span> price |
| <span class="java-object">Float</span> taxRate |
| <span class="java-object">Float</span> tax<p class="paragraph"/> <span class="java-keyword">static</span> mapping = { |
| tax formula: 'PRICE * TAX_RATE' |
| } |
| }</pre></div><p class="paragraph"/>Note that the formula expressed in the ORM DSL is SQL so references to other |
| properties should relate to the persistence model not the object model, which |
| is why the example refers to <code>PRICE</code> and <code>TAX_RATE</code> instead of <code>price</code> and |
| <code>taxRate</code>.<p class="paragraph"/>With that in place, when a Product is retrieved with something like <code>Product.get(42)</code>, the SQL that is generated to support |
| that will look something like this:<p class="paragraph"/><div class="code"><pre>select |
| product0_.id as id1_0_, |
| product0_.version as version1_0_, |
| product0_.price as price1_0_, |
| product0_.tax_rate as tax4_1_0_, |
| product0_.PRICE * product0_.TAX_RATE as formula1_0_ |
| from |
| product product0_ |
| where |
| product0_.id=?</pre></div><p class="paragraph"/>Since the <code>tax</code> property is being derived at runtime and not stored in the |
| database it might seem that the same effect could be achieved by adding |
| a method like <code>getTax()</code> to the <code>Product</code> class that simply returns the |
| product of the <code>taxRate</code> and <code>price</code> properties. With an approach like |
| that you would give up the ability query the database based on the value |
| of the <code>tax</code> property. Using a derived property allows exactly that. To |
| retrieve all <code>Product</code> objects that have a <code>tax</code> value greater than 21.12 |
| you could execute a query like this:<p class="paragraph"/><div class="code"><pre>Product.findAllByTaxGreaterThan(21.12)</pre></div><p class="paragraph"/>Derived properties may be referenced in the Criteria API:<p class="paragraph"/><div class="code"><pre>Product.withCriteria { |
| gt 'tax', 21.12f |
| }</pre></div><p class="paragraph"/>The SQL that is generated to support either of those would look something like this:<p class="paragraph"/><div class="code"><pre>select |
| this_.id as id1_0_, |
| this_.version as version1_0_, |
| this_.price as price1_0_, |
| this_.tax_rate as tax4_1_0_, |
| this_.PRICE * this_.TAX_RATE as formula1_0_ |
| from |
| product this_ |
| where |
| this_.PRICE * this_.TAX_RATE>?</pre></div><p class="paragraph"/><blockquote class="note"> |
| Note that because the value of a derived property is generated in the database and depends |
| on the execution of SQL code, derived properties may not have GORM constraints applied |
| to them. If constraints are specified for a derived property, they will be ignored. |
| </blockquote><p class="paragraph"/><h2><a name="5.5.2.12 Custom Naming Strategy">5.5.2.12 Custom Naming Strategy</a></h2>By default Grails uses Hibernate's <code>ImprovedNamingStrategy</code> to convert domain class Class and field names to SQL table and column names by converting from camel-cased Strings to ones that use underscores as word separators. You can customize these on a per-instance basis in the <code>mapping</code> closure but if there's a consistent pattern you can specify a different <code>NamingStrategy</code> class to use.<p class="paragraph"/>Configure the class name to be used in <code>grails-app/conf/DataSource.groovy</code> in the <code>hibernate</code> section, e.g.<p class="paragraph"/><div class="code"><pre>dataSource { |
| pooled = <span class="java-keyword">true</span> |
| dbCreate = <span class="java-quote">"create-drop"</span> |
| … |
| }<p class="paragraph"/>hibernate { |
| cache.use_second_level_cache = <span class="java-keyword">true</span> |
| … |
| naming_strategy = com.myco.myproj.CustomNamingStrategy |
| }</pre></div><p class="paragraph"/>You can use an existing class or write your own, for example one that prefixes table names and column names:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> com.myco.myproj<p class="paragraph"/><span class="java-keyword">import</span> org.hibernate.cfg.ImprovedNamingStrategy |
| <span class="java-keyword">import</span> org.hibernate.util.StringHelper<p class="paragraph"/>class CustomNamingStrategy <span class="java-keyword">extends</span> ImprovedNamingStrategy {<p class="paragraph"/> <span class="java-object">String</span> classToTableName(<span class="java-object">String</span> className) { |
| <span class="java-quote">"table_"</span> + StringHelper.unqualify(className) |
| }<p class="paragraph"/> <span class="java-object">String</span> propertyToColumnName(<span class="java-object">String</span> propertyName) { |
| <span class="java-quote">"col_"</span> + StringHelper.unqualify(propertyName) |
| } |
| }</pre></div><p class="paragraph"/><h2><a name="5.5.3 Default Sort Order">5.5.3 Default Sort Order</a></h2>You can sort objects using queries arguments such as those found in the <a href="../ref/Domain Classes/list.html" class="domainClasses">list</a> method:<p class="paragraph"/><div class="code"><pre>def airports = Airport.list(sort:'name')</pre></div><p class="paragraph"/>However, you can also declare the sort order declaratively:<p class="paragraph"/><div class="code"><pre>class Airport { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| sort <span class="java-quote">"name"</span> |
| } |
| }</pre></div><p class="paragraph"/>You can also configure the sort order if necessary:<p class="paragraph"/><div class="code"><pre>class Airport { |
| … |
| <span class="java-keyword">static</span> mapping = { |
| sort name:<span class="java-quote">"desc"</span> |
| } |
| }</pre></div><p class="paragraph"/>Alternatively, you can configure sort order at the association level:<p class="paragraph"/><div class="code"><pre>class Airport { |
| … |
| <span class="java-keyword">static</span> hasMany = [flights:Flight] |
| <span class="java-keyword">static</span> mapping = { |
| flights sort:'number' |
| } |
| }</pre></div><h2><a name="5.6 Programmatic Transactions">5.6 Programmatic Transactions</a></h2>Grails is built on Spring and hence uses Spring's Transaction abstraction for dealing with programmatic transactions. However, GORM classes have been enhanced to make this more trivial through the <a href="../ref/Domain Classes/withTransaction.html" class="domainClasses">withTransaction</a> method which accepts a block the first argument to which is the Spring <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/transaction/TransactionStatus.html" class="api">TransactionStatus</a> object.<p class="paragraph"/>A typical usage scenario is as follows:<p class="paragraph"/><div class="code"><pre>def transferFunds = { |
| Account.withTransaction { status -> |
| def source = Account.get(params.from) |
| def dest = Account.get(params.to)<p class="paragraph"/> def amount = params.amount.toInteger() |
| <span class="java-keyword">if</span>(source.active) { |
| source.balance -= amount |
| <span class="java-keyword">if</span>(dest.active) { |
| dest.amount += amount |
| } |
| <span class="java-keyword">else</span> { |
| status.setRollbackOnly() |
| } |
| }<p class="paragraph"/> |
| }<p class="paragraph"/>}</pre></div><p class="paragraph"/>In this example we rollback the transactions if the destination account is not active and if any exception are thrown during the process the transaction will automatically be rolled back.<p class="paragraph"/>You can also use "save points" to rollback a transaction to a particular point in time if you don't want to rollback the entire transaction. This can be achieved through the use of Spring's <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/transaction/SavepointManager.html" class="api">SavePointManager</a> interface.<p class="paragraph"/>The <a href="../ref/Domain Classes/withTransaction.html" class="domainClasses">withTransaction</a> method deals with the begin/commit/rollback logic for you within the scope of the block.<h2><a name="5.7 GORM and Constraints">5.7 GORM and Constraints</a></h2>Although constraints are covered in the <a href="../guide/single.html#7.1 Declaring Constraints" class="guide">Validation</a> section, it is important to mention them here as some of the constraints can affect the way in which the database schema is generated.<p class="paragraph"/>Where feasible, Grails uses a domain class's constraints to influence the database columns generated for the corresponding domain class properties.<p class="paragraph"/>Consider the following example. Suppose we have a domain model with the following property.<p class="paragraph"/><div class="code"><pre><span class="java-object">String</span> name |
| <span class="java-object">String</span> description</pre></div><p class="paragraph"/>By default, in MySQL, Grails would define these columns as...<p class="paragraph"/><div class="code"><pre>column name | data type |
| description | varchar(255)</pre></div><p class="paragraph"/>But perhaps the business rules for this domain class state that a description can be up to 1000 characters in length. If that were the case, we'd likely define the column as follows <em class="italic">if</em> we were creating the table via an SQL script.<p class="paragraph"/><div class="code"><pre>column name | data type |
| description | TEXT</pre></div><p class="paragraph"/>Chances are we'd also want to have some application-based validation to make sure we don't exceed that 1000 character limit <em class="italic">before</em> we persist any records. In Grails, we achieve this validation via <a href="../guide/single.html#7.1 Declaring Constraints" class="guide">constraints</a>. We'd add the following constraint declaration to the domain class.<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> constraints = { |
| description(maxSize:1000) |
| }</pre></div><p class="paragraph"/>This constraint would provide both the application-based validation we want and it would also cause the schema to be generated as shown above. Below is a description of the other constraints that influence schema generation.<p class="paragraph"/><h4>Constraints Affecting String Properties</h4> |
| <ul class="star"> |
| <li><a href="../ref/Constraints/inList.html" class="constraints">inList</a></li> |
| <li><a href="../ref/Constraints/maxSize.html" class="constraints">maxSize</a></li> |
| <li><a href="../ref/Constraints/size.html" class="constraints">size</a></li> |
| </ul><p class="paragraph"/>If either the <code>maxSize</code> or the <code>size</code> constraint is defined, Grails sets the maximum column length based on the constraint value.<p class="paragraph"/>In general, it's not advisable to use both constraints on the same domain class property. However, if both the <code>maxSize</code> constraint and the <code>size</code> constraint are defined, then Grails sets the column length to the minimum of the <code>maxSize</code> constraint and the upper bound of the size constraint. (Grails uses the minimum of the two, because any length that exceeds that minimum will result in a validation error.)<p class="paragraph"/>If the inList constraint is defined (and the <code>maxSize</code> and the <code>size</code> constraints are not defined), then Grails sets the maximum column length based on the length of the longest string in the list of valid values. For example, given a list including values "Java", "Groovy", and "C++", Grails would set the column length to 6 (i.e., the number of characters in the string "Groovy").<p class="paragraph"/><h4>Constraints Affecting Numeric Properties</h4> |
| <ul class="star"> |
| <li><a href="../ref/Constraints/min.html" class="constraints">min</a></li> |
| <li><a href="../ref/Constraints/max.html" class="constraints">max</a></li> |
| <li><a href="../ref/Constraints/range.html" class="constraints">range</a></li> |
| </ul><p class="paragraph"/>If the <code>max</code> constraint, the <code>min</code> constraint, or the <code>range</code> constraint is defined, Grails attempts to set the column <a href="http://uk.builder.com/architecture/db/0,39026552,20268520,00.htm" target="blank">precision</a> based on the constraint value. (The success of this attempted influence is largely dependent on how Hibernate interacts with the underlying DBMS.)<p class="paragraph"/>In general, it's not advisable to combine the pair min/max and range constraints together on the same domain class property. However, if both of these constraints is defined, then Grails uses the minimum precision value from the constraints. (Grails uses the minimum of the two, because any length that exceeds that minimum precision will result in a validation error.) |
| <ul class="star"> |
| <li><a href="../ref/Constraints/scale.html" class="constraints">scale</a></li> |
| </ul><p class="paragraph"/>If the scale constraint is defined, then Grails attempts to set the column <a href="http://uk.builder.com/architecture/db/0,39026552,20268520,00.htm" target="blank">scale</a> based on the constraint value. This rule only applies to floating point numbers (i.e., java.lang.Float, java.Lang.Double, java.lang.BigDecimal, or subclasses of java.lang.BigDecimal). (The success of this attempted influence is largely dependent on how Hibernate interacts with the underlying DBMS.)<p class="paragraph"/>The constraints define the minimum/maximum numeric values, and Grails derives the maximum number of digits for use in the precision. Keep in mind that specifying only one of min/max constraints will not affect schema generation (since there could be large negative value of property with max:100, for example), unless specified constraint value requires more digits than default Hibernate column precision is (19 at the moment). For example...<p class="paragraph"/><div class="code"><pre>someFloatValue(max:1000000, scale:3)</pre></div><p class="paragraph"/>would yield:<p class="paragraph"/><div class="code"><pre>someFloatValue DECIMAL(19, 3) // precision is <span class="java-keyword">default</span></pre></div><p class="paragraph"/>but<p class="paragraph"/><div class="code"><pre>someFloatValue(max:12345678901234567890, scale:5)</pre></div><p class="paragraph"/>would yield: |
| <div class="code"><pre>someFloatValue DECIMAL(25, 5) // precision = digits in max + scale</pre></div><p class="paragraph"/>and<p class="paragraph"/><div class="code"><pre>someFloatValue(max:100, min:-100000)</pre></div><p class="paragraph"/>would yield:<p class="paragraph"/><div class="code"><pre>someFloatValue DECIMAL(8, 2) // precision = digits in min + <span class="java-keyword">default</span> scale</pre></div><h1><a name="6. The Web Layer">6. The Web Layer</a></h1><h2><a name="6.1 Controllers">6.1 Controllers</a></h2>A controller handles requests and creates or prepares the response and is request-scoped. In other words a new instance is created for each <a href="../ref/Controllers/request.html" class="controllers">request</a>. A controller can generate the response or delegate to a view. To create a controller simply create a class whose name ends with <code>Controller</code> and place it within the <code>grails-app/controllers</code> directory.<p class="paragraph"/>The default <a href="../guide/single.html#6.4 URL Mappings" class="guide">URL Mapping</a> setup ensures that the first part of your controller name is mapped to a URI and each action defined within your controller maps to URI within the controller name URI.<p class="paragraph"/><p class="paragraph"/> |
| <h2><a name="6.1.1 Understanding Controllers and Actions">6.1.1 Understanding Controllers and Actions</a></h2><h4>Creating a controller</h4><p class="paragraph"/>Controllers can be created with the <a href="../ref/Command Line/create-controller.html" class="commandLine">create-controller</a> target. For example try running the following command from the root of a Grails project:<p class="paragraph"/><div class="code"><pre>grails create-controller book</pre></div><p class="paragraph"/>The command will result in the creation of a controller at the location <code>grails-app/controllers/BookController.groovy</code>:<p class="paragraph"/><div class="code"><pre>class BookController { … }</pre></div><p class="paragraph"/><code>BookController</code> by default maps to the /book URI (relative to your application root).<p class="paragraph"/><blockquote class="note"> |
| The <code>create-controller</code> command is merely for convenience and you can just as easily create controllers using your favorite text editor or IDE |
| </blockquote><p class="paragraph"/><h4>Creating Actions</h4><p class="paragraph"/>A controller can have multiple properties that are each assigned a block of code. Each of these properties maps to a URI:<p class="paragraph"/><div class="code"><pre>class BookController { |
| def list = {<p class="paragraph"/> // <span class="java-keyword">do</span> controller logic |
| // create model<p class="paragraph"/> <span class="java-keyword">return</span> model |
| } |
| }</pre></div><p class="paragraph"/>This example maps to the <code>/book/list</code> URI by default thanks to the property being named <code>list</code>.<p class="paragraph"/><h4>The Default Action</h4><p class="paragraph"/>A controller has the concept of a default URI that maps to the root URI of the controller. By default the default URI in this case is <code>/book</code>. The default URI is dictated by the following rules: |
| <ul class="star"> |
| <li>If only one action is present the default URI for a controller maps to that action.</li> |
| <li>If you define an <code>index</code> action which is the action that handles requests when no action is specified in the URI <code>/book</code></li> |
| <li>Alternatively you can set it explicitly with the <code>defaultAction</code> property:</li> |
| </ul><p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> defaultAction = <span class="java-quote">"list"</span></pre></div> |
| <h2><a name="6.1.2 Controllers and Scopes">6.1.2 Controllers and Scopes</a></h2><h4>Available Scopes</h4><p class="paragraph"/>Scopes are essentially hash like objects that allow you to store variables. The following scopes are available to controllers: |
| <ul class="star"> |
| <li><a href="../ref/Controllers/servletContext.html" class="controllers">servletContext</a> - Also known as application scope, this scope allows you to share state across the entire web application. The servletContext is an instance of <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/ServletContext.html" class="api">javax.servlet.ServletContext</a></li> |
| <li><a href="../ref/Controllers/session.html" class="controllers">session</a> - The session allows associating state with a given user and typically uses cookies to associate a session with a client. The session object is an instance of <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpSession.html" class="api">HttpSession</a></li> |
| <li><a href="../ref/Controllers/request.html" class="controllers">request</a> - The request object allows the storage of objects for the current request only. The request object is an instance of <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletRequest.html" class="api">HttpServletRequest</a></li> |
| <li><a href="../ref/Controllers/params.html" class="controllers">params</a> - Mutable map of incoming request (CGI) parameters</li> |
| <li><a href="../ref/Controllers/flash.html" class="controllers">flash</a> - See below.</li> |
| </ul><p class="paragraph"/><h4>Accessing Scopes</h4><p class="paragraph"/>Scopes can be accessed using the variable names above in combination with Groovy's array index operator even on classes provided by the Servlet API such as the <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletRequest.html" class="api">HttpServletRequest</a>:<p class="paragraph"/><div class="code"><pre>class BookController { |
| def find = { |
| def findBy = params[<span class="java-quote">"findBy"</span>] |
| def appContext = request[<span class="java-quote">"foo"</span>] |
| def loggedUser = session[<span class="java-quote">"logged_user"</span>]<p class="paragraph"/> } |
| }</pre></div><p class="paragraph"/>You can even access values within scopes using the de-reference operator making the syntax even clearer:<p class="paragraph"/><div class="code"><pre>class BookController { |
| def find = { |
| def findBy = params.findBy |
| def appContext = request.foo |
| def loggedUser = session.logged_user<p class="paragraph"/> } |
| }</pre></div><p class="paragraph"/>This is one of the ways that Grails unifies access to the different scopes.<p class="paragraph"/><h4>Using Flash Scope</h4><p class="paragraph"/>Grails supports the concept of <a href="../ref/Controllers/flash.html" class="controllers">flash</a> scope is a temporary store for attributes which need to be available for this request and the next request only. Afterwards the attributes are cleared. This is useful for setting a message directly before redirection, for example:<p class="paragraph"/><div class="code"><pre>def delete = { |
| def b = Book.get( params.id ) |
| <span class="java-keyword">if</span>(!b) { |
| flash.message = <span class="java-quote">"User not found <span class="java-keyword">for</span> id ${params.id}"</span> |
| redirect(action:list) |
| } |
| … // remaining code |
| }</pre></div> |
| <h2><a name="6.1.3 Models and Views">6.1.3 Models and Views</a></h2><h4>Returning the Model</h4><p class="paragraph"/>A model is essentially a map that the view uses when rendering. The keys within that map translate to variable names accessible by the view. There are a couple of ways to return a model, the first way is to explicitly return a map instance:<p class="paragraph"/><div class="code"><pre>def show = { |
| [ book : Book.get( params.id ) ] |
| }</pre></div><p class="paragraph"/>If no explicit model is returned the controller's properties will be used as the model thus allowing you to write code like this:<p class="paragraph"/><div class="code"><pre>class BookController { |
| List books |
| List authors |
| def list = { |
| books = Book.list() |
| authors = Author.list() |
| } |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| This is possible due to the fact that controllers are prototype scoped. In other words a new controller is created for each request. Otherwise code such as the above would not be thread safe. |
| </blockquote><p class="paragraph"/>In the above example the <code>books</code> and <code>authors</code> properties will be available in the view.<p class="paragraph"/>A more advanced approach is to return an instance of the Spring <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/ModelAndView.html" class="api">ModelAndView</a> class:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.springframework.web.servlet.ModelAndView<p class="paragraph"/>def index = { |
| def favoriteBooks = … // get some books just <span class="java-keyword">for</span> the index page, perhaps your favorites<p class="paragraph"/> // forward to the list view to show them |
| <span class="java-keyword">return</span> <span class="java-keyword">new</span> ModelAndView(<span class="java-quote">"/book/list"</span>, [ bookList : favoriteBooks ]) |
| }</pre></div><p class="paragraph"/> |
| <h4>Selecting the View</h4><p class="paragraph"/>In both of the previous two examples there was no code that specified which <a href="../guide/single.html#6.2 Groovy Server Pages" class="guide">view</a> to render. So how does Grails know which view to pick? The answer lies in the conventions. For the action:<p class="paragraph"/><div class="code"><pre>class BookController { |
| def show = { |
| [ book : Book.get( params.id ) ] |
| } |
| }</pre></div><p class="paragraph"/>Grails will automatically look for a view at the location <code>grails-app/views/book/show.gsp</code> (actually Grails will try to look for a JSP first, as Grails can equally be used with JSP).<p class="paragraph"/>If you wish to render another view, then the <a href="../ref/Controllers/render.html" class="controllers">render</a> method there to help:<p class="paragraph"/><div class="code"><pre>def show = { |
| def map = [ book : Book.get( params.id ) ] |
| render(view:<span class="java-quote">"display"</span>, model:map) |
| }</pre></div><p class="paragraph"/>In this case Grails will attempt to render a view at the location <code>grails-app/views/book/display.gsp</code>. Notice that Grails automatically qualifies the view location with the <code>book</code> folder of the <code>grails-app/views</code> directory. This is convenient, but if you have some shared views you need to access instead use:<p class="paragraph"/><div class="code"><pre>def show = { |
| def map = [ book : Book.get( params.id ) ] |
| render(view:<span class="java-quote">"/shared/display"</span>, model:map) |
| }</pre></div><p class="paragraph"/>In this case Grails will attempt to render a view at the location <code>grails-app/views/shared/display.gsp</code>.<p class="paragraph"/> |
| <h4>Rendering a Response</h4><p class="paragraph"/>Sometimes its easier (typically with Ajax applications) to render snippets of text or code to the response directly from the controller. For this, the highly flexible <code>render</code> method can be used:<p class="paragraph"/><div class="code"><pre>render <span class="java-quote">"Hello World!"</span></pre></div><p class="paragraph"/> |
| The above code writes the text "Hello World!" to the response, other examples include:<p class="paragraph"/><div class="code"><pre>// write some markup |
| render { |
| <span class="java-keyword">for</span>(b in books) { |
| div(id:b.id, b.title) |
| } |
| } |
| // render a specific view |
| render(view:'show') |
| // render a template <span class="java-keyword">for</span> each item in a collection |
| render(template:'book_template', collection:Book.list()) |
| // render some text with encoding and content type |
| render(text:<span class="java-quote">"<xml>some xml</xml>"</span>,contentType:<span class="java-quote">"text/xml"</span>,encoding:<span class="java-quote">"UTF-8"</span>)</pre></div><p class="paragraph"/>If you plan on using Groovy's MarkupBuilder to generate html for use with the render method becareful of naming clashes between html elements and Grails tags. e.g.<p class="paragraph"/><div class="code"><pre>def login = { |
| StringWriter w = <span class="java-keyword">new</span> StringWriter() |
| def builder = <span class="java-keyword">new</span> groovy.xml.MarkupBuilder(w) |
| builder.html{ |
| head{ |
| title 'Log in' |
| } |
| body{ |
| h1 'Hello' |
| form{ |
| } |
| } |
| }<p class="paragraph"/> def html = w.toString() |
| render html |
| }</pre></div><p class="paragraph"/>Will actually <a href="../guide/single.html#6.2.2.6 Tags as Method Calls" class="guide">call the form tag</a> (which will return some text that will be ignored by the MarkupBuilder). To correctly output a <form> elemement, use the following:<p class="paragraph"/><div class="code"><pre>def login = { |
| // … |
| body{ |
| h1 'Hello' |
| builder.form{ |
| } |
| } |
| // … |
| }</pre></div> |
| <h2><a name="6.1.4 Redirects and Chaining">6.1.4 Redirects and Chaining</a></h2><h4>Redirects</h4><p class="paragraph"/>Actions can be redirected using the <a href="../ref/Controllers/redirect.html" class="controllers">redirect</a> method present in all controllers:<p class="paragraph"/><div class="code"><pre>class OverviewController { |
| def login = {}<p class="paragraph"/> def find = { |
| <span class="java-keyword">if</span>(!session.user) |
| redirect(action:login) |
| … |
| } |
| }</pre></div><p class="paragraph"/>Internally the <a href="../ref/Controllers/redirect.html" class="controllers">redirect</a> method uses the <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletResponse.html" class="api">HttpServletResonse</a> object's <code>sendRedirect</code> method.<p class="paragraph"/>The <code>redirect</code> method expects either: |
| <ul class="star"> |
| <li>Another closure within the same controller class:</li> |
| </ul><p class="paragraph"/><div class="code"><pre>// Call the login action within the same class |
| redirect(action:login)</pre></div> |
| <ul class="star"> |
| <li>The name of a controller and action:</li> |
| </ul><p class="paragraph"/><div class="code"><pre>// Also redirects to the index action in the home controller |
| redirect(controller:'home',action:'index')</pre></div> |
| <ul class="star"> |
| <li> A URI for a resource relative the application context path:</li> |
| </ul><p class="paragraph"/><div class="code"><pre>// Redirect to an explicit URI |
| redirect(uri:<span class="java-quote">"/login.html"</span>)</pre></div> |
| <ul class="star"> |
| <li>Or a full URL:</li> |
| </ul><p class="paragraph"/><div class="code"><pre>// Redirect to a URL |
| redirect(url:<span class="java-quote">"http://grails.org"</span>)</pre></div><p class="paragraph"/>Parameters can be optionally passed from one action to the next using the <code>params</code> argument of the method:<p class="paragraph"/><div class="code"><pre>redirect(action:myaction, params:[myparam:<span class="java-quote">"myvalue"</span>])</pre></div><p class="paragraph"/> |
| These parameters are made available through the <a href="../ref/Controllers/params.html" class="controllers">params</a> dynamic property that also 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 used.<p class="paragraph"/>Since the <code>params</code> object is also a map, you can use it to pass the current request parameters from one action to the next:<p class="paragraph"/><div class="code"><pre>redirect(action:<span class="java-quote">"next"</span>, params:params)</pre></div><p class="paragraph"/>Finally, you can also include a fragment in the target URI:<p class="paragraph"/><div class="code"><pre>redirect(controller: <span class="java-quote">"test"</span>, action: <span class="java-quote">"show"</span>, fragment: <span class="java-quote">"profile"</span>)</pre></div><p class="paragraph"/>will (depending on the URL mappings) redirect to something like "/myapp/test/show#profile".<p class="paragraph"/><h4>Chaining</h4><p class="paragraph"/>Actions can also be chained. Chaining allows the model to be retained from one action to the next. For example calling the <code>first</code> action in the below action:<p class="paragraph"/><div class="code"><pre>class ExampleChainController { |
| def first = { |
| chain(action:second,model:[one:1]) |
| } |
| def second = { |
| chain(action:third,model:[two:2]) |
| } |
| def third = { |
| [three:3]) |
| } |
| }</pre></div><p class="paragraph"/> |
| Results in the model:<p class="paragraph"/><div class="code"><pre>[one:1, two:2, three:3]</pre></div><p class="paragraph"/> |
| The model can be accessed in subsequent controller actions in the chain via the <code>chainModel</code> map. This dynamic property only exists in actions following the call to the <code>chain</code> method:<p class="paragraph"/><div class="code"><pre>class ChainController {<p class="paragraph"/> def nextInChain = { |
| def model = chainModel.myModel |
| … |
| } |
| }</pre></div><p class="paragraph"/> |
| Like the <code>redirect</code> method you can also pass parameters to the <code>chain</code> method:<p class="paragraph"/><div class="code"><pre>chain(action:<span class="java-quote">"action1"</span>, model:[one:1], params:[myparam:<span class="java-quote">"param1"</span>])</pre></div><p class="paragraph"/><h2><a name="6.1.5 Controller Interceptors">6.1.5 Controller Interceptors</a></h2>Often it is useful to intercept processing based on either request, session or application state. This can be achieved via action interceptors. There are currently 2 types of interceptors: before and after.<p class="paragraph"/><blockquote class="note"> |
| If your interceptor is likely to apply to more than one controller, you are almost certainly better off writing a <a href="../guide/single.html#6.6 Filters" class="guide">Filter</a>. Filters can be applied to multiple controllers or URIs, without the need to change the logic of each controller |
| </blockquote><p class="paragraph"/><h4>Before Interception</h4><p class="paragraph"/>The <code>beforeInterceptor</code> intercepts processing before the action is executed. If it returns <code>false</code> then the intercepted action will not be executed. The interceptor can be defined for all actions in a controller as follows:<p class="paragraph"/><div class="code"><pre>def beforeInterceptor = { |
| println <span class="java-quote">"Tracing action ${actionUri}"</span> |
| }</pre></div><p class="paragraph"/> |
| The above is declared inside the body of the controller definition. It will be executed before all actions and does not interfere with processing. A common use case is however for authentication:<p class="paragraph"/><div class="code"><pre>def beforeInterceptor = [action:<span class="java-keyword">this</span>.&auth,except:'login'] |
| // defined as a regular method so its <span class="java-keyword">private</span> |
| def auth() { |
| <span class="java-keyword">if</span>(!session.user) { |
| redirect(action:'login') |
| <span class="java-keyword">return</span> <span class="java-keyword">false</span> |
| } |
| } |
| def login = { |
| // display login page |
| }</pre></div><p class="paragraph"/> |
| The above code defines a method called <code>auth</code>. A method is used so that it is not exposed as an action to the outside world (i.e. it is private). The <code>beforeInterceptor</code> then defines an interceptor that is used on all actions 'except' the login action and is told to execute the 'auth' method. The 'auth' method is referenced using Groovy's method pointer syntax, within the method itself it detects whether there is a user in the session otherwise it redirects to the login action and returns false, instruction the intercepted action not to be processed.<p class="paragraph"/><h4>After Interception</h4><p class="paragraph"/>To define an interceptor that is executed after an action use the <code>afterInterceptor</code> property:<p class="paragraph"/><div class="code"><pre>def afterInterceptor = { model -> |
| println <span class="java-quote">"Tracing action ${actionUri}"</span> |
| }</pre></div><p class="paragraph"/>The after interceptor takes the resulting model as an argument and can hence perform post manipulation of the model or response.<p class="paragraph"/>An after interceptor may also modify the Spring MVC <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/ModelAndView.html" class="api">ModelAndView</a> object prior to rendering. In this case, the above example becomes:<p class="paragraph"/><div class="code"><pre>def afterInterceptor = { model, modelAndView -> |
| println <span class="java-quote">"Current view is ${modelAndView.viewName}"</span> |
| <span class="java-keyword">if</span>(model.someVar) modelAndView.viewName = <span class="java-quote">"/mycontroller/someotherview"</span> |
| println <span class="java-quote">"View is now ${modelAndView.viewName}"</span> |
| }</pre></div><p class="paragraph"/>This allows the view to be changed based on the model returned by the current action. Note that the <code>modelAndView</code> may be <code>null</code> if the action being intercepted called redirect or render.<p class="paragraph"/> |
| <h4>Interception Conditions</h4><p class="paragraph"/>Rails users will be familiar with the authentication example and how the 'except' condition was used when executing the interceptor (interceptors are called 'filters' in Rails, this terminology conflicts with the servlet filter terminology in Java land):<p class="paragraph"/><div class="code"><pre>def beforeInterceptor = [action:<span class="java-keyword">this</span>.&auth,except:'login']</pre></div><p class="paragraph"/>This executes the interceptor for all actions except the specified action. A list of actions can also be defined as follows:<p class="paragraph"/><div class="code"><pre>def beforeInterceptor = [action:<span class="java-keyword">this</span>.&auth,except:['login','register']]</pre></div><p class="paragraph"/>The other supported condition is 'only', this executes the interceptor for only the specified actions:<p class="paragraph"/><div class="code"><pre>def beforeInterceptor = [action:<span class="java-keyword">this</span>.&auth,only:['secure']]</pre></div><p class="paragraph"/><h2><a name="6.1.6 Data Binding">6.1.6 Data Binding</a></h2>Data binding is the act of "binding" incoming request parameters onto the properties of an object or an entire graph of objects. Data binding should deal with all necessary type conversion since request parameters, which are typically delivered via a form submission, are always strings whilst the properties of a Groovy or Java object may well not be.<p class="paragraph"/>Grails uses <a href="http://www.springframework.org" target="blank">Spring's</a> underlying data binding capability to perform data binding.<p class="paragraph"/><h4>Binding Request Data to the Model</h4><p class="paragraph"/>There are two ways to bind request parameters onto the properties of a domain class. The first involves using a domain classes' implicit constructor:<p class="paragraph"/><div class="code"><pre>def save = { |
| def b = <span class="java-keyword">new</span> Book(params) |
| b.save() |
| }</pre></div><p class="paragraph"/>The data binding happens within the code <code>new Book(params)</code>. By passing the <a href="../ref/Controllers/params.html" class="controllers">params</a> object to the domain class constructor Grails automatically recognizes that you are trying to bind from request parameters. So if we had an incoming request like:<p class="paragraph"/><div class="code"><pre>/book/save?title=The%20Stand&author=Stephen%20King</pre></div><p class="paragraph"/>Then the <code>title</code> and <code>author</code> request parameters would automatically get set on the domain class. If you need to perform data binding onto an existing instance then you can use the <a href="../ref/Domain Classes/properties.html" class="domainClasses">properties</a> property:<p class="paragraph"/><div class="code"><pre>def save = { |
| def b = Book.get(params.id) |
| b.properties = params |
| b.save() |
| }</pre></div><p class="paragraph"/>This has exactly the same effect as using the implicit constructor.<p class="paragraph"/><h4>Data binding and Single-ended Associations</h4><p class="paragraph"/>If you have a <code>one-to-one</code> or <code>many-to-one</code> association you can use Grails' data binding capability to update these relationships too. For example if you have an incoming request such as:<p class="paragraph"/><div class="code"><pre>/book/save?author.id=20</pre></div><p class="paragraph"/>Grails will automatically detect the <code>.id</code> suffix on the request parameter and look-up the <code>Author</code> instance for the given id when doing data binding such as:<p class="paragraph"/><div class="code"><pre>def b = <span class="java-keyword">new</span> Book(params)</pre></div><p class="paragraph"/>An association property can be set to <code>null</code> by passing the literal <code>String</code> "null". For example:<p class="paragraph"/><div class="code"><pre>/book/save?author.id=<span class="java-keyword">null</span></pre></div><p class="paragraph"/><h4>Data Binding and Many-ended Associations</h4><p class="paragraph"/>If you have a one-to-many or many-to-many association there are different techniques for data binding depending of the association type.<p class="paragraph"/>If you have a <code>Set</code> based association (default for a <code>hasMany</code>) then the simplest way to populate an association is to simply send a list of identifiers. For example consider the usage of <code><g:select></code> below:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:select name=<span class="xml-quote">"books"</span> |
| from=<span class="xml-quote">"${Book.list()}"</span> |
| size=<span class="xml-quote">"5"</span> multiple=<span class="xml-quote">"yes"</span> optionKey=<span class="xml-quote">"id"</span> |
| value=<span class="xml-quote">"${author?.books}"</span> /></span></pre></div><p class="paragraph"/>This produces a select box that allows you to select multiple values. In this case if you submit the form Grails will automatically use the identifiers from the select box to populate the <code>books</code> association.<p class="paragraph"/>However, if you have a scenario where you want to update the properties of the associated objects the this technique won't work. Instead you have to use the subscript operator:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:textField name=<span class="xml-quote">"books[0].title"</span> value=<span class="xml-quote">"the Stand"</span> /></span> |
| <span class="xml-tag"><g:textField name=<span class="xml-quote">"books[1].title"</span> value=<span class="xml-quote">"the Shining"</span> /></span></pre></div><p class="paragraph"/>However, with <code>Set</code> based association it is critical that you render the mark-up in the same order that you plan to do the update in. This is because a <code>Set</code> has no concept of order, so although we're referring to <code>books0</code> and <code>books1</code> it is not guaranteed that the order of the association will be correct on the server side unless you apply some explicit sorting yourself.<p class="paragraph"/>This is not a problem if you use <code>List</code> based associations, since a <code>List</code> has a defined order and an index you can refer to. This is also true of <code>Map</code> based associations.<p class="paragraph"/>Note also that if the association you are binding to has a size of 2 and you refer to an element that is outside the size of association:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:textField name=<span class="xml-quote">"books[0].title"</span> value=<span class="xml-quote">"the Stand"</span> /></span> |
| <span class="xml-tag"><g:textField name=<span class="xml-quote">"books[1].title"</span> value=<span class="xml-quote">"the Shining"</span> /></span> |
| <span class="xml-tag"><g:textField name=<span class="xml-quote">"books[2].title"</span> value=<span class="xml-quote">"Red Madder"</span> /></span></pre></div><p class="paragraph"/>Then Grails will automatically create a new instance for you at the defined position. If you "skipped" a few elements in the middle:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:textField name=<span class="xml-quote">"books[0].title"</span> value=<span class="xml-quote">"the Stand"</span> /></span> |
| <span class="xml-tag"><g:textField name=<span class="xml-quote">"books[1].title"</span> value=<span class="xml-quote">"the Shining"</span> /></span> |
| <span class="xml-tag"><g:textField name=<span class="xml-quote">"books[5].title"</span> value=<span class="xml-quote">"Red Madder"</span> /></span></pre></div><p class="paragraph"/>Then Grails will automatically create instances in between. For example in the above case Grails will create 4 additional instances if the association being bound had a size of 2.<p class="paragraph"/>You can bind existing instances of the associated type to a <code>List</code> using the same <code>.id</code> syntax as you would use with a single-ended association. For example:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:select name=<span class="xml-quote">"books[0].id"</span> from=<span class="xml-quote">"${Book.list()}"</span> value=<span class="xml-quote">"${author?.books[0]?.id}"</span> /></span> |
| <span class="xml-tag"><g:select name=<span class="xml-quote">"books[1].id"</span> from=<span class="xml-quote">"${Book.list()}"</span> value=<span class="xml-quote">"${author?.books[1]?.id}"</span> /></span> |
| <span class="xml-tag"><g:select name=<span class="xml-quote">"books[2].id"</span> from=<span class="xml-quote">"${Book.list()}"</span> value=<span class="xml-quote">"${author?.books[2]?.id}"</span> /></span></pre></div><p class="paragraph"/>Would allow individual entries in the <code>books List</code> to be selected separately.<p class="paragraph"/>Entries at particular indexes can be removed in the same way too. For example:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:select name=<span class="xml-quote">"books[0].id"</span> from=<span class="xml-quote">"${Book.list()}"</span> value=<span class="xml-quote">"${author?.books[0]?.id}"</span> noSelection=<span class="xml-quote">"['null': '']"</span>/></span></pre></div><p class="paragraph"/>Will render a select box that will remove the association at <code>books0</code> if the empty option is chosen.<p class="paragraph"/>Binding to a <code>Map</code> property works in exactly the same way except that the list index in the parameter name is replaced by the map key:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:select name=<span class="xml-quote">"images[cover].id"</span> from=<span class="xml-quote">"${Image.list()}"</span> value=<span class="xml-quote">"${book?.images[cover]?.id}"</span> noSelection=<span class="xml-quote">"['null': '']"</span>/></span></pre></div><p class="paragraph"/>This would bind the selected image into the <code>Map</code> property <code>images</code> under a key of <code>"cover"</code>.<p class="paragraph"/><h4>Data binding with Multiple domain classes</h4><p class="paragraph"/>It is possible to bind data to multiple domain objects from the <a href="../ref/Controllers/params.html" class="controllers">params</a> object.<p class="paragraph"/>For example so you have an incoming request to:<p class="paragraph"/><div class="code"><pre>/book/save?book.title=The%20Stand&author.name=Stephen%20King</pre></div><p class="paragraph"/>You'll notice the difference with the above request is that each parameter has a prefix such as <code>author.</code> or <code>book.</code> which is used to isolate which parameters belong to which type. Grails' <code>params</code> object is like a multi-dimensional hash and you can index into to isolate only a subset of the parameters to bind.<p class="paragraph"/><div class="code"><pre>def b = <span class="java-keyword">new</span> Book(params['book'])</pre></div><p class="paragraph"/>Notice how we use the prefix before the first dot of the <code>book.title</code> parameter to isolate only parameters below this level to bind. We could do the same with an <code>Author</code> domain class:<p class="paragraph"/><div class="code"><pre>def a = <span class="java-keyword">new</span> Author(params['author'])</pre></div><p class="paragraph"/><h4>Data binding and type conversion errors</h4><p class="paragraph"/>Sometimes when performing data binding it is not possible to convert a particular String into a particular target type. What you get is a type conversion error. Grails will retain type conversion errors inside the <a href="../ref/Domain Classes/errors.html" class="domainClasses">errors</a> property of a Grails domain class. Take this example:<p class="paragraph"/><div class="code"><pre>class Book { |
| … |
| URL publisherURL |
| }</pre></div><p class="paragraph"/>Here we have a domain class <code>Book</code> that uses the Java concrete type <code>java.net.URL</code> to represent URLs. Now say we had an incoming request such as:<p class="paragraph"/><div class="code"><pre>/book/save?publisherURL=a-bad-url</pre></div><p class="paragraph"/> |
| In this case it is not possible to bind the string <code>a-bad-url</code> to the <code>publisherURL</code> property os a type mismatch error occurs. You can check for these like this:<p class="paragraph"/> |
| <div class="code"><pre>def b = <span class="java-keyword">new</span> Book(params)<p class="paragraph"/><span class="java-keyword">if</span>(b.hasErrors()) { |
| println <span class="java-quote">"The value ${b.errors.getFieldError('publisherURL').rejectedValue} is not a valid URL!"</span> |
| }</pre></div><p class="paragraph"/>Although we have not yet covered error codes (for more information see the section on <a href="../guide/single.html#7. Validation" class="guide">Validation</a>), for type conversion errors you would want a message to use for the error inside the grails-app/i18n/messages.properties file. You can use a generic error message handler such as:<p class="paragraph"/><div class="code"><pre>typeMismatch.java.net.URL=The field {0} is not a valid URL</pre></div><p class="paragraph"/>Or a more specific one:<p class="paragraph"/><div class="code"><pre>typeMismatch.Book.publisherURL=The publisher URL you specified is not a valid URL</pre></div><p class="paragraph"/><h4>Data Binding and Security concerns</h4><p class="paragraph"/>When batch updating properties from request parameters you need to be careful not to allow clients to bind malicious data to domain classes that end up being persisted to the database. You can limit what properties are bound to a given domain class using the subscript operator:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1)<p class="paragraph"/>p.properties['firstName','lastName'] = params</pre></div><p class="paragraph"/>In this case only the <code>firstName</code> and <code>lastName</code> properties will be bound.<p class="paragraph"/>Another way to do this is instead of using domain classes as the target of data binding you could use <a href="../guide/single.html#6.1.10 Command Objects" class="guide">Command Objects</a>. Alternatively there is also the flexible <a href="../ref/Controllers/bindData.html" class="controllers">bindData</a> method.<p class="paragraph"/>The <code>bindData</code> method allows the same data binding capability, but to arbitrary objects:<p class="paragraph"/><div class="code"><pre>def p = <span class="java-keyword">new</span> Person() |
| bindData(p, params)</pre></div><p class="paragraph"/>However, the <code>bindData</code> method also allows you to exclude certain parameters that you don't want updated:<p class="paragraph"/><div class="code"><pre>def p = <span class="java-keyword">new</span> Person() |
| bindData(p, params, [exclude:'dateOfBirth'])</pre></div><p class="paragraph"/>Or include only certain properties:<p class="paragraph"/><div class="code"><pre>def p = <span class="java-keyword">new</span> Person() |
| bindData(p, params, [include:['firstName','lastName]])</pre></div><p class="paragraph"/><h2><a name="6.1.7 XML and JSON Responses">6.1.7 XML and JSON Responses</a></h2><h4>Using the render method to output XML</h4><p class="paragraph"/>Grails' supports a few different ways to produce XML and JSON responses. The first one covered is via the <a href="../ref/Controllers/render.html" class="controllers">render</a> method.<p class="paragraph"/>The <code>render</code> method can be passed a block of code to do mark-up building in XML:<p class="paragraph"/><div class="code"><pre>def list = { |
| def results = Book.list() |
| render(contentType:<span class="java-quote">"text/xml"</span>) { |
| books { |
| <span class="java-keyword">for</span>(b in results) { |
| book(title:b.title) |
| } |
| } |
| } |
| }</pre></div><p class="paragraph"/>The result of this code would be something like:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><books></span> |
| <span class="xml-tag"><book title=<span class="xml-quote">"The Stand"</span> /></span> |
| <span class="xml-tag"><book title=<span class="xml-quote">"The Shining"</span> /></span> |
| <span class="xml-tag"></books></span></pre></div><p class="paragraph"/>Note that you need to be careful to avoid naming conflicts when using mark-up building. For example this code would produce an error:<p class="paragraph"/><div class="code"><pre>def list = { |
| def books = Book.list() // naming conflict here |
| render(contentType:<span class="java-quote">"text/xml"</span>) { |
| books { |
| <span class="java-keyword">for</span>(b in results) { |
| book(title:b.title) |
| } |
| } |
| } |
| }</pre></div><p class="paragraph"/>The reason is that there is local variable <code>books</code> which Groovy attempts to invoke as a method.<p class="paragraph"/> |
| <h4>Using the render method to output JSON</h4><p class="paragraph"/>The <code>render</code> method can also be used to output JSON:<p class="paragraph"/><div class="code"><pre>def list = { |
| def results = Book.list() |
| render(contentType:<span class="java-quote">"text/json"</span>) { |
| books = array { |
| <span class="java-keyword">for</span>(b in results) { |
| book title:b.title |
| } |
| } |
| } |
| }</pre></div><p class="paragraph"/>In this case the result would be something along the lines of:<p class="paragraph"/><div class="code"><pre>[ |
| {title:<span class="java-quote">"The Stand"</span>}, |
| {title:<span class="java-quote">"The Shining"</span>} |
| ]</pre></div><p class="paragraph"/>Again the same dangers with naming conflicts apply to JSON building.<p class="paragraph"/><h4>Automatic XML Marshalling</h4><p class="paragraph"/>Grails also supports automatic marshaling of <a href="../guide/single.html#5. Object Relational Mapping (GORM)" class="guide">domain classes</a> to XML via special converters.<p class="paragraph"/>To start off with import the <code>grails.converters</code> package into your controller:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.converters.*</pre></div><p class="paragraph"/>Now you can use the following highly readable syntax to automatically convert domain classes to XML:<p class="paragraph"/><div class="code"><pre>render Book.list() as XML</pre></div><p class="paragraph"/>The resulting output would look something like the following::<p class="paragraph"/><div class="code"><pre><?xml version=<span class="java-quote">"1.0"</span> encoding=<span class="java-quote">"ISO-8859-1"</span>?> |
| <list> |
| <book id=<span class="java-quote">"1"</span>> |
| <author>Stephen King</author> |
| <title>The Stand</title> |
| </book> |
| <book id=<span class="java-quote">"2"</span>> |
| <author>Stephen King</author> |
| <title>The Shining</title> |
| </book> |
| </list></pre></div><p class="paragraph"/>An alternative to using the converters is to use the <a href="../guide/single.html#11.2 Encoding and Decoding Objects" class="guide">codecs</a> feature of Grails. The codecs feature provides <a href="../guide/single.html#11.2 Encoding and Decoding Objects" class="guide">encodeAsXML</a> and <a href="../guide/single.html#11.2 Encoding and Decoding Objects" class="guide">encodeAsJSON</a> methods:<p class="paragraph"/><div class="code"><pre>def xml = Book.list().encodeAsXML() |
| render xml</pre></div><p class="paragraph"/>For more information on XML marshaling see the section on <a href="../guide/single.html#13.1 REST" class="guide">REST</a><p class="paragraph"/><h4>Automatic JSON Marshalling</h4><p class="paragraph"/>Grails also supports automatic marshaling to JSON via the same mechanism. Simply substitute <code>XML</code> with <code>JSON</code>:<p class="paragraph"/><div class="code"><pre>render Book.list() as JSON</pre></div><p class="paragraph"/>The resulting output would look something like the following:<p class="paragraph"/><div class="code"><pre>[ |
| {<span class="java-quote">"id"</span>:1, |
| <span class="java-quote">"class"</span>:<span class="java-quote">"Book"</span>, |
| <span class="java-quote">"author"</span>:<span class="java-quote">"Stephen King"</span>, |
| <span class="java-quote">"title"</span>:<span class="java-quote">"The Stand"</span>}, |
| {<span class="java-quote">"id"</span>:2, |
| <span class="java-quote">"class"</span>:<span class="java-quote">"Book"</span>, |
| <span class="java-quote">"author"</span>:<span class="java-quote">"Stephen King"</span>, |
| <span class="java-quote">"releaseDate"</span>:<span class="java-keyword">new</span> Date(1194127343161), |
| <span class="java-quote">"title"</span>:<span class="java-quote">"The Shining"</span>} |
| ]</pre></div><p class="paragraph"/>Again as an alternative you can use the <code>encodeAsJSON</code> to achieve the same effect.<h2><a name="6.1.8 More on JSONBuilder">6.1.8 More on JSONBuilder</a></h2>The previous section on on XML and JSON responses covered simplistic examples of rendering XML and JSON responses. Whilst the XML builder used by Grails is the standard <a href="http://groovy.codehaus.org/Reading+XML+using+Groovy's+XmlSlurper" target="blank">XmlSlurper</a> found in Groovy, the JSON builder is a custom implementation specific to Grails.<p class="paragraph"/><h4>JSONBuilder and Grails versions</h4><p class="paragraph"/>JSONBuilder behaves different depending on the version of Grails you use. For version below 1.2 there deprecated <a href="../api/grails/util/JSonBuilder.html" class="api">grails.util.JSonBuilder</a> class is used. This section covers the usage of the Grails 1.2 JSONBuilder<p class="paragraph"/>For backwards compatibility the old <code>JSonBuilder</code> class is used with the <code>render</code> method for older applications, if you want to use the newer/better <code>JSONBuilder</code> class then you can do so by setting the following in <code>Config.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.json.legacy.builder=<span class="java-keyword">false</span></pre></div><p class="paragraph"/> |
| <h4>Rendering Simple Objects</h4><p class="paragraph"/>To render a simple JSON object just set properties within the context of the closure:<p class="paragraph"/><div class="code"><pre>render(contentType:<span class="java-quote">"text/json"</span>) { |
| hello = <span class="java-quote">"world"</span> |
| }</pre></div><p class="paragraph"/>The above will produce the JSON:<p class="paragraph"/><div class="code"><pre>{<span class="java-quote">"hello"</span>:<span class="java-quote">"world"</span>}</pre></div><p class="paragraph"/><h4>Rendering JSON Arrays</h4><p class="paragraph"/>To render a list of objects simple assign a list:<p class="paragraph"/><div class="code"><pre>render(contentType:<span class="java-quote">"text/json"</span>) { |
| categories = ['a', 'b', 'c'] |
| }</pre></div><p class="paragraph"/>This will produce:<p class="paragraph"/><div class="code"><pre>{<span class="java-quote">"categories"</span>:[<span class="java-quote">"a"</span>,<span class="java-quote">"b"</span>,<span class="java-quote">"c"</span>]}</pre></div><p class="paragraph"/>You can also render lists of complex objects, for example:<p class="paragraph"/><div class="code"><pre>render(contentType:<span class="java-quote">"text/json"</span>) { |
| categories = [ { a = <span class="java-quote">"A"</span> }, { b = <span class="java-quote">"B"</span> } ] |
| }</pre></div><p class="paragraph"/>This will produce:<p class="paragraph"/><div class="code"><pre>{<span class="java-quote">"categories"</span>:[ {<span class="java-quote">"a"</span>:<span class="java-quote">"A"</span>} , {<span class="java-quote">"b"</span>:<span class="java-quote">"B"</span>}] }</pre></div><p class="paragraph"/>If you want to return a list as the root then you have to use the special <code>element</code> method:<p class="paragraph"/><div class="code"><pre>render(contentType:<span class="java-quote">"text/json"</span>) { |
| element 1 |
| element 2 |
| element 3 |
| }</pre></div><p class="paragraph"/>The above code produces:<p class="paragraph"/><div class="code"><pre>[1,2,3]</pre></div><p class="paragraph"/><h4>Rendering Complex Objects</h4><p class="paragraph"/>Rendering complex objects can be done with closures. For example:<p class="paragraph"/><div class="code"><pre>render(contentType:<span class="java-quote">"text/json"</span>) { |
| categories = ['a', 'b', 'c'] |
| title =<span class="java-quote">"Hello JSON"</span> |
| information = { |
| pages = 10 |
| } |
| }</pre></div><p class="paragraph"/>The above will produce the JSON:<p class="paragraph"/><div class="code"><pre>{<span class="java-quote">"categories"</span>:[<span class="java-quote">"a"</span>,<span class="java-quote">"b"</span>,<span class="java-quote">"c"</span>],<span class="java-quote">"title"</span>:<span class="java-quote">"Hello JSON"</span>,<span class="java-quote">"information"</span>:{<span class="java-quote">"pages"</span>:10}}</pre></div><p class="paragraph"/><h4>Arrays of Complex Objects</h4><p class="paragraph"/>As mentioned previously you can nest complex objects within arrays using closures:<p class="paragraph"/><div class="code"><pre>render(contentType:<span class="java-quote">"text/json"</span>) { |
| categories = [ { a = <span class="java-quote">"A"</span> }, { b = <span class="java-quote">"B"</span> } ] |
| }</pre></div><p class="paragraph"/>However, if you need to build them up dynamically then you may want to use the <code>array</code> method:<p class="paragraph"/><div class="code"><pre>def results = Book.list() |
| render(contentType:<span class="java-quote">"text/json"</span>) { |
| books = array { |
| <span class="java-keyword">for</span>(b in results) { |
| book title:b.title |
| } |
| } |
| }</pre></div><p class="paragraph"/><h4>Direct JSONBuilder API Access</h4><p class="paragraph"/>If you don't have access to the <code>render</code> method, but still want to produce JSON you can use the API directly:<p class="paragraph"/><div class="code"><pre>def builder = <span class="java-keyword">new</span> JSONBuilder()<p class="paragraph"/>def result = builder.build { |
| categories = ['a', 'b', 'c'] |
| title =<span class="java-quote">"Hello JSON"</span> |
| information = { |
| pages = 10 |
| } |
| }<p class="paragraph"/>// prints the JSON text |
| println result.toString()<p class="paragraph"/>def sw = <span class="java-keyword">new</span> StringWriter() |
| result.render sw</pre></div><p class="paragraph"/><h2><a name="6.1.9 Uploading Files">6.1.9 Uploading Files</a></h2><h4>Programmatic File Uploads</h4><p class="paragraph"/>Grails supports file uploads via Spring's <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/multipart/MultipartHttpServletRequest.html" class="api">MultipartHttpServletRequest</a> interface. To upload a file the first step is to create a multipart form like the one below:<p class="paragraph"/><div class="code"><pre>Upload Form: <span class="xml-tag"><br /></span> |
| <span class="xml-tag"><g:form action=<span class="xml-quote">"upload"</span> method=<span class="xml-quote">"post"</span> enctype=<span class="xml-quote">"multipart/form-data"</span>></span> |
| <span class="xml-tag"><input type=<span class="xml-quote">"file"</span> name=<span class="xml-quote">"myFile"</span> /></span> |
| <span class="xml-tag"><input type=<span class="xml-quote">"submit"</span> /></span> |
| <span class="xml-tag"></g:form></span></pre></div><p class="paragraph"/> |
| There are then a number of ways to handle the file upload. The first way is to work with the Spring <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/multipart/MultipartFile.html" class="api">MultipartFile</a> instance directly:<p class="paragraph"/><div class="code"><pre>def upload = { |
| def f = request.getFile('myFile') |
| <span class="java-keyword">if</span>(!f.empty) { |
| f.transferTo( <span class="java-keyword">new</span> File('/some/local/dir/myfile.txt') ) |
| response.sendError(200,'Done'); |
| } |
| <span class="java-keyword">else</span> { |
| flash.message = 'file cannot be empty' |
| render(view:'uploadForm') |
| } |
| }</pre></div><p class="paragraph"/><p class="paragraph"/>This is clearly handy for doing transfers to other destinations and manipulating the file directly as you can obtain an InputStream and so on via the <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/multipart/MultipartFile.html" class="api">MultipartFile</a> interface.<p class="paragraph"/><h4>File Uploads through Data Binding</h4><p class="paragraph"/>File uploads can also be performed via data binding. For example say you have an <code>Image</code> domain class as per the below example:<p class="paragraph"/><div class="code"><pre>class Image { |
| <span class="java-object">byte</span>[] myFile |
| }</pre></div><p class="paragraph"/>Now if you create an image and pass in the <code>params</code> object such as the below example, Grails will automatically bind the file's contents as a byte to the <code>myFile</code> property:<p class="paragraph"/><div class="code"><pre>def img = <span class="java-keyword">new</span> Image(params)</pre></div><p class="paragraph"/>It is also possible to set the contents of the file as a string by changing the type of the <code>myFile</code> property on the image to a String type:<p class="paragraph"/><div class="code"><pre>class Image { |
| <span class="java-object">String</span> myFile |
| }</pre></div><p class="paragraph"/><h2><a name="6.1.10 Command Objects">6.1.10 Command Objects</a></h2>Grails controllers support the concept of command objects. A command object is similar to a form bean in something like Struts and they are useful in circumstances when you want to populate a subset of the properties needed to update a domain class. Or where there is no domain class required for the interaction, but you need features such as <a href="../guide/single.html#6.1.6 Data Binding" class="guide">data binding</a> and <a href="../guide/single.html#7. Validation" class="guide">validation</a>.<p class="paragraph"/><h4>Declaring Command Objects</h4><p class="paragraph"/>Command objects are typically declared in the same source file as a controller directly below the controller class definition. For example:<p class="paragraph"/><div class="code"><pre>class UserController { |
| … |
| } |
| class LoginCommand { |
| <span class="java-object">String</span> username |
| <span class="java-object">String</span> password |
| <span class="java-keyword">static</span> constraints = { |
| username(blank:<span class="java-keyword">false</span>, minSize:6) |
| password(blank:<span class="java-keyword">false</span>, minSize:6) |
| } |
| }</pre></div><p class="paragraph"/>As the previous example demonstrates you can supply <a href="../guide/single.html#7.1 Declaring Constraints" class="guide">constraints</a> to command objects just as you can with <a href="../guide/single.html#5. Object Relational Mapping (GORM)" class="guide">domain classes</a>.<p class="paragraph"/><h4>Using Command Objects</h4><p class="paragraph"/>To use command objects, controller actions may optionally specify any number of command object parameters. The parameter types must be supplied so that Grails knows what objects to create, populate and validate.<p class="paragraph"/>Before the controller action is executed Grails will automatically create an instance of the command object class, populate the properties of the command object with request parameters having corresponding names and the command object will be validated. For Example:<p class="paragraph"/><div class="code"><pre>class LoginController { |
| def login = { LoginCommand cmd -> |
| <span class="java-keyword">if</span>(cmd.hasErrors()) { |
| redirect(action:'loginForm') |
| } |
| <span class="java-keyword">else</span> { |
| // <span class="java-keyword">do</span> something <span class="java-keyword">else</span> |
| } |
| } |
| }</pre></div><p class="paragraph"/><h4>Command Objects and Dependency Injection</h4><p class="paragraph"/>Command objects can participate in dependency injection. This is useful if your command object has some custom validation logic which may need to interact with Grails <a href="../guide/single.html#8. The Service Layer" class="guide">services</a>:<p class="paragraph"/><div class="code"><pre>class LoginCommand { |
| def loginService<p class="paragraph"/> <span class="java-object">String</span> username |
| <span class="java-object">String</span> password<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| username validator: { val, obj -> |
| obj.loginService.canLogin(obj.username, obj.password) |
| } |
| } |
| }</pre></div><p class="paragraph"/>In this example the command object interacts with a bean injected by name from the Spring <code>ApplicationContext</code>.<p class="paragraph"/> |
| <h2><a name="6.1.11 Handling Duplicate Form Submissions">6.1.11 Handling Duplicate Form Submissions</a></h2>Grails has built in support for handling duplicate form submissions using the "Synchronizer Token Pattern". To get started you need to define a token on the <a href="../ref/Tags/form.html" class="tags">form</a> tag:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:form useToken=<span class="xml-quote">"true"</span> ...></span></pre></div><p class="paragraph"/>Then in your controller code you can use the <a href="../ref/Controllers/withForm.html" class="controllers">withForm</a> method to handle valid and invalid requests:<p class="paragraph"/><div class="code"><pre>withForm { |
| // good request |
| }.invalidToken { |
| // bad request |
| }</pre></div><p class="paragraph"/>If you only provide the <a href="../ref/Controllers/withForm.html" class="controllers">withForm</a> method and not the chained <code>invalidToken</code> method then by default Grails will store the invalid token in a <code>flash.invalidToken</code> variable and redirect the request back to the original page. This can then be checked in the view:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:if test=<span class="xml-quote">"${flash.invalidToken}"</span>></span> |
| Don't click the button twice! |
| <span class="xml-tag"></g:if></span></pre></div><p class="paragraph"/><blockquote class="warning"> |
| The <a href="../ref/Controllers/withForm.html" class="controllers">withForm</a> tag makes use of the <a href="../ref/Controllers/session.html" class="controllers">session</a> and hence requires session affinity if used in a cluster. |
| </blockquote><h2><a name="6.1.12 Simple Type Converters">6.1.12 Simple Type Converters</a></h2><h3>Type Conversion Methods</h3><p class="paragraph"/>If you prefer to avoid the overhead of <a href="../guide/single.html#6.1.6 Data Binding" class="guide">Data Binding</a> and simply want to convert incoming parameters (typically Strings) into another more appropriate type the <a href="../ref/Controllers/params.html" class="controllers">params</a> object has a number of convenience methods for each type:<p class="paragraph"/><div class="code"><pre>def total = params.<span class="java-object">int</span>('total')</pre></div><p class="paragraph"/>The above example uses the <code>int</code> method, there are also methods for <code>boolean</code>, <code>long</code>, <code>char</code>, <code>short</code> and so on. Each of these methods are null safe and safe from any parsing errors so you don't have to perform any addition checks on the parameters.<p class="paragraph"/>These same type conversion methods are also available on the <code>attrs</code> parameter of GSP tags.<p class="paragraph"/><h3>Handling Multi Parameters</h3><p class="paragraph"/>A common use case is dealing with multiple request parameters of the same name. For example you could get a query string such as <code>?name=Bob&name=Judy</code>.<p class="paragraph"/>In this case dealing with 1 parameter and dealing with many has different semantics since Groovy's iteration mechanics for <code>String</code> iterate over each character. To avoid this problem the <a href="../ref/Controllers/params.html" class="controllers">params</a> object provides a <code>list</code> method that always returns a list:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">for</span>(name in params.list('name')) { |
| println name |
| }</pre></div><p class="paragraph"/> |
| <h2><a name="6.2 Groovy Server Pages">6.2 Groovy Server Pages</a></h2>Groovy Servers Pages (or GSP for short) is Grails' view technology. It is designed to be familiar for users of technologies such as ASP and JSP, but to be far more flexible and intuitive.<p class="paragraph"/>In Grails GSPs live in the <code>grails-app/views</code> directory and are typically rendered automatically (by convention) or via the <a href="../ref/Controllers/render.html" class="controllers">render</a> method such as:<p class="paragraph"/><div class="code"><pre>render(view:<span class="java-quote">"index"</span>)</pre></div><p class="paragraph"/>A GSP is typically a mix of mark-up and GSP tags which aid in view rendering.<p class="paragraph"/><blockquote class="note"> |
| Although it is possible to have Groovy logic embedded in your GSP and doing this will be covered in this document the practice is strongly discouraged. Mixing mark-up and code is a <strong class="bold">bad</strong> thing and most GSP pages contain no code and needn't do so. |
| </blockquote><p class="paragraph"/>A GSP typically has a "model" which is a set of variables that are used for view rendering. The model is passed to the GSP view from a controller. For example consider the following controller action:<p class="paragraph"/><div class="code"><pre>def show = { |
| [book: Book.get(params.id)] |
| }</pre></div><p class="paragraph"/>This action will look-up a <code>Book</code> instance and create a model that contains a key called <code>book</code>. This key can then be reference within the GSP view using the name <code>book</code>:<p class="paragraph"/><div class="code"><pre><%=book.title%></pre></div> |
| <h2><a name="6.2.1 GSP Basics">6.2.1 GSP Basics</a></h2>In the next view sections we'll go through the basics of GSP and what is available to you. First off let's cover some basic syntax that users of JSP and ASP should be familiar with.<p class="paragraph"/>GSP supports the usage of <code><% %></code> blocks to embed Groovy code (again this is discouraged):<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><html></span> |
| <span class="xml-tag"><body></span> |
| <span class="xml-tag"><% out << <span class="xml-quote">"Hello GSP!"</span> %></span> |
| <span class="xml-tag"></body></span> |
| <span class="xml-tag"></html></span></pre></div><p class="paragraph"/>As well as this syntax you can also use the <code><%= %></code> syntax to output values:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><html></span> |
| <span class="xml-tag"><body></span> |
| <span class="xml-tag"><%=<span class="xml-quote">"Hello GSP!"</span> %></span> |
| <span class="xml-tag"></body></span> |
| <span class="xml-tag"></html></span></pre></div><p class="paragraph"/> |
| GSP also supports JSP-style server-side comments as the following example demonstrates:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><html></span> |
| <span class="xml-tag"><body></span> |
| <span class="xml-tag"><%-- This is my comment --%></span> |
| <span class="xml-tag"><%=<span class="xml-quote">"Hello GSP!"</span> %></span> |
| <span class="xml-tag"></body></span> |
| <span class="xml-tag"></html></span></pre></div> |
| <h2><a name="6.2.1.1 Variables and Scopes">6.2.1.1 Variables and Scopes</a></h2>Within the <code><% %></code> brackets you can of course declare variables:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><% now = new Date() %></span></pre></div><p class="paragraph"/>And then re-use those variables further down the page:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><%=now%></span></pre></div><p class="paragraph"/>However, within the scope of a GSP there are a number of pre-defined variables including: |
| <ul class="star"> |
| <li><code>application</code> - The <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/ServletContext.html" class="api">javax.servlet.ServletContext</a> instance</li> |
| <li><code>applicationContext</code> The Spring <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/ApplicationContext.html" class="api">ApplicationContext</a> instance</li> |
| <li><code>flash</code> - The <a href="../ref/Controllers/flash.html" class="controllers">flash</a> object</li> |
| <li><code>grailsApplication</code> - The <a href="../api/org/codehaus/groovy/grails/commons/GrailsApplication.html" class="api">GrailsApplication</a> instance</li> |
| <li><code>out</code> - The response writer for writing to the output stream</li> |
| <li><code>params</code> - The <a href="../ref/Controllers/params.html" class="controllers">params</a> object for retrieving request parameters</li> |
| <li><code>request</code> - The <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletRequest.html" class="api">HttpServletRequest</a> instance</li> |
| <li><code>response</code> - The <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletResponse.html" class="api">HttpServletResponse</a> instance</li> |
| <li><code>session</code> - The <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpSession.html" class="api">HttpSession</a> instance</li> |
| <li><code>webRequest</code> - The <a href="../api/org/codehaus/groovy/grails/web/servlet/mvc/GrailsWebRequest.html" class="api">GrailsWebRequest</a> instance</li> |
| </ul><p class="paragraph"/><h2><a name="6.2.1.2 Logic and Iteration">6.2.1.2 Logic and Iteration</a></h2>Using the <code><% %></code> syntax you can of course embed loops and so on using this syntax:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><html></span> |
| <span class="xml-tag"><body></span> |
| <span class="xml-tag"><% [1,2,3,4].each { num -></span> %> |
| <span class="xml-tag"><p></span><span class="xml-tag"><%=<span class="xml-quote">"Hello ${num}!"</span> %></span><span class="xml-tag"></p></span> |
| <span class="xml-tag"><%}%></span> |
| <span class="xml-tag"></body></span> |
| <span class="xml-tag"></html></span></pre></div><p class="paragraph"/>As well as logical branching:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><html></span> |
| <span class="xml-tag"><body></span> |
| <span class="xml-tag"><% if(params.hello == 'true' )%></span> |
| <span class="xml-tag"><%=<span class="xml-quote">"Hello!"</span>%></span> |
| <span class="xml-tag"><% else %></span> |
| <span class="xml-tag"><%=<span class="xml-quote">"Goodbye!"</span>%></span> |
| <span class="xml-tag"></body></span> |
| <span class="xml-tag"></html></span></pre></div><h2><a name="6.2.1.3 Page Directives">6.2.1.3 Page Directives</a></h2>GSP also supports a few JSP-style page directives.<p class="paragraph"/>The import directive allows you to import classes into the page. However, it is rarely needed due to Groovy's default imports and <a href="../guide/single.html#6.2.2 GSP Tags" class="guide">GSP Tags</a>:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><%@ page import=<span class="xml-quote">"java.awt.*"</span> %></span></pre></div><p class="paragraph"/>GSP also supports the contentType directive:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><%@ page contentType=<span class="xml-quote">"text/json"</span> %></span></pre></div><p class="paragraph"/>The contentType directive allows using GSP to render other formats. |
| <h2><a name="6.2.1.4 Expressions">6.2.1.4 Expressions</a></h2>In GSP the <code><%= %></code> syntax introduced earlier is rarely used due to the support for GSP expressions. It is present mainly to allow ASP and JSP developers to feel at home using GSP. A GSP expression is similar to a JSP EL expression or a Groovy GString and takes the form <code>${expr}</code>:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><html></span> |
| <span class="xml-tag"><body></span> |
| Hello ${params.name} |
| <span class="xml-tag"></body></span> |
| <span class="xml-tag"></html></span></pre></div><p class="paragraph"/>However, unlike JSP EL you can have any Groovy expression within the <code>${..}</code> parenthesis. Variables within the <code>${..}</code> are <strong class="bold">not</strong> escaped by default, so any HTML in the variable's string is output directly to the page. To reduce the risk of Cross-site-scripting (XSS) attacks, you can enable automatic HTML escaping via the <code>grails.views.default.codec</code> setting in <code>grails-app/conf/Config.groovy</code>:<p class="paragraph"/><div class="code"><pre>grails.views.<span class="java-keyword">default</span>.codec='html'</pre></div><p class="paragraph"/>Other possible values are 'none' (for no default encoding) and 'base64'. |
| <h2><a name="6.2.2 GSP Tags">6.2.2 GSP Tags</a></h2>Now that the less attractive JSP heritage has been set aside, the following sections cover GSP's built-in tags, which are the favored way to define GSP pages.<p class="paragraph"/><blockquote class="note"> |
| The section on <a href="../guide/single.html#6.3 Tag Libraries" class="guide">Tag Libraries</a> covers how to add your own custom tag libraries. |
| </blockquote><p class="paragraph"/>All built-in GSP tags start with the prefix <code>g:</code>. Unlike JSP, you don't need to specify any tag library imports. If a tag starts with <code>g:</code> it is automatically assumed to be a GSP tag. An example GSP tag would look like:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:example /></span></pre></div><p class="paragraph"/>GSP tags can also have a body such as:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:example></span> |
| Hello world |
| <span class="xml-tag"></g:example></span></pre></div><p class="paragraph"/>Expressions can be passed into GSP tag attributes, if an expression is not used it will be assumed to be a String value:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:example attr=<span class="xml-quote">"${new Date()}"</span>></span> |
| Hello world |
| <span class="xml-tag"></g:example></span></pre></div><p class="paragraph"/>Maps can also be passed into GSP tag attributes, which are often used for a named parameter style syntax:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:example attr=<span class="xml-quote">"${new Date()}"</span> attr2=<span class="xml-quote">"[one:1, two:2, three:3]"</span>></span> |
| Hello world |
| <span class="xml-tag"></g:example></span></pre></div><p class="paragraph"/>Note that within the values of attributes you must use single quotes for Strings:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:example attr=<span class="xml-quote">"${new Date()}"</span> attr2=<span class="xml-quote">"[one:'one', two:'two']"</span>></span> |
| Hello world |
| <span class="xml-tag"></g:example></span></pre></div><p class="paragraph"/>With the basic syntax out the way, the next sections look at the tags that are built into Grails by default.<p class="paragraph"/><h2><a name="6.2.2.1 Variables and Scopes">6.2.2.1 Variables and Scopes</a></h2>Variables can be defined within a GSP using the <a href="../ref/Tags/set.html" class="tags">set</a> tag:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:set var=<span class="xml-quote">"now"</span> value=<span class="xml-quote">"${new Date()}"</span> /></span></pre></div><p class="paragraph"/>Here we assign a variable called <code>now</code> to the result of a GSP expression (which simply constructs a new <code>java.util.Date</code> instance). You can also use the body of the <code><g:set></code> tag to define a variable:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:set var=<span class="xml-quote">"myHTML"</span>></span> |
| Some re-usable code on: ${new Date()} |
| <span class="xml-tag"></g:set></span></pre></div><p class="paragraph"/>Variables can also be placed in one of the following scopes: |
| <ul class="star"> |
| <li><code>page</code> - Scoped to the current page (default)</li> |
| <li><code>request</code> - Scoped to the current request</li> |
| <li><code>flash</code> - Placed within <a href="../ref/Controllers/flash.html" class="controllers">flash</a> scope and hence available for the next request</li> |
| <li><code>session</code> - Scoped for the user session</li> |
| <li><code>application</code> - Application-wide scope.</li> |
| </ul><p class="paragraph"/>To select which scope a variable is placed into use the <code>scope</code> attribute:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:set var=<span class="xml-quote">"now"</span> value=<span class="xml-quote">"${new Date()}"</span> scope=<span class="xml-quote">"request"</span> /></span></pre></div><h2><a name="6.2.2.2 Logic and Iteration">6.2.2.2 Logic and Iteration</a></h2>GSP also supports logical and iterative tags out of the box. For logic there are <a href="../ref/Tags/if.html" class="tags">if</a>, <a href="../ref/Tags/else.html" class="tags">else</a> and <a href="../ref/Tags/elseif.html" class="tags">elseif</a> which support your typical branching scenarios:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:if test=<span class="xml-quote">"${session.role == 'admin'}"</span>></span> |
| <span class="xml-tag"><%-- show administrative functions --%></span> |
| <span class="xml-tag"></g:if></span> |
| <span class="xml-tag"><g:else></span> |
| <span class="xml-tag"><%-- show basic functions --%></span> |
| <span class="xml-tag"></g:else></span></pre></div><p class="paragraph"/>For iteration GSP has the <a href="../ref/Tags/each.html" class="tags">each</a> and <a href="../ref/Tags/while.html" class="tags">while</a> tags:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:each in=<span class="xml-quote">"${[1,2,3]}"</span> var=<span class="xml-quote">"num"</span>></span> |
| <span class="xml-tag"><p></span>Number ${num}<span class="xml-tag"></p></span> |
| <span class="xml-tag"></g:each></span><p class="paragraph"/><span class="xml-tag"><g:set var=<span class="xml-quote">"num"</span> value=<span class="xml-quote">"${1}"</span> /></span> |
| <span class="xml-tag"><g:while test=<span class="xml-quote">"${num < 5 }"</span>></span> |
| <span class="xml-tag"><p></span>Number ${num++}<span class="xml-tag"></p></span> |
| <span class="xml-tag"></g:while></span></pre></div><h2><a name="6.2.2.3 Search and Filtering">6.2.2.3 Search and Filtering</a></h2>If you have collections of objects you often need to sort and filter them in some way. GSP supports the <a href="../ref/Tags/findAll.html" class="tags">findAll</a> and <a href="../ref/Tags/grep.html" class="tags">grep</a> for this task:<p class="paragraph"/><div class="code"><pre>Stephen King's Books: |
| <span class="xml-tag"><g:findAll in=<span class="xml-quote">"${books}"</span> expr=<span class="xml-quote">"it.author == 'Stephen King'"</span>></span> |
| <span class="xml-tag"><p></span>Title: ${it.title}<span class="xml-tag"></p></span> |
| <span class="xml-tag"></g:findAll></span></pre></div><p class="paragraph"/>The <code>expr</code> attribute contains a Groovy expression that can be used as a filter. Speaking of filters the <a href="../ref/Tags/grep.html" class="tags">grep</a> tag does a similar job such as filter by class:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:grep in=<span class="xml-quote">"${books}"</span> filter=<span class="xml-quote">"NonFictionBooks.class"</span>></span> |
| <span class="xml-tag"><p></span>Title: ${it.title}<span class="xml-tag"></p></span> |
| <span class="xml-tag"></g:grep></span></pre></div><p class="paragraph"/>Or using a regular expression:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:grep in=<span class="xml-quote">"${books.title}"</span> filter=<span class="xml-quote">"~/.*?Groovy.*?/"</span>></span> |
| <span class="xml-tag"><p></span>Title: ${it}<span class="xml-tag"></p></span> |
| <span class="xml-tag"></g:grep></span></pre></div><p class="paragraph"/>The above example is also interesting due to its usage of GPath. GPath is Groovy's equivalent to an XPath like language. Essentially the <code>books</code> collection is a collection of <code>Book</code> instances. However assuming each <code>Book</code> has a <code>title</code>, you can obtain a list of Book titles using the expression <code>books.title</code>. Groovy will auto-magically go through the list of Book instances, obtain each title, and return a new list!<h2><a name="6.2.2.4 Links and Resources">6.2.2.4 Links and Resources</a></h2>GSP also features tags to help you manage linking to controllers and actions. The <a href="../ref/Tags/link.html" class="tags">link</a> tag allows you to specify controller and action name pairing and it will automatically work out the link based on the <a href="../guide/single.html#6.4 URL Mappings" class="guide">URL Mappings</a>, even if you change them! Some examples of the <a href="../ref/Tags/link.html" class="tags">link</a> can be seen below:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:link action=<span class="xml-quote">"show"</span> id=<span class="xml-quote">"1"</span>></span>Book 1<span class="xml-tag"></g:link></span> |
| <span class="xml-tag"><g:link action=<span class="xml-quote">"show"</span> id=<span class="xml-quote">"${currentBook.id}"</span>></span>${currentBook.name}<span class="xml-tag"></g:link></span> |
| <span class="xml-tag"><g:link controller=<span class="xml-quote">"book"</span>></span>Book Home<span class="xml-tag"></g:link></span> |
| <span class="xml-tag"><g:link controller=<span class="xml-quote">"book"</span> action=<span class="xml-quote">"list"</span>></span>Book List<span class="xml-tag"></g:link></span> |
| <span class="xml-tag"><g:link url=<span class="xml-quote">"[action:'list',controller:'book']"</span>></span>Book List<span class="xml-tag"></g:link></span> |
| <span class="xml-tag"><g:link action=<span class="xml-quote">"list"</span> params=<span class="xml-quote">"[sort:'title',order:'asc',author:currentBook.author]"</span>></span> |
| Book List |
| <span class="xml-tag"></g:link></span></pre></div> |
| <h2><a name="6.2.2.5 Forms and Fields">6.2.2.5 Forms and Fields</a></h2><h4>Form Basics</h4><p class="paragraph"/>GSP supports many different tags for aiding in dealing with HTML forms and fields, the most basic of which is the <a href="../ref/Tags/form.html" class="tags">form</a> tag. The <code>form</code> tag is a controller/action aware version of the regular HTML form tag. The <code>url</code> attribute allows you to specify which controller and action to map to:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:form name=<span class="xml-quote">"myForm"</span> url=<span class="xml-quote">"[controller:'book',action:'list']"</span>></span>...<span class="xml-tag"></g:form></span></pre></div><p class="paragraph"/>In this case we create a form called <code>myForm</code> that submits to the <code>BookController</code>'s <code>list</code> action. Beyond that all of the usual HTML attributes apply.<p class="paragraph"/><h4>Form Fields</h4><p class="paragraph"/>As well as easy construction of forms GSP supports custom tags for dealing with different types of fields including: |
| <ul class="star"> |
| <li><a href="../ref/Tags/textField.html" class="tags">textField</a> - For input fields of type 'text'</li> |
| <li><a href="../ref/Tags/checkBox.html" class="tags">checkBox</a> - For input fields of type 'checkbox'</li> |
| <li><a href="../ref/Tags/radio.html" class="tags">radio</a> - For input fields of type 'radio'</li> |
| <li><a href="../ref/Tags/hiddenField.html" class="tags">hiddenField</a> - For input fields of type 'hidden'</li> |
| <li><a href="../ref/Tags/select.html" class="tags">select</a> - For dealing with HTML select boxes</li> |
| </ul><p class="paragraph"/>Each of these allow GSP expressions as the value:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:textField name=<span class="xml-quote">"myField"</span> value=<span class="xml-quote">"${myValue}"</span> /></span></pre></div><p class="paragraph"/>GSP also contains extended helper versions of the above tags such as <a href="../ref/Tags/radioGroup.html" class="tags">radioGroup</a> (for creating groups of <a href="../ref/Tags/radio.html" class="tags">radio</a> tags), <a href="../ref/Tags/localeSelect.html" class="tags">localeSelect</a>, <a href="../ref/Tags/currencySelect.html" class="tags">currencySelect</a> and <a href="../ref/Tags/timeZoneSelect.html" class="tags">timeZoneSelect</a> (for selecting locale's, currencies and time zone's respectively).<p class="paragraph"/><h4>Multiple Submit Buttons</h4><p class="paragraph"/>The age old problem of dealing with multiple submit buttons is also handled elegantly with Grails via the <a href="../ref/Tags/actionSubmit.html" class="tags">actionSubmit</a> tag. It is just like a regular submit, but allows you to specify an alternative action to submit to:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:actionSubmit value=<span class="xml-quote">"Some update label"</span> action=<span class="xml-quote">"update"</span> /></span></pre></div><p class="paragraph"/><h2><a name="6.2.2.6 Tags as Method Calls">6.2.2.6 Tags as Method Calls</a></h2>One major different between GSP tags and other tagging technologies is that GSP tags can be called as either regular tags or as method calls from either <a href="../guide/single.html#6.1 Controllers" class="guide">controllers</a>, <a href="../guide/single.html#6.3 Tag Libraries" class="guide">tag libraries</a> or GSP views.<p class="paragraph"/><h4>Tags as method calls from GSPs</h4><p class="paragraph"/>When called as methods tags return their results as a String instead of writing directly to the response. So for example the <a href="../ref/Tags/createLinkTo.html" class="tags">createLinkTo</a> tag can equally be called as a method:<p class="paragraph"/><div class="code"><pre>Static Resource: ${createLinkTo(dir:<span class="xml-quote">"images"</span>, file:<span class="xml-quote">"logo.jpg"</span>)}</pre></div><p class="paragraph"/>This is particularly useful when you need to use a tag within an attribute:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><img src=<span class="xml-quote">"${createLinkTo(dir:'images', file:'logo.jpg')}"</span> /></span></pre></div><p class="paragraph"/>In view technologies that don't support this feature you have to nest tags within tags, which becomes messy quickly and often has an adverse effect of WYSWIG tools such as Dreamweaver that attempt to render the mark-up as it is not well-formed:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><img src=<span class="xml-quote">"<g:createLinkTo dir="</span>images<span class="xml-quote">" file="</span>logo.jpg<span class="xml-quote">" /></span>"</span> /></pre></div><p class="paragraph"/><h4>Tags as method calls from Controllers and Tag Libraries</h4><p class="paragraph"/>You can also invoke tags from controllers and tag libraries. Tags within the default <code>g:</code> <a href="../guide/single.html#6.3.5 Tag Namespaces" class="guide">namespace</a> can be invoked without the prefix and a String result is returned:<p class="paragraph"/><div class="code"><pre>def imageLocation = createLinkTo(dir:<span class="java-quote">"images"</span>, file:<span class="java-quote">"logo.jpg"</span>)</pre></div><p class="paragraph"/>However, you can also prefix the namespace to avoid naming conflicts:<p class="paragraph"/><div class="code"><pre>def imageLocation = g.createLinkTo(dir:<span class="java-quote">"images"</span>, file:<span class="java-quote">"logo.jpg"</span>)</pre></div><p class="paragraph"/>If you have a <a href="../guide/single.html#6.3.5 Tag Namespaces" class="guide">custom namespace</a> you can use that prefix instead (Example using the <a href="http://grails.org/FCK+editor+plugin" target="blank">FCK Editor plugin</a>):<p class="paragraph"/><div class="code"><pre>def editor = fck.editor()</pre></div><p class="paragraph"/><p class="paragraph"/><h2><a name="6.2.3 Views and Templates">6.2.3 Views and Templates</a></h2>As well as views, Grails has the concept of templates. Templates are useful for separating out your views into maintainable chunks and combined with <a href="../guide/single.html#6.2.4 Layouts with Sitemesh" class="guide">Layouts</a> provide a highly re-usable mechanism for structure views.<p class="paragraph"/><h4>Template Basics</h4><p class="paragraph"/>Grails uses the convention of placing an underscore before the name of a view to identify it as a template. For example a you may have a template that deals with rendering Books located at <code>grails-app/views/book/_bookTemplate.gsp</code>:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><div class=<span class="xml-quote">"book"</span> id=<span class="xml-quote">"${book?.id}"</span>></span> |
| <span class="xml-tag"><div></span>Title: ${book?.title}<span class="xml-tag"></div></span> |
| <span class="xml-tag"><div></span>Author: ${book?.author?.name}<span class="xml-tag"></div></span> |
| <span class="xml-tag"></div></span></pre></div><p class="paragraph"/>To render this template from one of the views in <code>grails-app/views/book</code> you can use the <a href="../ref/Tags/render.html" class="tags">render</a> tag:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:render template=<span class="xml-quote">"bookTemplate"</span> model=<span class="xml-quote">"[book:myBook]"</span> /></span></pre></div><p class="paragraph"/>Notice how we pass into a model to use using the <code>model</code> attribute of the render tag. If you have multiple <code>Book</code> instances you can also render the template for each <code>Book</code> using the render tag:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:render template=<span class="xml-quote">"bookTemplate"</span> var=<span class="xml-quote">"book"</span> collection=<span class="xml-quote">"${bookList}"</span> /></span></pre></div><p class="paragraph"/><h4>Shared Templates</h4><p class="paragraph"/>In the previous example we had a template that was specific to the <code>BookController</code> and its views at <code>grails-app/views/book</code>. However, you may want to share templates across your application.<p class="paragraph"/>In this case you can place them in the root views directory at grails-app/views or any subdirectory below that location and then with the template attribute use a <code>/</code> before the template name to indicate the relative template path. For example if you had a template called <code>grails-app/views/shared/_mySharedTemplate.gsp</code>, you could reference it as follows:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:render template=<span class="xml-quote">"/shared/mySharedTemplate"</span> /></span></pre></div><p class="paragraph"/>You can also use this technique to reference templates in any directory from any view or controller:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:render template=<span class="xml-quote">"/book/bookTemplate"</span> model=<span class="xml-quote">"[book:myBook]"</span> /></span></pre></div><p class="paragraph"/><h4>The Template Namespace</h4><p class="paragraph"/>Since templates are used so frequently there is template namespace, called <code>tmpl</code>, available that makes using templates easier. Consider for example the following usage pattern:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:render template=<span class="xml-quote">"bookTemplate"</span> model=<span class="xml-quote">"[book:myBook]"</span> /></span></pre></div><p class="paragraph"/>This can be expressed with the <code>tmpl</code> namespace as follows:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><tmpl:bookTemplate book=<span class="xml-quote">"${myBook}"</span> /></span></pre></div><p class="paragraph"/><h4>Templates in Controllers and Tag Libraries</h4><p class="paragraph"/>You can also render templates from controllers using the <a href="../ref/Controllers/render.html" class="controllers">render</a> method found within controllers, which is useful for <a href="../guide/single.html#6.7 Ajax" class="guide">Ajax</a> applications:<p class="paragraph"/><div class="code"><pre>def show = { |
| def b = Book.get(params.id) |
| render(template:<span class="java-quote">"bookTemplate"</span>, model:[book:b]) |
| }</pre></div><p class="paragraph"/>The <a href="../ref/Controllers/render.html" class="controllers">render</a> method within controllers writes directly to the response, which is the most common behaviour. If you need to instead obtain the result of template as a String you can use the <a href="../ref/Tags/render.html" class="tags">render</a> tag:<p class="paragraph"/> |
| <div class="code"><pre>def show = { |
| def b = Book.get(params.id) |
| <span class="java-object">String</span> content = g.render(template:<span class="java-quote">"bookTemplate"</span>, model:[book:b]) |
| render content |
| }</pre></div><p class="paragraph"/>Notice the usage of the <code>g.</code> namespace which tells Grails we want to use the <a href="../guide/single.html#6.2.2.6 Tags as Method Calls" class="guide">tag as method call</a> instead of the <a href="../ref/Controllers/render.html" class="controllers">render</a> method. |
| <h2><a name="6.2.4 Layouts with Sitemesh">6.2.4 Layouts with Sitemesh</a></h2><h4>Creating Layouts</h4><p class="paragraph"/>Grails leverages <a href="http://www.opensymphony.com/sitemesh/" target="blank">Sitemesh</a>, a decorator engine, to support view layouts. Layouts are located in the <code>grails-app/views/layouts</code> directory. A typical layout can be seen below:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><html></span> |
| <span class="xml-tag"><head></span> |
| <span class="xml-tag"><title></span><span class="xml-tag"><g:layoutTitle default=<span class="xml-quote">"An example decorator"</span> /></span><span class="xml-tag"></title></span> |
| <span class="xml-tag"><g:layoutHead /></span> |
| <span class="xml-tag"></head></span> |
| <span class="xml-tag"><body onload=<span class="xml-quote">"${pageProperty(name:'body.onload')}"</span>></span> |
| <span class="xml-tag"><div class=<span class="xml-quote">"menu"</span>></span><span class="xml-comment"><!--my common menu goes here--></span><span class="xml-tag"></menu></span> |
| <span class="xml-tag"><div class=<span class="xml-quote">"body"</span>></span> |
| <span class="xml-tag"><g:layoutBody /></span> |
| <span class="xml-tag"></div></span> |
| <span class="xml-tag"></div></span> |
| <span class="xml-tag"></body></span> |
| <span class="xml-tag"></html></span></pre></div><p class="paragraph"/>The key elements are the <a href="../ref/Tags/layoutHead.html" class="tags">layoutHead</a>, <a href="../ref/Tags/layoutTitle.html" class="tags">layoutTitle</a> and <a href="../ref/Tags/layoutBody.html" class="tags">layoutBody</a> tag usages, here is what they do: |
| <ul class="star"> |
| <li><code>layoutTitle</code> - outputs the target page's title</li> |
| <li><code>layoutHead</code> - outputs the target pages head tag contents</li> |
| <li><code>layoutBody</code> - outputs the target pages body tag contents</li> |
| </ul><p class="paragraph"/>The previous example also demonstrates the <a href="../ref/Tags/pageProperty.html" class="tags">pageProperty</a> tag which can be used to inspect and return aspects of the target page.<p class="paragraph"/><h4>Triggering Layouts</h4><p class="paragraph"/>There are a few ways to trigger a layout. The simplest is to add a meta tag to the view:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><html></span> |
| <span class="xml-tag"><head></span> |
| <span class="xml-tag"><title></span>An Example Page<span class="xml-tag"></title></span> |
| <span class="xml-tag"><meta name=<span class="xml-quote">"layout"</span> content=<span class="xml-quote">"main"</span>></span><span class="xml-tag"></meta></span> |
| <span class="xml-tag"></head></span> |
| <span class="xml-tag"><body></span>This is my content!<span class="xml-tag"></body></span> |
| <span class="xml-tag"></html></span></pre></div><p class="paragraph"/>In this case a layout called <code>grails-app/views/layouts/main.gsp</code> will be used to layout the page. If we were to use the layout from the previous section the output would resemble the below:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><html></span> |
| <span class="xml-tag"><head></span> |
| <span class="xml-tag"><title></span>An Example Page<span class="xml-tag"></title></span> |
| <span class="xml-tag"></head></span> |
| <span class="xml-tag"><body onload=<span class="xml-quote">""</span>></span> |
| <span class="xml-tag"><div class=<span class="xml-quote">"menu"</span>></span><span class="xml-comment"><!--my common menu goes here--></span><span class="xml-tag"></div></span> |
| <span class="xml-tag"><div class=<span class="xml-quote">"body"</span>></span> |
| This is my content! |
| <span class="xml-tag"></div></span> |
| <span class="xml-tag"></body></span> |
| <span class="xml-tag"></html></span></pre></div><p class="paragraph"/><h4>Specifying A Layout In A Controller</h4><p class="paragraph"/>Another way to specify a layout is to specify the name of the layout by assigning a value to the "layout" property in a controller. For example, if you have a controller such as:<p class="paragraph"/><div class="code"><pre>class BookController { |
| <span class="java-keyword">static</span> layout = 'customer'<p class="paragraph"/> def list = { … } |
| }</pre></div><p class="paragraph"/>You can create a layout called <code>grails-app/views/layouts/customer.gsp</code> which will be applied to all views that the <code>BookController</code> delegates to. The value of the "layout" property may contain a directory structure relative to the <code>grails-app/views/layouts/</code> directory. For example:<p class="paragraph"/> |
| <div class="code"><pre>class BookController { |
| <span class="java-keyword">static</span> layout = 'custom/customer'<p class="paragraph"/> def list = { … } |
| }</pre></div><p class="paragraph"/>Views rendered from that controller would be decorated with the <code>grails-app/views/layouts/custom/customer.gsp</code> template.<p class="paragraph"/><h4>Layout by Convention</h4><p class="paragraph"/>Another way to associate layouts is to use "layout by convention". For example, if you have a controller such as:<p class="paragraph"/><div class="code"><pre>class BookController { |
| def list = { … } |
| }</pre></div><p class="paragraph"/>You can create a layout called <code>grails-app/views/layouts/book.gsp</code>, by convention, which will be applied to all views that the <code>BookController</code> delegates to.<p class="paragraph"/>Alternatively, you can create a layout called <code>grails-app/views/layouts/book/list.gsp</code> which will only be applied to the <code>list</code> action within the <code>BookController</code>.<p class="paragraph"/>If you have both the above mentioned layouts in place the layout specific to the action will take precedence when the list action is executed.<p class="paragraph"/>If a layout may not be located using any of those conventions, the convention of last resort is to look for the application default layout which |
| is <code>grails-app/views/layouts/application.gsp</code>. The name of the application default layout may be changed by defining a property |
| in <code>grails-app/conf/Config.groovy</code> as follows:<p class="paragraph"/><div class="code"><pre>// grails-app/conf/Config.groovy |
| grails.sitemesh.<span class="java-keyword">default</span>.layout='myLayoutName'</pre></div><p class="paragraph"/>With that property in place, the application default layout will be <code>grails-app/views/layouts/myLayoutName.gsp</code>.<p class="paragraph"/><h4>Inline Layouts</h4><p class="paragraph"/>Grails' also supports Sitemesh's concept of inline layouts with the <a href="../ref/Tags/applyLayout.html" class="tags">applyLayout</a> tag. The <code>applyLayout</code> tag can be used to apply a layout to a template, URL or arbitrary section of content. Essentially, this allows to even further modularize your view structure by "decorating" your template includes.<p class="paragraph"/>Some examples of usage can be seen below:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:applyLayout name=<span class="xml-quote">"myLayout"</span> template=<span class="xml-quote">"bookTemplate"</span> collection=<span class="xml-quote">"${books}"</span> /></span><p class="paragraph"/><span class="xml-tag"><g:applyLayout name=<span class="xml-quote">"myLayout"</span> url=<span class="xml-quote">"http://www.google.com"</span> /></span><p class="paragraph"/><span class="xml-tag"><g:applyLayout name=<span class="xml-quote">"myLayout"</span>></span> |
| The content to apply a layout to |
| <span class="xml-tag"></g:applyLayout></span></pre></div><p class="paragraph"/><h4>Server-Side Includes</h4><p class="paragraph"/>While the <a href="../ref/Tags/applyLayout.html" class="tags">applyLayout</a> tag is useful for applying layouts to external content, if you simply want to include external content in the current page you can do so with the <a href="../ref/Tags/include.html" class="tags">include</a>:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:include controller=<span class="xml-quote">"book"</span> action=<span class="xml-quote">"list"</span>></span><span class="xml-tag"></g:include></span></pre></div><p class="paragraph"/>You can even combine the <a href="../ref/Tags/include.html" class="tags">include</a> tag and the <a href="../ref/Tags/applyLayout.html" class="tags">applyLayout</a> tag for added flexibility:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:applyLayout name=<span class="xml-quote">"myLayout"</span>></span> |
| <span class="xml-tag"><g:include controller=<span class="xml-quote">"book"</span> action=<span class="xml-quote">"list"</span>></span><span class="xml-tag"></g:include></span> |
| <span class="xml-tag"></g:applyLayout></span></pre></div><p class="paragraph"/>Finally, you can also call the <a href="../ref/Tags/include.html" class="tags">include</a> tag from a controller or tag library as a method:<p class="paragraph"/><div class="code"><pre>def content = include(controller:<span class="java-quote">"book"</span>, action:<span class="java-quote">"list"</span>)</pre></div><p class="paragraph"/>The resulting content will be provided via the return value of the <a href="../ref/Tags/include.html" class="tags">include</a> tag.<h2><a name="6.2.5 Sitemesh Content Blocks">6.2.5 Sitemesh Content Blocks</a></h2>Although it is useful to decorate an entire page sometimes you may find the need to decorate independent sections of your site. To do this you can use content blocks. To get started you need to divide the page to be decorate using the <code><content></code> tag:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><content tag=<span class="xml-quote">"navbar"</span>></span> |
| … draw the navbar here… |
| <span class="xml-tag"></content></span> |
| <span class="xml-tag"><content tag=<span class="xml-quote">"header"</span>></span> |
| … draw the header here… |
| <span class="xml-tag"></content></span> |
| <span class="xml-tag"><content tag=<span class="xml-quote">"footer"</span>></span> |
| … draw the footer here… |
| <span class="xml-tag"></content></span> |
| <span class="xml-tag"><content tag=<span class="xml-quote">"body"</span>></span> |
| … draw the body here… |
| <span class="xml-tag"></content></span></pre></div><p class="paragraph"/>Then within the layout you can reference these components and apply individual layouts to each:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><html></span> |
| <span class="xml-tag"><body></span> |
| <span class="xml-tag"><div id=<span class="xml-quote">"header"</span>></span> |
| <span class="xml-tag"><g:applyLayout name=<span class="xml-quote">"headerLayout"</span>></span> |
| <span class="xml-tag"><g:pageProperty name=<span class="xml-quote">"page.header"</span> /></span> |
| <span class="xml-tag"></g:applyLayout></span> |
| <span class="xml-tag"></div></span> |
| <span class="xml-tag"><div id=<span class="xml-quote">"nav"</span>></span> |
| <span class="xml-tag"><g:applyLayout name=<span class="xml-quote">"navLayout"</span>></span> |
| <span class="xml-tag"><g:pageProperty name=<span class="xml-quote">"page.navbar"</span> /></span> |
| <span class="xml-tag"></g:applyLayout></span> |
| <span class="xml-tag"></div></span> |
| <span class="xml-tag"><div id=<span class="xml-quote">"body"</span>></span> |
| <span class="xml-tag"><g:applyLayout name=<span class="xml-quote">"bodyLayout"</span>></span> |
| <span class="xml-tag"><g:pageProperty name=<span class="xml-quote">"page.body"</span> /></span> |
| <span class="xml-tag"></g:applyLayout></span> |
| <span class="xml-tag"></div></span> |
| <span class="xml-tag"><div id=<span class="xml-quote">"footer"</span>></span> |
| <span class="xml-tag"><g:applyLayout name=<span class="xml-quote">"footerLayout"</span>></span> |
| <span class="xml-tag"><g:pageProperty name=<span class="xml-quote">"page.footer"</span> /></span> |
| <span class="xml-tag"></g:applyLayout></span> |
| <span class="xml-tag"></div></span> |
| <span class="xml-tag"></body></span> |
| <span class="xml-tag"></html></span></pre></div><h2><a name="6.2.6 Making Changes to a Deployed Application">6.2.6 Making Changes to a Deployed Application</a></h2>One of the main issues with deploying a Grails application (or typically any servlet-based one) is that any change to the views requires you to redeploy your whole application. If all you want to do is fix a typo on a page, or change an image link, it can seem like a lot of unnecessary work. For such simple requirements, Grails does have a solution: the <code>grails.gsp.view.dir</code> configuration setting.<p class="paragraph"/>How does this work? The first step is to decide where the GSP files should go. Let's say we want to keep them unpacked in a <code>/var/www/grails/my-app</code> directory. We add these two lines to <code>grails-app/conf/Config.groovy</code> : |
| <div class="code"><pre>grails.gsp.enable.reload = <span class="java-keyword">true</span> |
| grails.gsp.view.dir = <span class="java-quote">"/<span class="java-keyword">var</span>/www/grails/my-app/"</span></pre></div> |
| The first line tells Grails that modified GSP files should be reloaded at runtime. If you don't have this setting, you can make as many changes as you like but they won't be reflected in the running application. The second line tells Grails where to load the views and layouts from.<p class="paragraph"/><blockquote class="note"> |
| The trailing slash on the <code>grails.gsp.view.dir</code> value is important! Without it, Grails will look for views in the parent directory. |
| </blockquote><p class="paragraph"/>Setting "grails.gsp.view.dir" is optional. If it's not specified, you can update files directly to the application server's deployed war directory. Depending on the application server, these files might get overwritten when the server is restarted. Most application servers support "exploded war deployment" which is recommended in this case.<p class="paragraph"/>With those settings in place, all you need to do is copy the views from your web application to the external directory. On a Unix-like system, this would look something like this: |
| <div class="code"><pre>mkdir -p /<span class="java-keyword">var</span>/www/grails/my-app/grails-app/views |
| cp -R grails-app/views/* /<span class="java-keyword">var</span>/www/grails/my-app/grails-app/views</pre></div> |
| The key point here is that you must retain the view directory structure, including the <code>grails-app/views</code> bit. So you end up with the path <code>/var/www/grails/my-app/grails-app/views/...</code> .<p class="paragraph"/>One thing to bear in mind with this technique is that every time you modify a GSP, it uses up permgen space. So at some point you will eventually hit "out of permgen space" errors unless you restart the server. So this technique is not recommended for frequent or large changes to the views.<p class="paragraph"/>There are also some System properties to control GSP reloading: |
| <table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th><strong class="bold">Name</strong></th><th><strong class="bold">Description</strong></th><th><strong class="bold">Default</strong></th></tr><tr class="table-odd"><td>grails.gsp.reload.interval</td><td>interval between checking the lastmodified time of the gsp source file, unit is milliseconds</td><td>5000</td></tr><tr class="table-even"><td>grails.gsp.reload.enable</td><td>altervative system property for enabling the GSP reload mode without changing Config.groovy</td><td> </td></tr><tr class="table-odd"><td>grails.gsp.reload.granularity</td><td>the number of milliseconds leeway to give before deciding a file is out of date. this is needed because different roundings usually cause a 1000ms difference in lastmodified times</td><td>1000</td></tr></table><p class="paragraph"/>GSP reloading is supported for precompiled GSPs since Grails 1.3.5 .<p class="paragraph"/><h2><a name="6.2.7 GSP Debugging">6.2.7 GSP Debugging</a></h2><h4>Viewing the generated source code</h4> |
| <ul class="star"> |
| <li>Adding "?showSource=true" or "&showSource=true" to the url shows the generated groovy source code for the view instead of rendering it. It won't show the source code of included templates. This only works in development mode</li> |
| <li>The saving of all generated source code can be activated by setting the property "grails.views.gsp.keepgenerateddir" (in Config.groovy) . It should point to a directory that's existing and writable.</li> |
| <li>During "grails war" gsp pre-compilation, the generated source code is stored in grails.project.work.dir/gspcompile (usually in ~/.grails/(grails_version)/projects/(project name)/gspcompile).</li> |
| </ul><p class="paragraph"/><h4>Debugging GSP code with a debugger</h4> |
| <ul class="star"> |
| <li><a href="http://contraptionsforprogramming.blogspot.com/2010/08/debuggable-gsps-in-springsource-tool.html" target="blank">Debugging GSP in STS</a></li> |
| </ul><p class="paragraph"/><h4>Viewing information about templates used to render a single url</h4><p class="paragraph"/>GSP templates are re-used in large web applications by using the g:render taglib. A lot of small templates can be used to render a single page. |
| It might be hard to find out what gsp template actually renders the html seen in the result. |
| The debug templates -feature adds html comments to the output. The comments contain debug information about gsp templates used to render the page.<p class="paragraph"/>Usage is simple: append "?debugTemplates" or "&debugTemplates" to the url and view the source of the result in your browser. |
| "debugTemplates" is restricted to development mode. It won't work in production.<p class="paragraph"/>Here is an example of comments added by debugTemplates : |
| <div class="code"><pre><!-- GSP #2 START template: /home/user/sampleapp/grails-app/views/_carousel.gsp precompiled: <span class="java-keyword">false</span> lastmodified: 22.6.2010 10:45 --> |
| . |
| . |
| . |
| <!-- GSP #2 END template: /home/user/sampleapp/grails-app/views/_carousel.gsp rendering time: 115 ms --></pre></div><p class="paragraph"/>Each comment block has a unique id so that you can find the start & end of each template call. |
| <h2><a name="6.3 Tag Libraries">6.3 Tag Libraries</a></h2>Like <a href="http://java.sun.com/products/jsp/" target="blank">Java Server Pages</a> (JSP), GSP supports the concept of custom tag libraries. Unlike JSP, Grails tag library mechanism is simply, elegant and completely reload-able at runtime.<p class="paragraph"/>Quite simply, to create a tag library create a Groovy class that ends with the convention <code>TagLib</code> and place it within the <code>grails-app/taglib</code> directory:<p class="paragraph"/><div class="code"><pre>class SimpleTagLib {<p class="paragraph"/>}</pre></div><p class="paragraph"/>Now to create a tag simply create property that is assigned a block of code that takes two arguments: The tag attributes and the body content:<p class="paragraph"/><div class="code"><pre>class SimpleTagLib { |
| def simple = { attrs, body -><p class="paragraph"/> } |
| }</pre></div><p class="paragraph"/>The <code>attrs</code> argument is a simple map of the attributes of the tag, whilst the <code>body</code> argument is another invokable block of code that returns the body content:<p class="paragraph"/><div class="code"><pre>class SimpleTagLib { |
| def emoticon = { attrs, body -> |
| out << body() << (attrs.happy == '<span class="java-keyword">true</span>' ? <span class="java-quote">" :-)"</span> : <span class="java-quote">" :-("</span>) |
| } |
| }</pre></div><p class="paragraph"/>As demonstrated above there is an implicit <code>out</code> variable that refers to the output <code>Writer</code> which you can use to append content to the response. Then you can simply reference the tag inside your GSP, no imports necessary:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:emoticon happy=<span class="xml-quote">"true"</span>></span>Hi John<span class="xml-tag"></g:emoticon></span></pre></div><p class="paragraph"/> |
| <h2><a name="6.3.1 Variables and Scopes">6.3.1 Variables and Scopes</a></h2>Within the scope of a tag library there are a number of pre-defined variables including: |
| <ul class="star"> |
| <li><code>actionName</code> - The currently executing action name</li> |
| <li><code>controllerName</code> - The currently executing controller name</li> |
| <li><code>flash</code> - The <a href="../ref/Controllers/flash.html" class="controllers">flash</a> object</li> |
| <li><code>grailsApplication</code> - The <a href="../api/org/codehaus/groovy/grails/commons/GrailsApplication.html" class="api">GrailsApplication</a> instance</li> |
| <li><code>out</code> - The response writer for writing to the output stream</li> |
| <li><code>pageScope</code> - A reference to the <a href="../ref/Tag Libraries/pageScope.html" class="tagLibraries">pageScope</a> object used for GSP rendering (i.e. the binding)</li> |
| <li><code>params</code> - The <a href="../ref/Controllers/params.html" class="controllers">params</a> object for retrieving request parameters</li> |
| <li><code>pluginContextPath</code> - The context path to the plugin that contains the tag library</li> |
| <li><code>request</code> - The <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletRequest.html" class="api">HttpServletRequest</a> instance</li> |
| <li><code>response</code> - The <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletResponse.html" class="api">HttpServletResponse</a> instance</li> |
| <li><code>servletContext</code> - The <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/ServletContext.html" class="api">javax.servlet.ServletContext</a> instance</li> |
| <li><code>session</code> - The <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpSession.html" class="api">HttpSession</a> instance</li> |
| </ul><p class="paragraph"/><h2><a name="6.3.2 Simple Tags">6.3.2 Simple Tags</a></h2>As demonstrated it the previous example it is trivial to write simple tags that have no body and merely output content. Another example is a <code>dateFormat</code> style tag:<p class="paragraph"/><div class="code"><pre>def dateFormat = { attrs, body -> |
| out << <span class="java-keyword">new</span> java.text.SimpleDateFormat(attrs.format).format(attrs.date) |
| }</pre></div><p class="paragraph"/>The above uses Java's <code>SimpleDateFormat</code> class to format a date and then write it to the response. The tag can then be used within a GSP as follows:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:dateFormat format=<span class="xml-quote">"dd-MM-yyyy"</span> date=<span class="xml-quote">"${new Date()}"</span> /></span></pre></div><p class="paragraph"/>With simple tags sometimes you need to write HTML mark-up to the response. One approach would be to embed the content directly:<p class="paragraph"/><div class="code"><pre>def formatBook = { attrs, body -> |
| out << <span class="java-quote">"<div id="${attrs.book.id}">"</span> |
| out << <span class="java-quote">"Title : ${attrs.book.title}"</span> |
| out << <span class="java-quote">"</div>"</span> |
| }</pre></div><p class="paragraph"/>Although this approach may be tempting it is not very clean. A better approach would be to re-use the <a href="../ref/Tags/render.html" class="tags">render</a> tag:<p class="paragraph"/><div class="code"><pre>def formatBook = { attrs, body -> |
| out << render(template:<span class="java-quote">"bookTemplate"</span>, model:[book:attrs.book]) |
| }</pre></div><p class="paragraph"/>And then have a separate GSP template that does the actual rendering.<h2><a name="6.3.3 Logical Tags">6.3.3 Logical Tags</a></h2>You can also create logical tags where the body of the tag is only output once a set of conditions have been met. An example of this may be a set of security tags:<p class="paragraph"/><div class="code"><pre>def isAdmin = { attrs, body -> |
| def user = attrs['user'] |
| <span class="java-keyword">if</span>(user != <span class="java-keyword">null</span> && checkUserPrivs(user)) { |
| out << body() |
| } |
| }</pre></div><p class="paragraph"/>The tag above checks if the user is an administrator and only outputs the body content if he/she has the correct set of access privileges:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:isAdmin user=<span class="xml-quote">"${myUser}"</span>></span> |
| // some restricted content |
| <span class="xml-tag"></g:isAdmin></span></pre></div><p class="paragraph"/> |
| <h2><a name="6.3.4 Iterative Tags">6.3.4 Iterative Tags</a></h2>Iterative tags are trivial too, since you can invoke the body multiple times:<p class="paragraph"/><div class="code"><pre>def repeat = { attrs, body -> |
| attrs.times?.toInteger().times { num -> |
| out << body(num) |
| } |
| }</pre></div><p class="paragraph"/>In this example we check for a <code>times</code> attribute and if it exists convert it to a number then use Groovy's <code>times</code> method to iterate by the number of times specified by the number:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:repeat times=<span class="xml-quote">"3"</span>></span> |
| <span class="xml-tag"><p></span>Repeat this 3 times! Current repeat = ${it}<span class="xml-tag"></p></span> |
| <span class="xml-tag"></g:repeat></span></pre></div><p class="paragraph"/>Notice how in this example we use the implicit <code>it</code> variable to refer to the current number. This works because when we invoked the body we passed in the current value inside the iteration:<p class="paragraph"/><div class="code"><pre>out << body(num)</pre></div><p class="paragraph"/>That value is then passed as the default variable <code>it</code> to the tag. However, if you have nested tags this can lead to conflicts, hence you should should instead name the variables that the body uses:<p class="paragraph"/> |
| <div class="code"><pre>def repeat = { attrs, body -> |
| def <span class="java-keyword">var</span> = attrs.<span class="java-keyword">var</span> ? attrs.<span class="java-keyword">var</span> : <span class="java-quote">"num"</span> |
| attrs.times?.toInteger().times { num -> |
| out << body((<span class="java-keyword">var</span>):num) |
| } |
| }</pre></div><p class="paragraph"/>Here we check if there is a <code>var</code> attribute and if there is use that as the name to pass into the body invocation on this line:<p class="paragraph"/><div class="code"><pre>out << body((<span class="java-keyword">var</span>):num)</pre></div><p class="paragraph"/><blockquote class="note"> |
| Note the usage of the parenthesis around the variable name. If you omit these Groovy assumes you are using a String key and not referring to the variable itself. |
| </blockquote><p class="paragraph"/>Now we can change the usage of the tag as follows:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:repeat times=<span class="xml-quote">"3"</span> var=<span class="xml-quote">"j"</span>></span> |
| <span class="xml-tag"><p></span>Repeat this 3 times! Current repeat = ${j}<span class="xml-tag"></p></span> |
| <span class="xml-tag"></g:repeat></span></pre></div><p class="paragraph"/>Notice how we use the <code>var</code> attribute to define the name of the variable <code>j</code> and then we are able to reference that variable within the body of the tag.<h2><a name="6.3.5 Tag Namespaces">6.3.5 Tag Namespaces</a></h2>By default, tags are added to the default Grails namespace and are used with the <code>g:</code> prefix in GSP pages. However, you can specify a different namespace by adding a static property to your <code>TagLib</code> class:<p class="paragraph"/><div class="code"><pre>class SimpleTagLib { |
| <span class="java-keyword">static</span> namespace = <span class="java-quote">"my"</span><p class="paragraph"/> def example = { attrs -> |
| … |
| } |
| }</pre></div><p class="paragraph"/>Here we have specified a <code>namespace</code> of <code>my</code> and hence the tags in this tag lib must then be referenced from GSP pages like this:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><my:example name=<span class="xml-quote">"..."</span> /></span></pre></div><p class="paragraph"/>Where the prefix is the same as the value of the static <code>namespace</code> property. Namespaces are particularly useful for plugins.<p class="paragraph"/> |
| Tags within namespaces can be invoked as methods using the namespace as a prefix to the method call:<p class="paragraph"/><div class="code"><pre>out << my.example(name:<span class="java-quote">"foo"</span>)</pre></div><p class="paragraph"/>This works from GSP, controllers or tag libraries<h2><a name="6.3.6 Using JSP Tag Libraries">6.3.6 Using JSP Tag Libraries</a></h2>In addition to the simplified tag library mechanism provided by GSP, you can also use JSP tags from GSP. To do so simply declare the JSP you want to use via the <code>taglib</code> directive:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><%@ taglib prefix=<span class="xml-quote">"fmt"</span> uri=<span class="xml-quote">"http://java.sun.com/jsp/jstl/fmt"</span> %></span></pre></div><p class="paragraph"/>Then you can use it like any other tag:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><fmt:formatNumber value=<span class="xml-quote">"${10}"</span> pattern=<span class="xml-quote">".00"</span>/></span></pre></div><p class="paragraph"/>With the added bonus that you can invoke JSP tags like methods:<p class="paragraph"/><div class="code"><pre>${fmt.formatNumber(value:10, pattern:<span class="java-quote">".00"</span>)}</pre></div><h2><a name="6.3.7 Tag return value">6.3.7 Tag return value</a></h2>Since Grails 1.2, a tag library call returns an instance of <code>org.codehaus.groovy.grails.web.util.StreamCharBuffer</code> class by default. |
| This change improves performance by reducing object creation and optimizing buffering during request processing. |
| In earlier Grails versions, a <code>java.lang.String</code> instance was returned.<p class="paragraph"/>Tag libraries can also return direct object values to the caller since Grails 1.2.. |
| Object returning tag names are listed in a static <code>returnObjectForTags</code> property in the tag library class.<p class="paragraph"/>Example: |
| <div class="code"><pre>class ObjectReturningTagLib { |
| <span class="java-keyword">static</span> namespace = <span class="java-quote">"cms"</span> |
| <span class="java-keyword">static</span> returnObjectForTags = ['content']<p class="paragraph"/> def content = { attrs, body -> |
| CmsContent.findByCode(attrs.code)?.content |
| } |
| }</pre></div><h2><a name="6.4 URL Mappings">6.4 URL Mappings</a></h2>Throughout the documentation so far the convention used for URLs has been the default of <code>/controller/action/id</code>. However, this convention is not hard wired into Grails and is in fact controlled by a URL Mappings class located at <code>grails-app/conf/UrlMappings.groovy</code>.<p class="paragraph"/>The <code>UrlMappings</code> class contains a single property called <code>mappings</code> that has been assigned a block of code:<p class="paragraph"/><div class="code"><pre>class UrlMappings { |
| <span class="java-keyword">static</span> mappings = { |
| } |
| }</pre></div><p class="paragraph"/><h2><a name="6.4.1 Mapping to Controllers and Actions">6.4.1 Mapping to Controllers and Actions</a></h2>To create a simple mapping simply use a relative URL as the method name and specify named parameters for the controller and action to map to:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/product"</span>(controller:<span class="java-quote">"product"</span>, action:<span class="java-quote">"list"</span>)</pre></div><p class="paragraph"/>In this case we've mapped the URL <code>/product</code> to the <code>list</code> action of the <code>ProductController</code>. You could of course omit the action definition to map to the default action of the controller:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/product"</span>(controller:<span class="java-quote">"product"</span>)</pre></div><p class="paragraph"/>An alternative syntax is to assign the controller and action to use within a block passed to the method:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/product"</span> { |
| controller = <span class="java-quote">"product"</span> |
| action = <span class="java-quote">"list"</span> |
| }</pre></div><p class="paragraph"/>Which syntax you use is largely dependent on personal preference. If you simply want to rewrite on URI onto another explicit URI (rather than a controller/action pair) this can be achieved with the following example:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/hello"</span>(uri:<span class="java-quote">"/hello.dispatch"</span>)</pre></div><p class="paragraph"/>Rewriting specific URIs is often useful when integrating with other frameworks.<p class="paragraph"/> |
| <h2><a name="6.4.2 Embedded Variables">6.4.2 Embedded Variables</a></h2><h4>Simple Variables</h4><p class="paragraph"/>The previous section demonstrated how to map trivial URLs with concrete "tokens". In URL mapping speak tokens are the sequence of characters between each slash / character. A concrete token is one which is well defined such as as <code>/product</code>. However, in many circumstances you don't know what the value of a particular token will be until runtime. In this case you can use variable placeholders within the URL for example:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/product/$id"</span>(controller:<span class="java-quote">"product"</span>) |
| }</pre></div><p class="paragraph"/>In this case by embedding a $id variable as the second token Grails will automatically map the second token into a parameter (available via the <a href="../ref/Controllers/params.html" class="controllers">params</a> object) called <code>id</code>. For example given the URL <code>/product/MacBook</code>, the following code will render "MacBook" to the response:<p class="paragraph"/><div class="code"><pre>class ProductController { |
| def index = { render params.id } |
| }</pre></div><p class="paragraph"/> |
| You can of course construct more complex examples of mappings. For example the traditional blog URL format could be mapped as follows:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/$blog/$year/$month/$day/$id"</span>(controller:<span class="java-quote">"blog"</span>, action:<span class="java-quote">"show"</span>) |
| }</pre></div><p class="paragraph"/>The above mapping would allow you to do things like:<p class="paragraph"/><div class="code"><pre>/graemerocher/2007/01/10/my_funky_blog_entry</pre></div><p class="paragraph"/>The individual tokens in the URL would again be mapped into the <a href="../ref/Controllers/params.html" class="controllers">params</a> object with values available for <code>year</code>, <code>month</code>, <code>day</code>, <code>id</code> and so on.<p class="paragraph"/><h4>Dynamic Controller and Action Names</h4><p class="paragraph"/>Variables can also be used to dynamically construct the controller and action name. In fact the default Grails URL mappings use this technique:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/$controller/$action?/$id?"</span>() |
| }</pre></div><p class="paragraph"/>Here the name of the controller, action and id are implicitly obtained from the variables <code>controller</code>, <code>action</code> and <code>id</code> embedded within the URL.<p class="paragraph"/>You can also resolve the controller name and action name to execute dynamically using a closure:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/$controller"</span> { |
| action = { params.goHere } |
| } |
| }</pre></div><p class="paragraph"/><h4>Optional Variables</h4><p class="paragraph"/>Another characteristic of the default mapping is the ability to append a <code>?</code> at the end of a variable to make it an optional token. In a further example this technique could be applied to the blog URL mapping to have more flexible linking:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/$blog/$year?/$month?/$day?/$id?"</span>(controller:<span class="java-quote">"blog"</span>, action:<span class="java-quote">"show"</span>) |
| }</pre></div><p class="paragraph"/>With this mapping all of the below URLs would match with only the relevant parameters being populated in the <a href="../ref/Controllers/params.html" class="controllers">params</a> object:<p class="paragraph"/><div class="code"><pre>/graemerocher/2007/01/10/my_funky_blog_entry |
| /graemerocher/2007/01/10 |
| /graemerocher/2007/01 |
| /graemerocher/2007 |
| /graemerocher</pre></div><p class="paragraph"/><h4>Arbitrary Variables</h4><p class="paragraph"/>You can also pass arbitrary parameters from the URL mapping into the controller by merely setting them in the block passed to the mapping:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/holiday/win"</span> { |
| id = <span class="java-quote">"Marrakech"</span> |
| year = 2007 |
| }</pre></div><p class="paragraph"/>This variables will be available within the <a href="../ref/Controllers/params.html" class="controllers">params</a> object passed to the controller.<p class="paragraph"/><h4>Dynamically Resolved Variables</h4><p class="paragraph"/>The hard coded arbitrary variables are useful, but sometimes you need to calculate the name of the variable based on runtime factors. This is also possible by assigning a block to the variable name:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/holiday/win"</span> { |
| id = { params.id } |
| isEligible = { session.user != <span class="java-keyword">null</span> } // must be logged in |
| }</pre></div><p class="paragraph"/>In the above case the code within the blocks is resolved when the URL is actually matched and hence can be used in combination with all sorts of logic.<h2><a name="6.4.3 Mapping to Views">6.4.3 Mapping to Views</a></h2>If you want to resolve a URL to a view, without a controller or action involved, you can do so too. For example if you wanted to map the root URL <code>/</code> to a GSP at the location <code>grails-app/views/index.gsp</code> you could use:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/"</span>(view:<span class="java-quote">"/index"</span>) // map the root URL |
| }</pre></div><p class="paragraph"/>Alternatively if you need a view that is specific to a given controller you could use:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/help"</span>(controller:<span class="java-quote">"site"</span>,view:<span class="java-quote">"help"</span>) // to a view <span class="java-keyword">for</span> a controller |
| }</pre></div><h2><a name="6.4.4 Mapping to Response Codes">6.4.4 Mapping to Response Codes</a></h2>Grails also allows you to map HTTP response codes to controllers, actions or views. All you have to do is use a method name that matches the response code you are interested in:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"403"</span>(controller: <span class="java-quote">"errors"</span>, action: <span class="java-quote">"forbidden"</span>) |
| <span class="java-quote">"404"</span>(controller: <span class="java-quote">"errors"</span>, action: <span class="java-quote">"notFound"</span>) |
| <span class="java-quote">"500"</span>(controller: <span class="java-quote">"errors"</span>, action: <span class="java-quote">"serverError"</span>) |
| }</pre></div><p class="paragraph"/>Or alternatively if you merely want to provide custom error pages:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"403"</span>(view: <span class="java-quote">"/errors/forbidden"</span>) |
| <span class="java-quote">"404"</span>(view: <span class="java-quote">"/errors/notFound"</span>) |
| <span class="java-quote">"500"</span>(view: <span class="java-quote">"/errors/serverError"</span>) |
| }</pre></div><p class="paragraph"/><h4>Declarative Error Handling</h4><p class="paragraph"/>In addition you can configure handlers for individual exceptions:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"403"</span>(view: <span class="java-quote">"/errors/forbidden"</span>) |
| <span class="java-quote">"404"</span>(view: <span class="java-quote">"/errors/notFound"</span>) |
| <span class="java-quote">"500"</span>(controller: <span class="java-quote">"errors"</span>, action: <span class="java-quote">"illegalArgument"</span>, exception: IllegalArgumentException) |
| <span class="java-quote">"500"</span>(controller: <span class="java-quote">"errors"</span>, action: <span class="java-quote">"nullPointer"</span>, exception: NullPointerException) |
| <span class="java-quote">"500"</span>(controller: <span class="java-quote">"errors"</span>, action: <span class="java-quote">"customException"</span>, exception: MyException) |
| <span class="java-quote">"500"</span>(view: <span class="java-quote">"/errors/serverError"</span>) |
| }</pre></div><p class="paragraph"/>With this configuration, an <code>IllegalArgumentException</code> will be handled by the <code>illegalArgument</code> action in <code>ErrorsController</code>, a <code>NullPointerException</code> will be handled by the <code>nullPointer</code> action, and a <code>MyException</code> will be handled by the <code>customException</code> action. Other exceptions will be handled by the catch-all rule and use the <code>/errors/serverError</code> view. |
| <h2><a name="6.4.5 Mapping to HTTP methods">6.4.5 Mapping to HTTP methods</a></h2>URL mappings can also be configured to map based on the HTTP method (GET, POST, PUT or DELETE). This is extremely useful for RESTful APIs and for restricting mappings based on HTTP method.<p class="paragraph"/>As an example the following mappings provide a RESTful API URL mappings for the <code>ProductController</code>:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/product/$id"</span>(controller:<span class="java-quote">"product"</span>){ |
| action = [GET:<span class="java-quote">"show"</span>, PUT:<span class="java-quote">"update"</span>, DELETE:<span class="java-quote">"delete"</span>, POST:<span class="java-quote">"save"</span>] |
| } |
| }</pre></div><h2><a name="6.4.6 Mapping Wildcards">6.4.6 Mapping Wildcards</a></h2>Grails' URL mappings mechanism also supports wildcard mappings. For example consider the following mapping:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/images/*.jpg"</span>(controller:<span class="java-quote">"image"</span>) |
| }</pre></div><p class="paragraph"/>This mapping will match all paths to images such as <code>/image/logo.jpg</code>. Of course you can achieve the same effect with a variable:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/images/$name.jpg"</span>(controller:<span class="java-quote">"image"</span>) |
| }</pre></div><p class="paragraph"/>However, you can also use double wildcards to match more than one level below:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/images/**.jpg"</span>(controller:<span class="java-quote">"image"</span>) |
| }</pre></div><p class="paragraph"/>In this cases the mapping will match <code>/image/logo.jpg</code> as well as <code>/image/other/logo.jpg</code>. Even better you can use a double wildcard variable:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| // will match /image/logo.jpg and /image/other/logo.jpg |
| <span class="java-quote">"/images/$name**.jpg"</span>(controller:<span class="java-quote">"image"</span>) |
| }</pre></div><p class="paragraph"/>In this case it will store the path matched by the wildcard inside a <code>name</code> parameter obtainable from the <a href="../ref/Controllers/params.html" class="controllers">params</a> object:<p class="paragraph"/><div class="code"><pre>def name = params.name |
| println name // prints <span class="java-quote">"logo"</span> or <span class="java-quote">"other/logo"</span></pre></div><p class="paragraph"/>If you are using wildcard URL mappings then you may want to exclude certain URIs from Grails' URL mapping process. To do this you can provide an <code>excludes</code> setting inside the <code>UrlMappings.groovy</code> class:<p class="paragraph"/><div class="code"><pre>class UrlMappings = { |
| <span class="java-keyword">static</span> excludes = [<span class="java-quote">"/images/*"</span>, <span class="java-quote">"/css/*"</span>] |
| <span class="java-keyword">static</span> mappings = { |
| … |
| } |
| }</pre></div><p class="paragraph"/>In this case Grails won't attempt to match any URIs that start with <code>/images</code> or <code>/css</code>. |
| <h2><a name="6.4.7 Automatic Link Re-Writing">6.4.7 Automatic Link Re-Writing</a></h2>Another great feature of URL mappings is that they automatically customize the behaviour of the <a href="../ref/Tags/link.html" class="tags">link</a> tag so that changing the mappings don't require you to go and change all of your links.<p class="paragraph"/>This is done through a URL re-writing technique that reverse engineers the links from the URL mappings. So given a mapping such as the blog one from an earlier section:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/$blog/$year?/$month?/$day?/$id?"</span>(controller:<span class="java-quote">"blog"</span>, action:<span class="java-quote">"show"</span>) |
| }</pre></div><p class="paragraph"/>If you use the link tag as follows:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:link controller=<span class="xml-quote">"blog"</span> action=<span class="xml-quote">"show"</span> params=<span class="xml-quote">"[blog:'fred', year:2007]"</span>></span>My Blog<span class="xml-tag"></g:link></span> |
| <span class="xml-tag"><g:link controller=<span class="xml-quote">"blog"</span> action=<span class="xml-quote">"show"</span> params=<span class="xml-quote">"[blog:'fred', year:2007, month:10]"</span>></span>My Blog - October 2007 Posts<span class="xml-tag"></g:link></span></pre></div><p class="paragraph"/>Grails will automatically re-write the URL in the correct format:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><a href=<span class="xml-quote">"/fred/2007"</span>></span>My Blog<span class="xml-tag"></a></span> |
| <span class="xml-tag"><a href=<span class="xml-quote">"/fred/2007/10"</span>></span>My Blog - October 2007 Posts<span class="xml-tag"></a></span></pre></div><h2><a name="6.4.8 Applying Constraints">6.4.8 Applying Constraints</a></h2>URL Mappings also support Grails' unified <a href="../guide/single.html#7.1 Declaring Constraints" class="guide">validation constraints</a> mechanism, which allows you to further "constrain" how a URL is matched. For example, if we revisit the blog sample code from earlier, the mapping currently looks like this:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/$blog/$year?/$month?/$day?/$id?"</span>(controller:<span class="java-quote">"blog"</span>, action:<span class="java-quote">"show"</span>) |
| }</pre></div><p class="paragraph"/>This allows URLs such as:<p class="paragraph"/><div class="code"><pre>/graemerocher/2007/01/10/my_funky_blog_entry</pre></div><p class="paragraph"/>However, it would also allow:<p class="paragraph"/><div class="code"><pre>/graemerocher/not_a_year/not_a_month/not_a_day/my_funky_blog_entry</pre></div><p class="paragraph"/>This is problematic as it forces you to do some clever parsing in the controller code. Luckily, URL Mappings can be constrained to further validate the URL tokens:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/$blog/$year?/$month?/$day?/$id?"</span> { |
| controller = <span class="java-quote">"blog"</span> |
| action = <span class="java-quote">"show"</span> |
| constraints { |
| year(matches:/\d{4}/) |
| month(matches:/\d{2}/) |
| day(matches:/\d{2}/) |
| } |
| }</pre></div><p class="paragraph"/>In this case the constraints ensure that the <code>year</code>, <code>month</code> and <code>day</code> parameters match a particular valid pattern thus relieving you of that burden later on.<h2><a name="6.4.9 Named URL Mappings">6.4.9 Named URL Mappings</a></h2>URL Mappings also support named mappings. Simply put, named mappings are mappings |
| which have a name associated with them. The name may be used to refer to a |
| specific mapping when links are being generated.<p class="paragraph"/>The syntax for defining a named mapping is as follows:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| name <mapping name>: <url pattern> { |
| // … |
| } |
| }</pre></div><p class="paragraph"/>An example:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| name personList: <span class="java-quote">"/showPeople"</span> { |
| controller = 'person' |
| action = 'list' |
| } |
| name accountDetails: <span class="java-quote">"/details/$acctNumber"</span> { |
| controller = 'product' |
| action = 'accountDetails' |
| } |
| }</pre></div><p class="paragraph"/>The mapping may be referenced in a link tag in a GSP.<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:link mapping=<span class="xml-quote">"personList"</span>></span>List People<span class="xml-tag"></g:link></span></pre></div><p class="paragraph"/>That would result in:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><a href=<span class="xml-quote">"/showPeople"</span>></span>List People<span class="xml-tag"></a></span></pre></div><p class="paragraph"/>Parameters may be specified using the params attribute.<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:link mapping=<span class="xml-quote">"accountDetails"</span> params=<span class="xml-quote">"[acctNumber:'8675309']"</span>></span>Show Account<span class="xml-tag"></g:link></span></pre></div><p class="paragraph"/>That would result in:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><a href=<span class="xml-quote">"/details/8675309"</span>></span>Show Account<span class="xml-tag"></a></span></pre></div><p class="paragraph"/>Alternatively you may reference a named mapping using the link namespace.<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><link:personList></span>List People<span class="xml-tag"></link:personList></span></pre></div><p class="paragraph"/>That would result in:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><a href=<span class="xml-quote">"/showPeople"</span>></span>List People<span class="xml-tag"></a></span></pre></div><p class="paragraph"/>The link namespace approach allows parameters to be specified as attributes.<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><link:accountDetails acctNumber=<span class="xml-quote">"8675309"</span>></span>Show Account<span class="xml-tag"></link:accountDetails></span></pre></div><p class="paragraph"/>That would result in:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><a href=<span class="xml-quote">"/details/8675309"</span>></span>Show Account<span class="xml-tag"></a></span></pre></div> |
| <h2><a name="6.5 Web Flow">6.5 Web Flow</a></h2><h4>Overview</h4><p class="paragraph"/>Grails supports the creation of web flows built on the <a href="http://www.springsource.org/webflow" target="blank">Spring Web Flow</a> project. A web flow is a conversation that spans multiple requests and retains state for the scope of the flow. A web flow also has a defined start and end state.<p class="paragraph"/>Web flows don't require an HTTP session, but instead store their state in a serialized form, which is then restored using a flow execution key that Grails passes around as a request parameter. This makes flows far more scalable than other forms of stateful application that use the HttpSession and its inherit memory and clustering concerns.<p class="paragraph"/>Web flow is essentially an advanced state machine that manages the "flow" of execution from one state to the next. Since the state is managed for you, you don't have to be concerned with ensuring that users enter an action in the middle of some multi step flow, as web flow manages that for you. This makes web flow perfect for use cases such as shopping carts, hotel booking and any application that has multi page work flows.<p class="paragraph"/><h4>Creating a Flow</h4><p class="paragraph"/>To create a flow create a regular Grails controller and then add an action that ends with the convention <code>Flow</code>. For example:<p class="paragraph"/><div class="code"><pre>class BookController { |
| def index = { |
| redirect(action:<span class="java-quote">"shoppingCart"</span>) |
| } |
| def shoppingCartFlow = { |
| … |
| } |
| }</pre></div><p class="paragraph"/>Notice when redirecting or referring to the flow as an action we omit the <code>Flow</code> suffix. In other words the name of the action of the above flow is <code>shoppingCart</code>. |
| <h2><a name="6.5.1 Start and End States">6.5.1 Start and End States</a></h2>As mentioned before a flow has a defined start and end state. A start state is the state which is entered when a user first initiates a conversation (or flow). The start state of A Grails flow is the first method call that takes a block. For example:<p class="paragraph"/> |
| <div class="code"><pre>class BookController { |
| … |
| def shoppingCartFlow = { |
| showCart { |
| on(<span class="java-quote">"checkout"</span>).to <span class="java-quote">"enterPersonalDetails"</span> |
| on(<span class="java-quote">"continueShopping"</span>).to <span class="java-quote">"displayCatalogue"</span> |
| } |
| … |
| displayCatalogue { |
| redirect(controller:<span class="java-quote">"catalogue"</span>, action:<span class="java-quote">"show"</span>) |
| } |
| displayInvoice() |
| } |
| }</pre></div><p class="paragraph"/>Here the <code>showCart</code> node is the start state of the flow. Since the showCart state doesn't define an action or redirect it is assumed be a <a href="../guide/single.html#6.5.2 Action States and View States" class="guide">view state</a> that, by convention, refers to the view <code>grails-app/views/book/shoppingCart/showCart.gsp</code>.<p class="paragraph"/>Notice that unlike regular controller actions, the views are stored within a directory that matches the name of the flow: <code>grails-app/views/book/shoppingCart</code>.<p class="paragraph"/>The <code>shoppingCart</code> flow also has two possible end states. The first is <code>displayCatalogue</code> which performs an external redirect to another controller and action, thus exiting the flow. The second is <code>displayInvoice</code> which is an end state as it has no events at all and will simply render a view called <code>grails-app/views/book/shoppingCart/displayInvoice.gsp</code> whilst ending the flow at the same time.<p class="paragraph"/>Once a flow has ended it can only be resumed from the start state, in this case <code>showCart</code>, and not from any other state. |
| <h2><a name="6.5.2 Action States and View States">6.5.2 Action States and View States</a></h2><h4>View states</h4><p class="paragraph"/>A view state is a one that doesn't define an <code>action</code> or a <code>redirect</code>. So for example the below is a view state:<p class="paragraph"/><div class="code"><pre>enterPersonalDetails { |
| on(<span class="java-quote">"submit"</span>).to <span class="java-quote">"enterShipping"</span> |
| on(<span class="java-quote">"<span class="java-keyword">return</span>"</span>).to <span class="java-quote">"showCart"</span> |
| }</pre></div><p class="paragraph"/>It will look for a view called <code>grails-app/views/book/shoppingCart/enterPersonalDetails.gsp</code> by default. Note that the <code>enterPersonalDetails</code> state defines two events: <code>submit</code> and <code>return</code>. The view is responsible for <a href="../guide/single.html#6.5.3 Flow Execution Events" class="guide">triggering</a> these events. If you want to change the view to be rendered you can do so with the render method:<p class="paragraph"/><div class="code"><pre>enterPersonalDetails { |
| render(view:<span class="java-quote">"enterDetailsView"</span>) |
| on(<span class="java-quote">"submit"</span>).to <span class="java-quote">"enterShipping"</span> |
| on(<span class="java-quote">"<span class="java-keyword">return</span>"</span>).to <span class="java-quote">"showCart"</span> |
| }</pre></div><p class="paragraph"/>Now it will look for <code>grails-app/views/book/shoppingCart/enterDetailsView.gsp</code>. If you want to use a shared view, start with a / in view argument:<p class="paragraph"/><div class="code"><pre>enterPersonalDetails { |
| render(view:<span class="java-quote">"/shared/enterDetailsView"</span>) |
| on(<span class="java-quote">"submit"</span>).to <span class="java-quote">"enterShipping"</span> |
| on(<span class="java-quote">"<span class="java-keyword">return</span>"</span>).to <span class="java-quote">"showCart"</span> |
| }</pre></div><p class="paragraph"/>Now it will look for <code>grails-app/views/shared/enterDetailsView.gsp</code><p class="paragraph"/> |
| <h4>Action States</h4><p class="paragraph"/>An action state is a state that executes code but does not render any view. The result of the action is used to dictate flow transition. To create an action state you need to define an action to to be executed. This is done by calling the <code>action</code> method and passing it a block of code to be executed:<p class="paragraph"/><div class="code"><pre>listBooks { |
| action { |
| [ bookList:Book.list() ] |
| } |
| on(<span class="java-quote">"success"</span>).to <span class="java-quote">"showCatalogue"</span> |
| on(Exception).to <span class="java-quote">"handleError"</span> |
| }</pre></div><p class="paragraph"/>As you can see an action looks very similar to a controller action and in fact you can re-use controller actions if you want. If the action successfully returns with no errors the <code>success</code> event will be triggered. In this case since we return a map, this is regarded as the "model" and is automatically placed in <a href="../guide/single.html#6.5.4 Flow Scopes" class="guide">flow scope</a>.<p class="paragraph"/> |
| In addition, in the above example we also use an exception handler to deal with errors on the line:<p class="paragraph"/><div class="code"><pre>on(Exception).to <span class="java-quote">"handleError"</span></pre></div><p class="paragraph"/>What this does is make the flow transition to a state called <code>handleError</code> in the case of an exception.<p class="paragraph"/>You can write more complex actions that interact with the flow request context:<p class="paragraph"/><div class="code"><pre>processPurchaseOrder { |
| action { |
| def a = flow.address |
| def p = flow.person |
| def pd = flow.paymentDetails |
| def cartItems = flow.cartItems |
| flow.clear()<p class="paragraph"/> def o = <span class="java-keyword">new</span> Order(person:p, shippingAddress:a, paymentDetails:pd) |
| o.invoiceNumber = <span class="java-keyword">new</span> Random().nextInt(9999999) |
| cartItems.each { o.addToItems(it) } |
| o.save() |
| [order:o] |
| } |
| on(<span class="java-quote">"error"</span>).to <span class="java-quote">"confirmPurchase"</span> |
| on(Exception).to <span class="java-quote">"confirmPurchase"</span> |
| on(<span class="java-quote">"success"</span>).to <span class="java-quote">"displayInvoice"</span> |
| }</pre></div><p class="paragraph"/>Here is a more complex action that gathers all the information accumulated from the flow scope and creates an <code>Order</code> object. It then returns the order as the model. The important thing to note here is the interaction with the request context and "flow scope".<p class="paragraph"/><h4>Transition Actions</h4><p class="paragraph"/>Another form of action is what is known as a <em class="italic">transition</em> action. A transition action is executed directly prior to state transition once an <a href="../guide/single.html#6.5.3 Flow Execution Events" class="guide">event</a> has been triggered. A trivial example of a transition action can be seen below:<p class="paragraph"/><div class="code"><pre>enterPersonalDetails { |
| on(<span class="java-quote">"submit"</span>) { |
| log.trace <span class="java-quote">"Going to enter shipping"</span> |
| }.to <span class="java-quote">"enterShipping"</span> |
| on(<span class="java-quote">"<span class="java-keyword">return</span>"</span>).to <span class="java-quote">"showCart"</span> |
| }</pre></div><p class="paragraph"/>Notice how we pass a block of the code to <code>submit</code> event that simply logs the transition. Transition states are extremely useful for <a href="../guide/single.html#6.5.5 Data Binding and Validation" class="guide">data binding and validation</a>, which is covered in a later section.<p class="paragraph"/><p class="paragraph"/><h2><a name="6.5.3 Flow Execution Events">6.5.3 Flow Execution Events</a></h2>In order to <em class="italic">transition</em> execution of a flow from one state to the next you need some way of trigger an <em class="italic">event</em> that indicates what the flow should do next. Events can be triggered from either view states or action states.<p class="paragraph"/><h4>Triggering Events from a View State</h4><p class="paragraph"/>As discussed previously the start state of the flow in a previous code listing deals with two possible events. A <code>checkout</code> event and a <code>continueShopping</code> event:<p class="paragraph"/><div class="code"><pre>def shoppingCartFlow = { |
| showCart { |
| on(<span class="java-quote">"checkout"</span>).to <span class="java-quote">"enterPersonalDetails"</span> |
| on(<span class="java-quote">"continueShopping"</span>).to <span class="java-quote">"displayCatalogue"</span> |
| } |
| … |
| }</pre></div><p class="paragraph"/>Since the <code>showCart</code> event is a view state it will render the view <code>grails-app/book/shoppingCart/showCart.gsp</code>. Within this view you need to have components that trigger flow execution. On a form this can be done use the <a href="../ref/Tags/submitButton.html" class="tags">submitButton</a> tag:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:form action=<span class="xml-quote">"shoppingCart"</span>></span> |
| <span class="xml-tag"><g:submitButton name=<span class="xml-quote">"continueShopping"</span> value=<span class="xml-quote">"Continue Shopping"</span>></span><span class="xml-tag"></g:submitButton></span> |
| <span class="xml-tag"><g:submitButton name=<span class="xml-quote">"checkout"</span> value=<span class="xml-quote">"Checkout"</span>></span><span class="xml-tag"></g:submitButton></span> |
| <span class="xml-tag"></g:form></span></pre></div><p class="paragraph"/>The form must submit back to the <code>shoppingCart</code> flow. The name attribute of each <a href="../ref/Tags/submitButton.html" class="tags">submitButton</a> tag signals which event will be triggered. If you don't have a form you can also trigger an event with the <a href="../ref/Tags/link.html" class="tags">link</a> tag as follows:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:link action=<span class="xml-quote">"shoppingCart"</span> event=<span class="xml-quote">"checkout"</span> /></span></pre></div><p class="paragraph"/><h4>Triggering Events from an Action</h4><p class="paragraph"/>To trigger an event from an <code>action</code> you need to invoke a method. For example there is the built in <code>error()</code> and <code>success()</code> methods. The example below triggers the <code>error()</code> event on validation failure in a transition action:<p class="paragraph"/><div class="code"><pre>enterPersonalDetails { |
| on(<span class="java-quote">"submit"</span>) { |
| def p = <span class="java-keyword">new</span> Person(params) |
| flow.person = p |
| <span class="java-keyword">if</span>(!p.validate())<span class="java-keyword">return</span> error() |
| }.to <span class="java-quote">"enterShipping"</span> |
| on(<span class="java-quote">"<span class="java-keyword">return</span>"</span>).to <span class="java-quote">"showCart"</span> |
| }</pre></div><p class="paragraph"/>In this case because of the error the transition action will make the flow go back to the <code>enterPersonalDetails</code> state.<p class="paragraph"/>With an action state you can also trigger events to redirect flow:<p class="paragraph"/><div class="code"><pre>shippingNeeded { |
| action { |
| <span class="java-keyword">if</span>(params.shippingRequired) yes() |
| <span class="java-keyword">else</span> no() |
| } |
| on(<span class="java-quote">"yes"</span>).to <span class="java-quote">"enterShipping"</span> |
| on(<span class="java-quote">"no"</span>).to <span class="java-quote">"enterPayment"</span> |
| }</pre></div><p class="paragraph"/><h2><a name="6.5.4 Flow Scopes">6.5.4 Flow Scopes</a></h2><h4>Scope Basics</h4><p class="paragraph"/>You'll notice from previous examples that we used a special object called <code>flow</code> to store objects within "flow scope". Grails flows have 5 different scopes you can utilize: |
| <ul class="star"> |
| <li><code>request</code> - Stores an object for the scope of the current request</li> |
| <li><code>flash</code> - Stores the object for the current and next request only</li> |
| <li><code>flow</code> - Stores objects for the scope of the flow, removing them when the flow reaches an end state</li> |
| <li><code>conversation</code> - Stores objects for the scope of the conversation including the root flow and nested subflows</li> |
| <li><code>session</code> - Stores objects inside the users session</li> |
| </ul><p class="paragraph"/><blockquote class="note"> |
| Grails service classes can be automatically scoped to a web flow scope. See the documentation on <a href="../guide/single.html#8. The Service Layer" class="guide">Services</a> for more information. |
| </blockquote><p class="paragraph"/>Also returning a model map from an action will automatically result in the model being placed in flow scope. For example, using a transition action, you can place objects within <code>flow</code> scope as follows:<p class="paragraph"/><div class="code"><pre>enterPersonalDetails { |
| on(<span class="java-quote">"submit"</span>) { |
| [person:<span class="java-keyword">new</span> Person(params)] |
| }.to <span class="java-quote">"enterShipping"</span> |
| on(<span class="java-quote">"<span class="java-keyword">return</span>"</span>).to <span class="java-quote">"showCart"</span> |
| }</pre></div><p class="paragraph"/>Be aware that a new request is always created for each state, so an object placed in request scope in an action state (for example) will not be available in a subsequent view state. Use one of the other scopes to pass objects from one state to another. Also note that Web Flow: |
| <ol> |
| <li>Moves objects from flash scope to request scope upon transition between states;</li> |
| <li>Merges objects from the flow and conversation scopes into the view model before rendering (so you shouldn't include a scope prefix when referencing these objects within a view, e.g. GSP pages).</li> |
| </ol><p class="paragraph"/><p class="paragraph"/><h4>Flow Scopes and Serialization</h4><p class="paragraph"/>When placing objects in <code>flash</code>, <code>flow</code> or <code>conversation</code> scope they must implement <code>java.io.Serializable</code> otherwise you will get an error. This has an impact on <a href="../guide/single.html#5. Object Relational Mapping (GORM)" class="guide">domain classes</a> in that domain classes are typically placed within a scope so that they can be rendered in a view. For example consider the following domain class:<p class="paragraph"/><div class="code"><pre>class Book { |
| <span class="java-object">String</span> title |
| }</pre></div><p class="paragraph"/>In order to place an instance of the <code>Book</code> class in a flow scope you will need to modify it as follows:<p class="paragraph"/><div class="code"><pre>class Book <span class="java-keyword">implements</span> Serializable { |
| <span class="java-object">String</span> title |
| }</pre></div><p class="paragraph"/>This also impacts associations and closures you declare within a domain class. For example consider this:<p class="paragraph"/><div class="code"><pre>class Book <span class="java-keyword">implements</span> Serializable { |
| <span class="java-object">String</span> title |
| Author author |
| }</pre></div><p class="paragraph"/>Here if the <code>Author</code> association is not <code>Serializable</code> you will also get an error. This also impacts closures used in <a href="../guide/single.html#5.5.1 Events and Auto Timestamping" class="guide">GORM events</a> such as <code>onLoad</code>, <code>onSave</code> and so on. The following domain class will cause an error if an instance is placed in a flow scope:<p class="paragraph"/><div class="code"><pre>class Book <span class="java-keyword">implements</span> Serializable { |
| <span class="java-object">String</span> title |
| def onLoad = { |
| println <span class="java-quote">"I'm loading"</span> |
| } |
| }</pre></div><p class="paragraph"/>The reason is that the assigned block on the <code>onLoad</code> event cannot be serialized. To get around this you should declare all events as <code>transient</code>:<p class="paragraph"/><div class="code"><pre>class Book <span class="java-keyword">implements</span> Serializable { |
| <span class="java-object">String</span> title |
| <span class="java-keyword">transient</span> onLoad = { |
| println <span class="java-quote">"I'm loading"</span> |
| } |
| }</pre></div> |
| <h2><a name="6.5.5 Data Binding and Validation">6.5.5 Data Binding and Validation</a></h2>In the section on <a href="../guide/single.html#6.5.1 Start and End States" class="guide">start and end states</a>, the start state in the first example triggered a transition to the <code>enterPersonalDetails</code> state. This state renders a view and waits for the user to enter the required information:<p class="paragraph"/><div class="code"><pre>enterPersonalDetails { |
| on(<span class="java-quote">"submit"</span>).to <span class="java-quote">"enterShipping"</span> |
| on(<span class="java-quote">"<span class="java-keyword">return</span>"</span>).to <span class="java-quote">"showCart"</span> |
| }</pre></div><p class="paragraph"/>The view contains a form with two submit buttons that either trigger the submit event or the return event:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:form action=<span class="xml-quote">"shoppingCart"</span>></span> |
| <span class="xml-comment"><!-- Other fields --></span> |
| <span class="xml-tag"><g:submitButton name=<span class="xml-quote">"submit"</span> value=<span class="xml-quote">"Continue"</span>></span><span class="xml-tag"></g:submitButton></span> |
| <span class="xml-tag"><g:submitButton name=<span class="xml-quote">"return"</span> value=<span class="xml-quote">"Back"</span>></span><span class="xml-tag"></g:submitButton></span> |
| <span class="xml-tag"></g:form></span></pre></div><p class="paragraph"/>However, what about the capturing the information submitted by the form? To to capture the form info we can use a flow transition action:<p class="paragraph"/><div class="code"><pre>enterPersonalDetails { |
| on(<span class="java-quote">"submit"</span>) { |
| flow.person = <span class="java-keyword">new</span> Person(params) |
| !flow.person.validate() ? error() : success() |
| }.to <span class="java-quote">"enterShipping"</span> |
| on(<span class="java-quote">"<span class="java-keyword">return</span>"</span>).to <span class="java-quote">"showCart"</span> |
| }</pre></div><p class="paragraph"/>Notice how we perform data binding from request parameters and place the <code>Person</code> instance within <code>flow</code> scope. Also interesting is that we perform <a href="../guide/single.html#7. Validation" class="guide">validation</a> and invoke the <code>error()</code> method if validation fails. This signals to the flow that the transition should halt and return to the <code>enterPersonalDetails</code> view so valid entries can be entered by the user, otherwise the transition should continue and go to the <code>enterShipping</code> state.<p class="paragraph"/>Like regular actions, flow actions also support the notion of <a href="../guide/single.html#6.1.10 Command Objects" class="guide">Command Objects</a> by defining the first argument of the closure:<p class="paragraph"/><div class="code"><pre>enterPersonalDetails { |
| on(<span class="java-quote">"submit"</span>) { PersonDetailsCommand cmd -> |
| flow.personDetails = cmd |
| !flow.personDetails.validate() ? error() : success() |
| }.to <span class="java-quote">"enterShipping"</span> |
| on(<span class="java-quote">"<span class="java-keyword">return</span>"</span>).to <span class="java-quote">"showCart"</span> |
| }</pre></div><h2><a name="6.5.6 Subflows and Conversations">6.5.6 Subflows and Conversations</a></h2>Grails' Web Flow integration also supports subflows. A subflow is like a flow within a flow. For example take this search flow:<p class="paragraph"/><div class="code"><pre>def searchFlow = { |
| displaySearchForm { |
| on(<span class="java-quote">"submit"</span>).to <span class="java-quote">"executeSearch"</span> |
| } |
| executeSearch { |
| action { |
| [results:searchService.executeSearch(params.q)] |
| } |
| on(<span class="java-quote">"success"</span>).to <span class="java-quote">"displayResults"</span> |
| on(<span class="java-quote">"error"</span>).to <span class="java-quote">"displaySearchForm"</span> |
| } |
| displayResults { |
| on(<span class="java-quote">"searchDeeper"</span>).to <span class="java-quote">"extendedSearch"</span> |
| on(<span class="java-quote">"searchAgain"</span>).to <span class="java-quote">"displaySearchForm"</span> |
| } |
| extendedSearch { |
| subflow(extendedSearchFlow) // <--- extended search subflow |
| on(<span class="java-quote">"moreResults"</span>).to <span class="java-quote">"displayMoreResults"</span> |
| on(<span class="java-quote">"noResults"</span>).to <span class="java-quote">"displayNoMoreResults"</span> |
| } |
| displayMoreResults() |
| displayNoMoreResults() |
| }</pre></div><p class="paragraph"/>It references a subflow in the <code>extendedSearch</code> state. The subflow is another flow entirely:<p class="paragraph"/><div class="code"><pre>def extendedSearchFlow = { |
| startExtendedSearch { |
| on(<span class="java-quote">"findMore"</span>).to <span class="java-quote">"searchMore"</span> |
| on(<span class="java-quote">"searchAgain"</span>).to <span class="java-quote">"noResults"</span> |
| } |
| searchMore { |
| action { |
| def results = searchService.deepSearch(ctx.conversation.query) |
| <span class="java-keyword">if</span>(!results)<span class="java-keyword">return</span> error() |
| conversation.extendedResults = results |
| } |
| on(<span class="java-quote">"success"</span>).to <span class="java-quote">"moreResults"</span> |
| on(<span class="java-quote">"error"</span>).to <span class="java-quote">"noResults"</span> |
| } |
| moreResults() |
| noResults() |
| }</pre></div><p class="paragraph"/>Notice how it places the <code>extendedResults</code> in conversation scope. This scope differs to flow scope as it allows you to share state that spans the whole conversation not just the flow. Also notice that the end state (either <code>moreResults</code> or <code>noResults</code> of the subflow triggers the events in the main flow:<p class="paragraph"/><div class="code"><pre>extendedSearch { |
| subflow(extendedSearchFlow) // <--- extended search subflow |
| on(<span class="java-quote">"moreResults"</span>).to <span class="java-quote">"displayMoreResults"</span> |
| on(<span class="java-quote">"noResults"</span>).to <span class="java-quote">"displayNoMoreResults"</span> |
| }</pre></div><p class="paragraph"/><h2><a name="6.6 Filters">6.6 Filters</a></h2>Although Grails <a href="../guide/single.html#6.1 Controllers" class="guide">controllers</a> support fine grained interceptors, these are only really useful when applied to a few controllers and become difficult to manage with larger applications. Filters on the other hand can be applied across a whole group of controllers, a URI space or a to a specific action. Filters are far easier to plug-in and maintain completely separately to your main controller logic and are useful for all sorts of cross cutting concerns such as security, logging, and so on.<p class="paragraph"/><h2><a name="6.6.1 Applying Filters">6.6.1 Applying Filters</a></h2>To create a filter create a class that ends with the convention <code>Filters</code> in the <code>grails-app/conf</code> directory. Within this class define a code block called <code>filters</code> that contains the filter definitions:<p class="paragraph"/><div class="code"><pre>class ExampleFilters { |
| def filters = { |
| // your filters here |
| } |
| }</pre></div><p class="paragraph"/>Each filter you define within the <code>filters</code> block has a name and a scope. The name is the method name and the scope is defined using named arguments. For example if you need to define a filter that applies to all controllers and all actions you can use wildcards:<p class="paragraph"/><div class="code"><pre>sampleFilter(controller:'*', action:'*') { |
| // interceptor definitions |
| }</pre></div><p class="paragraph"/>The scope of the filter can be one of the following things: |
| <ul class="star"> |
| <li>A controller and/or action name pairing with optional wildcards</li> |
| <li>A URI, with Ant path matching syntax</li> |
| </ul><p class="paragraph"/>Filter rule attributes: |
| <ul class="star"> |
| <li><code>controller</code> - controller matching pattern, by default * is replaced with .* and a regex is compiled</li> |
| <li><code>action</code> - action matching pattern, by default * is replaced with .* and a regex is compiled</li> |
| <li><code>regex</code> (true/false) - use regex syntax (don't replace '*' with '.*')</li> |
| <li><code>uri</code> - a uri to match, expressed with as Ant style path (e.g. /book/**)</li> |
| <li><code>find</code> (true/false) - rule matches with partial match (see java.util.regex.Matcher.find())</li> |
| <li><code>invert</code> (true/false) - invert the rule (NOT rule)</li> |
| </ul><p class="paragraph"/>Some examples of filters include: |
| <ul class="star"> |
| <li>All controllers and actions</li> |
| </ul><p class="paragraph"/><div class="code"><pre>all(controller:'*', action:'*') {<p class="paragraph"/>}</pre></div> |
| <ul class="star"> |
| <li>Only for the <code>BookController</code></li> |
| </ul><p class="paragraph"/><div class="code"><pre>justBook(controller:'book', action:'*') {<p class="paragraph"/>}</pre></div> |
| <ul class="star"> |
| <li>All controllers except the <code>BookController</code></li> |
| </ul><p class="paragraph"/><div class="code"><pre>notBook(controller:'book', invert:<span class="java-keyword">true</span>) {<p class="paragraph"/>}</pre></div> |
| <ul class="star"> |
| <li>All actions containing 'save' in the action name</li> |
| </ul><p class="paragraph"/><div class="code"><pre>saveInActionName(action:'save', find:<span class="java-keyword">true</span>) {<p class="paragraph"/>}</pre></div> |
| <ul class="star"> |
| <li>Applied to a URI space</li> |
| </ul><p class="paragraph"/><div class="code"><pre>someURIs(uri:'/book/**') {<p class="paragraph"/>}</pre></div> |
| <ul class="star"> |
| <li>Applied to all URIs</li> |
| </ul><p class="paragraph"/><div class="code"><pre>allURIs(uri:'/**') {<p class="paragraph"/>}</pre></div><p class="paragraph"/>In addition, the order in which you define the filters within the <code>filters</code> code block dictates the order in which they are executed. To control the order of execution between <code>Filters</code> classes, you can use the <code>dependsOn</code> property discussed in <a href="../guide/single.html#6.6.4 Filter Dependencies" class="guide">filter dependencies</a> section. |
| <h2><a name="6.6.2 Filter Types">6.6.2 Filter Types</a></h2>Within the body of the filter you can then define one or several of the following interceptor types for the filter: |
| <ul class="star"> |
| <li><code>before</code> - Executed before the action. Can return false to indicate all future filters and the action should not execute</li> |
| <li><code>after</code> - Executed after an action. Takes a first argument as the view model</li> |
| <li><code>afterView</code> - Executed after view rendering</li> |
| </ul><p class="paragraph"/>For example to fulfill the common authentication use case you could define a filter as follows:<p class="paragraph"/><div class="code"><pre>class SecurityFilters { |
| def filters = { |
| loginCheck(controller:'*', action:'*') { |
| before = { |
| <span class="java-keyword">if</span>(!session.user && !actionName.equals('login')) { |
| redirect(action:'login') |
| <span class="java-keyword">return</span> <span class="java-keyword">false</span> |
| } |
| }<p class="paragraph"/> } |
| } |
| }</pre></div><p class="paragraph"/> |
| Here the <code>loginCheck</code> filter uses a <code>before</code> interceptor to execute a block of code that checks if a user is in the session and if not redirects to the login action. Note how returning false ensure that the action itself is not executed. |
| <h2><a name="6.6.3 Variables and Scopes">6.6.3 Variables and Scopes</a></h2>Filters support all the common properties available to <a href="../guide/single.html#6.1 Controllers" class="guide">controllers</a> and <a href="../guide/single.html#6.3 Tag Libraries" class="guide">tag libraries</a>, plus the application context: |
| <ul class="star"> |
| <li><a href="../ref/Controllers/request.html" class="controllers">request</a> - The HttpServletRequest object</li> |
| <li><a href="../ref/Controllers/response.html" class="controllers">response</a> - The HttpServletResponse object</li> |
| <li><a href="../ref/Controllers/session.html" class="controllers">session</a> - The HttpSession object</li> |
| <li><a href="../ref/Controllers/servletContext.html" class="controllers">servletContext</a> - The ServletContext object</li> |
| <li><a href="../ref/Controllers/flash.html" class="controllers">flash</a> - The flash object</li> |
| <li><a href="../ref/Controllers/params.html" class="controllers">params</a> - The request parameters object</li> |
| <li><a href="../ref/Controllers/actionName.html" class="controllers">actionName</a> - The action name that is being dispatched to</li> |
| <li><a href="../ref/Controllers/controllerName.html" class="controllers">controllerName</a> - The controller name that is being dispatched to</li> |
| <li><a href="../ref/Controllers/grailsApplication.html" class="controllers">grailsApplication</a> - The Grails application currently running</li> |
| <li><a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/ApplicationContext.html" class="api">applicationContext</a> - The ApplicationContext object</li> |
| </ul><p class="paragraph"/>However, filters only support a subset of the methods available to controllers and tag libraries. These include: |
| <ul class="star"> |
| <li><a href="../ref/Controllers/redirect.html" class="controllers">redirect</a> - For redirects to other controllers and actions</li> |
| <li><a href="../ref/Controllers/render.html" class="controllers">render</a> - For rendering custom responses</li> |
| </ul><p class="paragraph"/><h2><a name="6.6.4 Filter Dependencies">6.6.4 Filter Dependencies</a></h2>In a <code>Filters</code> class, you can specify any other <code>Filters</code> classes that should first be executed using the <code>dependsOn</code> property. The <code>dependsOn</code> property is used when a <code>Filters</code> class depends on the behavior of another <code>Filters</code> class (e.g. setting up the environment, modifying the request/session, etc.) and is defined as an array of <code>Filters</code> classes.<p class="paragraph"/>Take the following example <code>Filters</code> classes:<p class="paragraph"/><div class="code"><pre>class MyFilters { |
| def dependsOn = [MyOtherFilters]<p class="paragraph"/> def filters = { |
| checkAwesome(uri:<span class="java-quote">"/*"</span>) { |
| before = { |
| <span class="java-keyword">if</span> (request.isAwesome) { // <span class="java-keyword">do</span> something awesome } |
| } |
| }<p class="paragraph"/> checkAwesome2(uri:<span class="java-quote">"/*"</span>) { |
| before = { |
| <span class="java-keyword">if</span> (request.isAwesome) { // <span class="java-keyword">do</span> something <span class="java-keyword">else</span> awesome } |
| } |
| } |
| } |
| }<p class="paragraph"/>class MyOtherFilters { |
| def filters = { |
| makeAwesome(uri:<span class="java-quote">"/*"</span>) { |
| before = { |
| request.isAwesome = <span class="java-keyword">true</span>; |
| } |
| } |
| doNothing(uri:<span class="java-quote">"/*"</span>) { |
| before = { |
| // <span class="java-keyword">do</span> nothing |
| } |
| } |
| } |
| }</pre></div><p class="paragraph"/>MyFilters specifically <code>dependsOn</code> MyOtherFilters. This will cause all the filters in MyOtherFilters to be executed before those in MyFilters, given their scope matches the current request. For a request of "/test", which will match the scope of every filter in the example, the execution order would be as follows: |
| <ul class="star"> |
| <li>MyOtherFilters - makeAwesome</li> |
| <li>MyOtherFilters - doNothing</li> |
| <li>MyFilters - checkAwesome</li> |
| <li>MyFilters - checkAwesome2</li> |
| </ul><p class="paragraph"/>The filters within the MyOtherFilters class are processed in order first, followed by the filters in the MyFilters class. Execution order between <code>Filters</code> classes are enabled and the execution order of filters within each <code>Filters</code> class are preserved.<p class="paragraph"/>If any cyclical dependencies are detected, the filters with cyclical dependencies will be added to the end of the filter chain and processing will continue. Information about any cyclical dependencies that are detected will be written to the logs. Ensure that your root logging level is set to at least WARN or configure an appender for the Grails Filters Plugin (org.codehaus.groovy.grails.plugins.web.filters.FiltersGrailsPlugin) when debugging filter dependency issues. |
| <h2><a name="6.7 Ajax">6.7 Ajax</a></h2>Ajax stands for Asynchronous Javascript and XML and is the driving force behind the shift to richer web applications. These types of applications in general are better suited to agile, dynamic frameworks written in languages like <a href="http://www.ruby-lang.org/" target="blank">Ruby</a> and <a href="http://groovy.codehaus.org." target="blank">Groovy</a> Grails provides support for building Ajax applications through its Ajax tag library for a full list of these see the Tag Library Reference. |
| <h2><a name="6.7.1 Ajax using Prototype">6.7.1 Ajax using Prototype</a></h2>By default Grails ships with the <a href="http://www.prototypejs.org/" target="blank">Prototype</a> library, but through the <a href="../guide/single.html#12. Plug-ins" class="guide">Plug-in system</a> provides support for other frameworks such as <a href="http://dojotoolkit.org/," target="blank">Dojo</a> <a href="http://developer.yahoo.com/yui/" target="blank">Yahoo UI</a> and the <a href="http://code.google.com/webtoolkit/." target="blank">Google Web Toolkit</a><p class="paragraph"/>This section covers Grails' support for Prototype. To get started you need to add this line to the <code><head></code> tag of your page:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:javascript library=<span class="xml-quote">"prototype"</span> /></span></pre></div><p class="paragraph"/>This uses the <a href="../ref/Tags/javascript.html" class="tags">javascript</a> tag to automatically place the correct references in place for Prototype. If you require <a href="http://script.aculo.us/" target="blank">Scriptaculous</a> too you can do the following instead:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:javascript library=<span class="xml-quote">"scriptaculous"</span> /></span></pre></div><p class="paragraph"/>This works because of Grails' support for adaptive tag libraries. Thanks to Grails' plugin system there is support for a number of different Ajax libraries including (but not limited to): |
| <ul class="star"> |
| <li>prototype</li> |
| <li>dojo</li> |
| <li>yui</li> |
| <li>mootools</li> |
| </ul><p class="paragraph"/><h2><a name="6.7.1.1 Remoting Linking">6.7.1.1 Remoting Linking</a></h2>Remote content can be loaded in a number of ways, the most commons way is through the <a href="../ref/Tags/remoteLink.html" class="tags">remoteLink</a> tag. This tag allows the creation of HTML anchor tags that perform an asynchronous request and optionally set the response in an element. The simplest way to create a remote link is as follows:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:remoteLink action=<span class="xml-quote">"delete"</span> id=<span class="xml-quote">"1"</span>></span>Delete Book<span class="xml-tag"></g:remoteLink></span></pre></div><p class="paragraph"/>The above link sends an asynchronous request to the <code>delete</code> action of the current controller with an id of <code>1</code>. <h2><a name="6.7.1.2 Updating Content">6.7.1.2 Updating Content</a></h2>This is great, but usually you would want to provide some kind of feedback to the user as to what has happened:<p class="paragraph"/><div class="code"><pre>def delete = { |
| def b = Book.get( params.id ) |
| b.delete() |
| render <span class="java-quote">"Book ${b.id} was deleted"</span> |
| }</pre></div><p class="paragraph"/>GSP code:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><div id=<span class="xml-quote">"message"</span>></span><span class="xml-tag"></div></span> |
| <span class="xml-tag"><g:remoteLink action=<span class="xml-quote">"delete"</span> id=<span class="xml-quote">"1"</span> update=<span class="xml-quote">"message"</span>></span>Delete Book<span class="xml-tag"></g:remoteLink></span></pre></div><p class="paragraph"/>The above example will call the action and set the contents of the <code>message</code> <code>div</code> to the response in this case <code>"Book 1 was deleted"</code>. This is done by the <code>update</code> attribute on the tag, which can also take a map to indicate what should be updated on failure:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><div id=<span class="xml-quote">"message"</span>></span><span class="xml-tag"></div></span> |
| <span class="xml-tag"><div id=<span class="xml-quote">"error"</span>></span><span class="xml-tag"></div></span> |
| <span class="xml-tag"><g:remoteLink action=<span class="xml-quote">"delete"</span> id=<span class="xml-quote">"1"</span> |
| update=<span class="xml-quote">"[success:'message',failure:'error']"</span>></span>Delete Book<span class="xml-tag"></g:remoteLink></span></pre></div><p class="paragraph"/>Here the <code>error</code> div will be updated if the request failed.<h2><a name="6.7.1.3 Remote Form Submission">6.7.1.3 Remote Form Submission</a></h2>An HTML form can also be submitted asynchronously in one of two ways. Firstly using the <a href="../ref/Tags/formRemote.html" class="tags">formRemote</a> tag which expects similar attributes to those for the <a href="../ref/Tags/remoteLink.html" class="tags">remoteLink</a> tag:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:formRemote url=<span class="xml-quote">"[controller:'book',action:'delete']"</span> |
| update=<span class="xml-quote">"[success:'message',failure:'error']"</span>></span> |
| <span class="xml-tag"><input type=<span class="xml-quote">"hidden"</span> name=<span class="xml-quote">"id"</span> value=<span class="xml-quote">"1"</span> /></span> |
| <span class="xml-tag"><input type=<span class="xml-quote">"submit"</span> value=<span class="xml-quote">"Delete Book!"</span> /></span> |
| <span class="xml-tag"></g:formRemote ></span></pre></div><p class="paragraph"/>Or alternatively you can use the <a href="../ref/Tags/submitToRemote.html" class="tags">submitToRemote</a> tag to create a submit button. This allows some buttons to submit remotely and some not depending on the action:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><form action=<span class="xml-quote">"delete"</span>></span> |
| <span class="xml-tag"><input type=<span class="xml-quote">"hidden"</span> name=<span class="xml-quote">"id"</span> value=<span class="xml-quote">"1"</span> /></span> |
| <span class="xml-tag"><g:submitToRemote action=<span class="xml-quote">"delete"</span> update=<span class="xml-quote">"[success:'message',failure:'error']"</span> /></span> |
| <span class="xml-tag"></form></span></pre></div><p class="paragraph"/><h2><a name="6.7.1.4 Ajax Events">6.7.1.4 Ajax Events</a></h2>Specific javascript can be called if certain events occur, all the events start with the "on" prefix and allow you to give feedback to the user where appropriate, or take other action:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:remoteLink action=<span class="xml-quote">"show"</span> |
| id=<span class="xml-quote">"1"</span> |
| update=<span class="xml-quote">"success"</span> |
| onLoading=<span class="xml-quote">"showProgress()"</span> |
| onComplete=<span class="xml-quote">"hideProgress()"</span>></span>Show Book 1<span class="xml-tag"></g:remoteLink></span></pre></div><p class="paragraph"/>The above code will execute the "showProgress()" function which may show a progress bar or whatever is appropriate. Other events include: |
| <ul class="star"> |
| <li><code>onSuccess</code> - The javascript function to call if successful</li> |
| <li><code>onFailure</code> - The javascript function to call if the call failed</li> |
| <li><code>on_ERROR_CODE</code> - The javascript function to call to handle specified error codes (eg on404="alert('not found!')")</li> |
| <li><code>onUninitialized</code> - The javascript function to call the a ajax engine failed to initialise</li> |
| <li><code>onLoading</code> - The javascript function to call when the remote function is loading the response</li> |
| <li><code>onLoaded</code> - The javascript function to call when the remote function is completed loading the response</li> |
| <li><code>onComplete</code> - The javascript function to call when the remote function is complete, including any updates</li> |
| </ul><p class="paragraph"/>If you need a reference to the <code>XmlHttpRequest</code> object you can use the implicit event parameter <code>e</code> to obtain it:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:javascript></span> |
| function fireMe(e) { |
| alert(<span class="xml-quote">"XmlHttpRequest = "</span> + e) |
| } |
| } |
| <span class="xml-tag"></g:javascript></span> |
| <span class="xml-tag"><g:remoteLink action=<span class="xml-quote">"example"</span> |
| update=<span class="xml-quote">"success"</span> |
| onSuccess=<span class="xml-quote">"fireMe(e)"</span>></span>Ajax Link<span class="xml-tag"></g:remoteLink></span></pre></div><p class="paragraph"/><h2><a name="6.7.2 Ajax with Dojo">6.7.2 Ajax with Dojo</a></h2>Grails features an external plug-in to add <a href="http://dojotoolkit.org/" target="blank">Dojo</a> support to Grails. To install the plug-in type the following command from the root of your project in a terminal window:<p class="paragraph"/><div class="code"><pre>grails install-plugin dojo</pre></div><p class="paragraph"/>This will download the current supported version of Dojo and install it into your Grails project. With that done you can add the following reference to the top of your page:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:javascript library=<span class="xml-quote">"dojo"</span> /></span></pre></div><p class="paragraph"/>Now all of Grails tags such as <a href="../ref/Tags/remoteLink.html" class="tags">remoteLink</a>, <a href="../ref/Tags/formRemote.html" class="tags">formRemote</a> and <a href="../ref/Tags/submitToRemote.html" class="tags">submitToRemote</a> work with Dojo remoting.<h2><a name="6.7.3 Ajax with GWT">6.7.3 Ajax with GWT</a></h2>Grails also features support for the <a href="http://code.google.com/webtoolkit/" target="blank">Google Web Toolkit</a> through a plug-in comprehensive <a href="http://grails.org/GWT+Plugin" target="blank">documentation</a> for can be found on the Grails wiki.<h2><a name="6.7.4 Ajax on the Server">6.7.4 Ajax on the Server</a></h2>Although Ajax features the X for XML there are a number of different ways to implement Ajax which are typically broken down into: |
| <ul class="star"> |
| <li>Content Centric Ajax - Where you merely use the HTML result of a remote call to update the page</li> |
| <li>Data Centric Ajax - Where you actually send an XML or JSON response from the server and programmatically update the page</li> |
| <li>Script Centric Ajax - Where the server sends down a stream of Javascript to be evaluated on the fly</li> |
| </ul><p class="paragraph"/>Most of the examples in the <a href="../guide/single.html#6.7 Ajax" class="guide">Ajax</a> section cover Content Centric Ajax where you are updating the page, but you may also want to use Data Centric or Script Centric. This guide covers the different styles of Ajax.<p class="paragraph"/><h4>Content Centric Ajax</h4><p class="paragraph"/>Just to re-cap, content centric Ajax involves sending some HTML back from the server and is typically done by rendering a template with the <a href="../ref/Controllers/render.html" class="controllers">render</a> method:<p class="paragraph"/><div class="code"><pre>def showBook = { |
| def b = Book.get(params.id)<p class="paragraph"/> render(template:<span class="java-quote">"bookTemplate"</span>, model:[book:b]) |
| }</pre></div><p class="paragraph"/>Calling this on the client involves using the <a href="../ref/Tags/remoteLink.html" class="tags">remoteLink</a> tag:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:remoteLink action=<span class="xml-quote">"showBook"</span> id=<span class="xml-quote">"${book.id}"</span> |
| update=<span class="xml-quote">"book${book.id}"</span>></span>Update Book<span class="xml-tag"></g:remoteLink></span><p class="paragraph"/><span class="xml-tag"><div id=<span class="xml-quote">"book${book.id}"</span>></span> |
| <span class="xml-comment"><!--existing book mark-up --></span> |
| <span class="xml-tag"></div></span></pre></div><p class="paragraph"/><h4>Data Centric Ajax with JSON</h4><p class="paragraph"/>Data Centric Ajax typically involves evaluating the response on the client and updating programmatically. For a JSON response with Grails you would typically use Grails' <a href="../guide/single.html#6.1.7 XML and JSON Responses" class="guide">JSON marshaling</a> capability:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.converters.*<p class="paragraph"/>def showBook = { |
| def b = Book.get(params.id)<p class="paragraph"/> render b as JSON |
| }</pre></div><p class="paragraph"/>And then on the client parse the incoming JSON request using an Ajax event handler:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:javascript></span> |
| function updateBook(e) { |
| var book = eval(<span class="xml-quote">"("</span>+e.responseText+<span class="xml-quote">")"</span>) // evaluate the JSON |
| $(<span class="xml-quote">"book"</span> + book.id + <span class="xml-quote">"_title"</span>).innerHTML = book.title |
| } |
| <span class="xml-tag"><g:javascript></span> |
| <span class="xml-tag"><g:remoteLink action=<span class="xml-quote">"test"</span> update=<span class="xml-quote">"foo"</span> onSuccess=<span class="xml-quote">"updateBook(e)"</span>></span>Update Book<span class="xml-tag"></g:remoteLink></span> |
| <span class="xml-tag"><g:set var=<span class="xml-quote">"bookId"</span>></span>book${book.id}<span class="xml-tag"></g:set></span> |
| <span class="xml-tag"><div id=<span class="xml-quote">"${bookId}"</span>></span> |
| <span class="xml-tag"><div id=<span class="xml-quote">"${bookId}_title"</span>></span>The Stand<span class="xml-tag"></div></span> |
| <span class="xml-tag"></div></span></pre></div><p class="paragraph"/><h4>Data Centric Ajax with XML</h4><p class="paragraph"/>On the server side using XML is equally trivial:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.converters.*<p class="paragraph"/>def showBook = { |
| def b = Book.get(params.id)<p class="paragraph"/> render b as XML |
| }</pre></div><p class="paragraph"/>However, since DOM is involved the client gets more complicated:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:javascript></span> |
| function updateBook(e) { |
| var xml = e.responseXML |
| var id = xml.getElementsByTagName(<span class="xml-quote">"book"</span>).getAttribute(<span class="xml-quote">"id"</span>) |
| $(<span class="xml-quote">"book"</span> + id + <span class="xml-quote">"_title"</span>) = xml.getElementsByTagName(<span class="xml-quote">"title"</span>)[0].textContent |
| } |
| <span class="xml-tag"><g:javascript></span> |
| <span class="xml-tag"><g:remoteLink action=<span class="xml-quote">"test"</span> update=<span class="xml-quote">"foo"</span> onSuccess=<span class="xml-quote">"updateBook(e)"</span>></span>Update Book<span class="xml-tag"></g:remoteLink></span> |
| <span class="xml-tag"><g:set var=<span class="xml-quote">"bookId"</span>></span>book${book.id}<span class="xml-tag"></g:set></span> |
| <span class="xml-tag"><div id=<span class="xml-quote">"${bookId}"</span>></span> |
| <span class="xml-tag"><div id=<span class="xml-quote">"${bookId}_title"</span>></span>The Stand<span class="xml-tag"></div></span> |
| <span class="xml-tag"></div></span></pre></div><p class="paragraph"/><h4>Script Centric Ajax with JavaScript</h4><p class="paragraph"/>Script centric Ajax involves actually sending Javascript back that gets evaluated on the client. An example of this can be seen below:<p class="paragraph"/><div class="code"><pre>def showBook = { |
| def b = Book.get(params.id)<p class="paragraph"/> response.contentType = <span class="java-quote">"text/javascript"</span> |
| <span class="java-object">String</span> title = b.title.encodeAsJavascript() |
| render <span class="java-quote">"$('book${b.id}_title')='${title}'"</span> |
| }</pre></div><p class="paragraph"/>The important thing to remember is to set the <code>contentType</code> to <code>text/javascript</code>. If you are using Prototype on the client the returned Javascript will automatically be evaluated due to this <code>contentType</code> setting.<p class="paragraph"/>Obviously in this case it is critical that you have an agreed client-side API as you don't want changes on the client breaking the server. This is one of the reasons Rails has something like RJS. Although Grails does not currently have a feature such as RJS there is a <a href="http://grails.org/Dynamic+Javascript+Plugin" target="blank">Dynamic JavaScript Plug-in</a> that offers similar capabilities. |
| <h2><a name="6.8 Content Negotiation">6.8 Content Negotiation</a></h2>Grails has built in support for <a href="http://en.wikipedia.org/wiki/Content_negotiation" target="blank">Content negotiation</a> using either the HTTP <code>Accept</code> header, an explicit format request parameter or the extension of a mapped URI.<p class="paragraph"/><h4>Configuring Mime Types</h4><p class="paragraph"/>Before you can start dealing with content negotiation you need to tell Grails what content types you wish to support. By default Grails comes configured with a number of different content types within <code>grails-app/conf/Config.groovy</code> using the <code>grails.mime.types</code> setting:<p class="paragraph"/><div class="code"><pre>grails.mime.types = [ xml: ['text/xml', 'application/xml'], |
| text: 'text-plain', |
| js: 'text/javascript', |
| rss: 'application/rss+xml', |
| atom: 'application/atom+xml', |
| css: 'text/css', |
| csv: 'text/csv', |
| all: '*/*', |
| json: 'text/json', |
| html: ['text/html','application/xhtml+xml'] |
| ]</pre></div><p class="paragraph"/>The above bit of configuration allows Grails to detect to format of a request containing either the 'text/xml' or 'application/xml' media types as simply 'xml'. You can add your own types by simply adding new entries into the map.<p class="paragraph"/><h4>Content Negotiation using the Accept header</h4><p class="paragraph"/>Every incoming HTTP request has a special <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html" target="blank">Accept</a> header that defines what media types (or mime types) a client can "accept". In older browsers this is typically:<p class="paragraph"/><div class="code"><pre>*/*</pre></div><p class="paragraph"/>Which simply means anything. However, on newer browser something all together more useful is sent such as (an example of a Firefox <code>Accept</code> header):<p class="paragraph"/><div class="code"><pre>text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5</pre></div><p class="paragraph"/>Grails parses this incoming format and adds a <code>property</code> to the <a href="../ref/Servlet API/request.html" class="servletAPI">request</a> object that outlines the preferred request format. For the above example the following assertion would pass:<p class="paragraph"/><div class="code"><pre>assert 'html' == request.format</pre></div><p class="paragraph"/>Why? The <code>text/html</code> media type has the highest "quality" rating of 0.9, therefore is the highest priority. If you have an older browser as mentioned previously the result is slightly different:<p class="paragraph"/><div class="code"><pre>assert 'all' == request.format</pre></div><p class="paragraph"/>In this case 'all' possible formats are accepted by the client. To deal with different kinds of requests from <a href="../guide/single.html#6.1 Controllers" class="guide">Controllers</a> you can use the <a href="../ref/Controllers/withFormat.html" class="controllers">withFormat</a> method that acts as kind of a switch statement:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.converters.*<p class="paragraph"/>class BookController { |
| def books |
| def list = { |
| <span class="java-keyword">this</span>.books = Book.list() |
| withFormat { |
| html bookList:books |
| js { render <span class="java-quote">"alert('hello')"</span> } |
| xml { render books as XML } |
| } |
| } |
| }</pre></div><p class="paragraph"/>What happens here is that if the preferred format is <code>html</code> then Grails will execute the <code>html()</code> call only. What this is does is make Grails look for a view called either <code>grails-app/views/books/list.html.gsp</code> or <code>grails-app/views/books/list.gsp</code>. If the format is <code>xml</code> then the closure will be invoked and an XML response rendered.<p class="paragraph"/>How do we handle the "all" format? Simply order the content-types within your <code>withFormat</code> block so that whichever one you want executed comes first. So in the above example, "all" will trigger the <code>html</code> handler.<p class="paragraph"/><blockquote class="note"> |
| When using <a href="../ref/Controllers/withFormat.html" class="controllers">withFormat</a> make sure it is the last call in your controller action as the return value of the <code>withFormat</code> method is used by the action to dictate what happens next. |
| </blockquote><p class="paragraph"/><h4>Content Negotiation with the format Request Parameter</h4><p class="paragraph"/>If fiddling with request headers if not your favorite activity you can override the format used by specifying a <code>format</code> request parameter:<p class="paragraph"/><div class="code"><pre>/book/list?format=xml</pre></div><p class="paragraph"/>You can also define this parameter in the <a href="../guide/single.html#6.4 URL Mappings" class="guide">URL Mappings</a> definition:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/book/list"</span>(controller:<span class="java-quote">"book"</span>, action:<span class="java-quote">"list"</span>) { |
| format = <span class="java-quote">"xml"</span> |
| }</pre></div><p class="paragraph"/><h4>Content Negotiation with URI Extensions</h4><p class="paragraph"/>Grails also supports content negotiation via URI extensions. For example given the following URI:<p class="paragraph"/><div class="code"><pre>/book/list.xml</pre></div><p class="paragraph"/>Grails will shave off the extension and map it to <code>/book/list</code> instead whilst simultaneously setting the content format to <code>xml</code> based on this extension. This behaviour is enabled by default, so if you wish to turn it off, you must set the <code>grails.mime.file.extensions</code> property in <code>grails-app/conf/Config.groovy</code> to <code>false</code>:<p class="paragraph"/><div class="code"><pre>grails.mime.file.extensions = <span class="java-keyword">false</span></pre></div><p class="paragraph"/><h4>Testing Content Negotiation</h4><p class="paragraph"/>To test content negotiation in an integration test (see the section on <a href="../guide/single.html#9. Testing" class="guide">Testing</a>) you can either manipulate the incoming request headers:<p class="paragraph"/><div class="code"><pre>void testJavascriptOutput() { |
| def controller = <span class="java-keyword">new</span> TestController() |
| controller.request.addHeader <span class="java-quote">"Accept"</span>, |
| <span class="java-quote">"text/javascript, text/html, application/xml, text/xml, */*"</span><p class="paragraph"/> controller.testAction() |
| assertEquals <span class="java-quote">"alert('hello')"</span>, controller.response.contentAsString |
| }</pre></div><p class="paragraph"/>Or you can set the format parameter to achieve a similar effect:<p class="paragraph"/><div class="code"><pre>void testJavascriptOutput() { |
| def controller = <span class="java-keyword">new</span> TestController() |
| controller.params.format = 'js'<p class="paragraph"/> controller.testAction() |
| assertEquals <span class="java-quote">"alert('hello')"</span>, controller.response.contentAsString |
| }</pre></div> |
| <h1><a name="7. Validation">7. Validation</a></h1>Grails validation capability is built on <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/validation/package-summary.html" target="blank">Spring's Validator API</a> and data binding capabilities. However Grails takes this further and provides a unified way to define validation "constraints" with its constraints mechanism.<p class="paragraph"/>Constraints in Grails are a way to declaratively specify validation rules. Most commonly they are applied to <a href="../guide/single.html#5. Object Relational Mapping (GORM)" class="guide">domain classes</a>, however <a href="../guide/single.html#6.4 URL Mappings" class="guide">URL Mappings</a> and <a href="../guide/single.html#6.1.10 Command Objects" class="guide">Command Objects</a> also support constraints.<p class="paragraph"/><p class="paragraph"/><h2><a name="7.1 Declaring Constraints">7.1 Declaring Constraints</a></h2>Within a domain class a <a href="../ref/Domain Classes/constraints.html" class="domainClasses">constraints</a> are defined with the constraints property that is assigned a code block:<p class="paragraph"/><div class="code"><pre>class User { |
| <span class="java-object">String</span> login |
| <span class="java-object">String</span> password |
| <span class="java-object">String</span> email |
| <span class="java-object">Integer</span> age<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| … |
| } |
| }</pre></div><p class="paragraph"/>You then use method calls that match the property name for which the constraint applies in combination with named parameters to specify constraints:<p class="paragraph"/> |
| <div class="code"><pre>class User { |
| ...<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| login(size:5..15, blank:<span class="java-keyword">false</span>, unique:<span class="java-keyword">true</span>) |
| password(size:5..15, blank:<span class="java-keyword">false</span>) |
| email(email:<span class="java-keyword">true</span>, blank:<span class="java-keyword">false</span>) |
| age(min:18, nullable:<span class="java-keyword">false</span>) |
| } |
| }</pre></div><p class="paragraph"/>In this example we've declared that the <code>login</code> property must be between 5 and 15 characters long, it cannot be blank and must be unique. We've all applied other constraints to the <code>password</code>, <code>email</code> and <code>age</code> properties.<p class="paragraph"/><blockquote class="note"> |
| A complete reference for the available constraints can be found in the left navigation bar (if you have frames enabled) under the Constraints heading. |
| </blockquote> |
| <h2><a name="7.2 Validating Constraints">7.2 Validating Constraints</a></h2><h4>Validation Basics</h4><p class="paragraph"/>To validate a domain class you can call the <a href="../ref/Domain Classes/validate.html" class="domainClasses">validate</a> method on any instance:<p class="paragraph"/><div class="code"><pre>def user = <span class="java-keyword">new</span> User(params)<p class="paragraph"/><span class="java-keyword">if</span>(user.validate()) { |
| // <span class="java-keyword">do</span> something with user |
| } |
| <span class="java-keyword">else</span> { |
| user.errors.allErrors.each { |
| println it |
| } |
| }</pre></div><p class="paragraph"/>The <code>errors</code> property on domain classes is an instance of the Spring <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/validation/Errors.html" class="api">Errors</a> interface. The <code>Errors</code> interface provides methods to navigate the validation errors and also retrieve the original values.<p class="paragraph"/><h4>Validation Phases</h4><p class="paragraph"/>Within Grails there are essentially 2 phases of validation, the first phase is <a href="../guide/single.html#6.1.6 Data Binding" class="guide">data binding</a> which occurs when you bind request parameters onto an instance such as:<p class="paragraph"/><div class="code"><pre>def user = <span class="java-keyword">new</span> User(params)</pre></div><p class="paragraph"/>At this point you may already have errors in the <code>errors</code> property due to type conversion (such as converting Strings to Dates). You can check these and obtain the original input value using the <code>Errors</code> API:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">if</span>(user.hasErrors()) { |
| <span class="java-keyword">if</span>(user.errors.hasFieldErrors(<span class="java-quote">"login"</span>)) { |
| println user.errors.getFieldError(<span class="java-quote">"login"</span>).rejectedValue |
| } |
| }</pre></div><p class="paragraph"/>The second phase of validation happens when you call <a href="../ref/Domain Classes/validate.html" class="domainClasses">validate</a> or <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a>. This is when Grails will validate the bound values againts the <a href="../ref/Domain Classes/constraints.html" class="domainClasses">constraints</a> you defined. For example, by default the persistent <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> method calls <code>validate</code> before executing hence allowing you to write code like:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">if</span>(user.save()) { |
| <span class="java-keyword">return</span> user |
| } |
| <span class="java-keyword">else</span> { |
| user.errors.allErrors.each { |
| println it |
| } |
| }</pre></div><p class="paragraph"/><h2><a name="7.3 Validation on the Client">7.3 Validation on the Client</a></h2><h4>Displaying Errors</h4><p class="paragraph"/>Typically if you get a validation error you want to redirect back to the view for rendering. Once there you need some way of rendering errors. Grails supports a rich set of tags for dealing with errors. If you simply want to render the errors as a list you can use <a href="../ref/Tags/renderErrors.html" class="tags">renderErrors</a>:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:renderErrors bean=<span class="xml-quote">"${user}"</span> /></span></pre></div><p class="paragraph"/>If you need more control you can use <a href="../ref/Tags/hasErrors.html" class="tags">hasErrors</a> and <a href="../ref/Tags/eachError.html" class="tags">eachError</a>:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:hasErrors bean=<span class="xml-quote">"${user}"</span>></span> |
| <span class="xml-tag"><ul></span> |
| <span class="xml-tag"><g:eachError var=<span class="xml-quote">"err"</span> bean=<span class="xml-quote">"${user}"</span>></span> |
| <span class="xml-tag"><li></span>${err}<span class="xml-tag"></li></span> |
| <span class="xml-tag"></g:eachError></span> |
| <span class="xml-tag"></ul></span> |
| <span class="xml-tag"></g:hasErrors></span></pre></div><p class="paragraph"/><h4>Highlighting Errors</h4><p class="paragraph"/>It is often useful to highlight using a red box or some indicator when a field has been incorrectly input. This can also be done with the <a href="../ref/Tags/hasErrors.html" class="tags">hasErrors</a> by invoking it as a method. For example:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><div class='value ${hasErrors(bean:user,field:'login','errors')}'></span> |
| <span class="xml-tag"><input type=<span class="xml-quote">"text"</span> name=<span class="xml-quote">"login"</span> value=<span class="xml-quote">"${fieldValue(bean:user,field:'login')}"</span>/></span> |
| <span class="xml-tag"></div></span></pre></div><p class="paragraph"/>What this code does is check if the <code>login</code> field of the <code>user</code> bean has any errors and if it does adds an <code>errors</code> CSS class to the <code>div</code> thus allowing you to use CSS rules to highlight the <code>div</code>.<p class="paragraph"/> |
| <h4>Retrieving Input Values</h4><p class="paragraph"/>Each error is actually an instance of the <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/validation/FieldError.html" class="api">FieldError</a> class in Spring, which retains the original input value within it. This is useful as you can use the error object to restore the value input by the user using the <a href="../ref/Tags/fieldValue.html" class="tags">fieldValue</a> tag:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><input type=<span class="xml-quote">"text"</span> name=<span class="xml-quote">"login"</span> value=<span class="xml-quote">"${fieldValue(bean:user,field:'login')}"</span>/></span></pre></div><p class="paragraph"/>This code will look if there is 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.<h2><a name="7.4 Validation and Internationalization">7.4 Validation and Internationalization</a></h2>Another important thing to note about errors in Grails is that the messages that the errors display are not hard coded anywhere. The <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/validation/FieldError.html" class="api">FieldError</a> class in Spring essentially resolves messages from message bundles using Grails' <a href="../guide/single.html#10. Internationalization" class="guide">i18n</a> support.<p class="paragraph"/><h4>Constraints and Message Codes</h4><p class="paragraph"/>The codes themselves are dictated by a convention. For example consider the constraints we looked at earlier:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> com.mycompany.myapp<p class="paragraph"/>class User { |
| ...<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| login(size:5..15, blank:<span class="java-keyword">false</span>, unique:<span class="java-keyword">true</span>) |
| password(size:5..15, blank:<span class="java-keyword">false</span>) |
| email(email:<span class="java-keyword">true</span>, blank:<span class="java-keyword">false</span>) |
| age(min:18, nullable:<span class="java-keyword">false</span>) |
| } |
| }</pre></div><p class="paragraph"/>If the <code>blank</code> constraint was violated Grails will, by convention, look for a message code in the form:<p class="paragraph"/><div class="code"><pre>[<span class="java-object">Class</span> Name].[Property Name].[Constraint Code]</pre></div><p class="paragraph"/>In the case of the <code>blank</code> constraint this would be <code>user.login.blank</code> so you would need a message such as the following in your <code>grails-app/i18n/messages.properties</code> file:<p class="paragraph"/><div class="code"><pre>user.login.blank=Your login name must be specified!</pre></div><p class="paragraph"/>The class name is looked for both with and without a package, with the packaged version taking precedence. So for example, com.mycompany.myapp.User.login.blank will be used before user.login.blank. This allows for cases where you domain class encounters message code clashes with plugins.<p class="paragraph"/>For a reference on what codes are for which constraints refer to the reference guide for each constraint.<p class="paragraph"/><h4>Displaying Messages</h4><p class="paragraph"/>The <a href="../ref/Tags/renderErrors.html" class="tags">renderErrors</a> tag will automatically deal with looking up messages for you using the <a href="../ref/Tags/message.html" class="tags">message</a> tag. However, if you need more control of rendering you will need to do this yourself:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:hasErrors bean=<span class="xml-quote">"${user}"</span>></span> |
| <span class="xml-tag"><ul></span> |
| <span class="xml-tag"><g:eachError var=<span class="xml-quote">"err"</span> bean=<span class="xml-quote">"${user}"</span>></span> |
| <span class="xml-tag"><li></span><span class="xml-tag"><g:message error=<span class="xml-quote">"${err}"</span> /></span><span class="xml-tag"></li></span> |
| <span class="xml-tag"></g:eachError></span> |
| <span class="xml-tag"></ul></span> |
| <span class="xml-tag"></g:hasErrors></span></pre></div><p class="paragraph"/>In this example within the body of the <a href="../ref/Tags/eachError.html" class="tags">eachError</a> tag we use the <a href="../ref/Tags/message.html" class="tags">message</a> tag in combination with its <code>error</code> argument to read the message for the given error.<p class="paragraph"/><h2><a name="7.5 Validation Non Domain and Command Object Classes">7.5 Validation Non Domain and Command Object Classes</a></h2><a href="../guide/single.html#5.2 Domain Modelling in GORM" class="guide">Domain classes</a> and <a href="../guide/single.html#6.1.10 Command Objects" class="guide">command objects</a> support validation by default. Other classes may be made validateable by defining the static constraints 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 constraints property is not sufficient.<p class="paragraph"/><h4>The Validateable Annotation</h4><p class="paragraph"/>Classes which define the static constraints property and are marked with the @Validateable annotation may be made validateable by the framework. Consider this example:<p class="paragraph"/><div class="code"><pre>// src/groovy/com/mycompany/myapp/User.groovy |
| <span class="java-keyword">package</span> com.mycompany.myapp<p class="paragraph"/><span class="java-keyword">import</span> org.codehaus.groovy.grails.validation.Validateable<p class="paragraph"/>@Validateable |
| class User { |
| ...<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| login(size:5..15, blank:<span class="java-keyword">false</span>, unique:<span class="java-keyword">true</span>) |
| password(size:5..15, blank:<span class="java-keyword">false</span>) |
| email(email:<span class="java-keyword">true</span>, blank:<span class="java-keyword">false</span>) |
| age(min:18, nullable:<span class="java-keyword">false</span>) |
| } |
| }</pre></div><p class="paragraph"/>You need to tell the framework which packages to search for @Validateable classes by assigning a list of Strings to the grails.validateable.packages property in Config.groovy.<p class="paragraph"/><div class="code"><pre>// grails-app/conf/Config.groovy<p class="paragraph"/>...<p class="paragraph"/>grails.validateable.packages = ['com.mycompany.dto', 'com.mycompany.util']<p class="paragraph"/>...</pre></div><p class="paragraph"/>The framework will only search those packages (and child packages of those) for classes marked with @Validateable.<p class="paragraph"/><h4>Registering Validateable Classes</h4><p class="paragraph"/>If a class is not marked with @Validateable, it may still be made validateable by the framework. The steps required to do this are to define the static constraints property in the class (as described above) and then telling the framework about the class by assigning a value to the grails.validateable.classes property in Config.groovy.<p class="paragraph"/> |
| <div class="code"><pre>// grails-app/conf/Config.groovy<p class="paragraph"/>...<p class="paragraph"/>grails.validateable.classes = [com.mycompany.myapp.User, com.mycompany.dto.Account]<p class="paragraph"/>...</pre></div><p class="paragraph"/><h1><a name="8. The Service Layer">8. The Service Layer</a></h1>As well as the <a href="../guide/single.html#6. The Web Layer" class="guide">Web layer</a>, 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 re-use and a clean separation of concerns.<p class="paragraph"/>Services in Grails are seen as the place to put the majority of the logic in your application, leaving controllers responsible for handling request flow via redirects and so on.<p class="paragraph"/><h4>Creating a Service</h4><p class="paragraph"/>You can create a Grails service by running the <a href="../ref/Command Line/create-service.html" class="commandLine">create-service</a> command from the root of your project in a terminal window:<p class="paragraph"/><div class="code"><pre>grails create-service simple</pre></div><p class="paragraph"/>The above example will create a service at the location <code>grails-app/services/SimpleService.groovy</code>. A service's name ends with the convention <code>Service</code>, other than that a service is a plain Groovy class:<p class="paragraph"/><div class="code"><pre>class SimpleService { |
| }</pre></div><h2><a name="8.1 Declarative Transactions">8.1 Declarative Transactions</a></h2><h3>Default Declarative Transactions</h3><p class="paragraph"/>Services are typically involved with co-ordinating logic between <a href="../guide/single.html#5. Object Relational Mapping (GORM)" class="guide">domain classes</a>, and hence often involved with persistence that spans large operations. Given the nature of services they frequently require transactional behaviour. You can of course use programmatic transactions with the <a href="../ref/Domain Classes/withTransaction.html" class="domainClasses">withTransaction</a> method, however this is repetitive and doesn't fully leverage the power of Spring's underlying transaction abstraction.<p class="paragraph"/>Services allow the enablement of transaction demarcation, which is essentially a declarative way of saying all methods within this service are to be made transactional. All services have transaction demarcation enabled by default - to disable it, simply set the <code>transactional</code> property to <code>false</code>:<p class="paragraph"/><div class="code"><pre>class CountryService { |
| <span class="java-keyword">static</span> transactional = <span class="java-keyword">false</span> |
| }</pre></div><p class="paragraph"/>You may also set this property to <code>true</code> in case the default changes in the future, or simply to make it clear that the service is intentionally transactional.<p class="paragraph"/><blockquote class="warning"> |
| Warning: <a href="../guide/single.html#8.3 Dependency Injection and Services" class="guide">dependency injection</a> is the <strong class="bold">only</strong> way that declarative transactions work. You will not get a transactional service if you use the <code>new</code> operator such as <code>new BookService()</code> |
| </blockquote><p class="paragraph"/> |
| The result is all methods are wrapped in a transaction and automatic rollback occurs if an exception is thrown in the body of one of the methods. The propagation level of the transaction is by default set to <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/transaction/TransactionDefinition.html#PROPAGATION_REQUIRED" target="blank">PROPAGATION_REQUIRED</a>.<p class="paragraph"/><h3>Custom Transaction Configuration</h3><p class="paragraph"/>Grails also fully supports Spring's <code>Transactional</code> annotation for cases where you need more fine-grained control over transactions at a per-method level or need specify an alternative propagation level:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.springframework.transaction.annotation.*<p class="paragraph"/>class BookService {<p class="paragraph"/> @Transactional(readOnly = <span class="java-keyword">true</span>) |
| def listBooks() { Book.list() }<p class="paragraph"/> @Transactional def updateBook() { |
| // … |
| }<p class="paragraph"/>}</pre></div><p class="paragraph"/>For more information refer to the section of the Spring user guide on <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/transaction.html#transaction-declarative-annotations" target="blank">Using @Transactional</a>.<p class="paragraph"/><blockquote class="note"> |
| Unlike Spring you do not need any prior configuration to use <code>Transactional</code>, just specify the annotation as needed and Grails will pick them up automatically. |
| </blockquote><h2><a name="8.2 Scoped Services">8.2 Scoped Services</a></h2>By default, access to service methods is not synchronised, so nothing prevents concurrent execution of those functions. In fact, because the service is a singleton and may be used concurrently, you should be very careful about storing state in a service. Or take the easy (and better) road and never store state in a service.<p class="paragraph"/>You can change this behaviour by placing a service in a particular scope. The supported scopes are: |
| <ul class="star"> |
| <li><code>prototype</code> - A new service is created every time it is injected into another class</li> |
| <li><code>request</code> - A new service will be created per request</li> |
| <li><code>flash</code> - A new service will be created for the current and next request only</li> |
| <li><code>flow</code> - In web flows the service will exist for the scope of the flow</li> |
| <li><code>conversation</code> - In web flows the service will exist for the scope of the conversation. ie a root flow and its sub flows</li> |
| <li><code>session</code> - A service is created for the scope of a user session</li> |
| <li><code>singleton</code> (default) - Only one instance of the service ever exists</li> |
| </ul><p class="paragraph"/><blockquote class="note"> |
| If your service is <code>flash</code>, <code>flow</code> or <code>conversation</code> scoped it will need to implement <code>java.io.Serializable</code> and can only be used in the context of a <a href="../guide/single.html#6.5 Web Flow" class="guide">Web Flow</a> |
| </blockquote><p class="paragraph"/>To enable one of the scopes, add a static scope property to your class whose value is one of the above:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> scope = <span class="java-quote">"flow"</span></pre></div><p class="paragraph"/><h2><a name="8.3 Dependency Injection and Services">8.3 Dependency Injection and Services</a></h2><h4>Dependency Injection Basics</h4><p class="paragraph"/>A key aspect of Grails services is the ability to take advantage of the <a href="http://www.springframework.org/" target="blank">Spring Framework's</a> dependency injection capability. Grails supports "dependency injection by convention". In other words, you can use the property name representation of the class name of a service, to automatically inject them into controllers, tag libraries, and so on.<p class="paragraph"/>As an example, given a service called <code>BookService</code>, if you place a property called <code>bookService</code> within a controller as follows:<p class="paragraph"/><div class="code"><pre>class BookController { |
| def bookService |
| … |
| }</pre></div><p class="paragraph"/>In this case, the Spring container will automatically inject an instance of that service based on its configured scope. All dependency injection is done by name. You can also specify the type as follows:<p class="paragraph"/><div class="code"><pre>class AuthorService { |
| BookService bookService |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| NOTE: Normally the property name is generated by lower casing the first letter of the type. For example, an instance of the <code>BookService</code> class would map to a property named <code>bookService</code>.<p class="paragraph"/>To be consistent with standard JavaBean convetions, if the first 2 letters of the class name are upper case, the property name is the same as the class name. For example, an instance of the <code>MYhelperService</code> class would map to a property named <code>MYhelperService</code>.<p class="paragraph"/>See section 8.8 of the JavaBean specification for more information on de-capitalization rules. |
| </blockquote><p class="paragraph"/><h4>Dependency Injection and Services</h4><p class="paragraph"/>You can inject services in other services with the same technique. Say you had an <code>AuthorService</code> that needed to use the <code>BookService</code>, declaring the <code>AuthorService</code> as follows would allow that:<p class="paragraph"/><div class="code"><pre>class AuthorService { |
| def bookService |
| }</pre></div><p class="paragraph"/><h4>Dependency Injection and Domain Classes</h4><p class="paragraph"/>You can even inject services into domain classes, which can aid in the development of rich domain models:<p class="paragraph"/><div class="code"><pre>class Book { |
| … |
| def bookService |
| def buyBook() { |
| bookService.buyBook(<span class="java-keyword">this</span>) |
| } |
| }</pre></div> |
| <h2><a name="8.4 Using Services from Java">8.4 Using Services from Java</a></h2>One of the powerful things about services is that since they encapsulate re-usable logic, you can use them from other classes, including Java classes. There are a couple of ways you can re-use a service from Java. The simplest way is to move your service into a package within the <code>grails-app/services</code> directory. The reason this is a critical step is that it is not possible to import classes into Java from the default package (the package used when no package declaration is present). So for example the <code>BookService</code> below cannot be used from Java as it stands:<p class="paragraph"/><div class="code"><pre>class BookService { |
| void buyBook(Book book) { |
| // logic |
| } |
| }</pre></div><p class="paragraph"/>However, this can be rectified by placing this class in a package, by moving the class into a sub directory such as <code>grails-app/services/bookstore</code> and then modifying the package declaration:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> bookstore |
| class BookService { |
| void buyBook(Book book) { |
| // logic |
| } |
| }</pre></div><p class="paragraph"/>An alternative to packages is to instead have an interface within a package that the service implements:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> bookstore; |
| <span class="java-keyword">interface</span> BookStore { |
| void buyBook(Book book); |
| }</pre></div><p class="paragraph"/>And then the service:<p class="paragraph"/><div class="code"><pre>class BookService <span class="java-keyword">implements</span> bookstore.BookStore { |
| void buyBook(Book b) { |
| // logic |
| } |
| }</pre></div><p class="paragraph"/>This latter technique is arguably cleaner, as the Java side only has a reference to the interface and not to the implementation class. Either way, the goal of this exercise to enable Java to statically resolve the class (or interface) to use, at compile time. Now that this is done you can create a Java class within the <code>src/java</code> package, and provide a setter that uses the type and the name of the bean in Spring:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> bookstore; |
| // note: <span class="java-keyword">this</span> is Java class |
| <span class="java-keyword">public</span> class BookConsumer { |
| <span class="java-keyword">private</span> BookStore store;<p class="paragraph"/> <span class="java-keyword">public</span> void setBookStore(BookStore storeInstance) { |
| <span class="java-keyword">this</span>.store = storeInstance; |
| } |
| … |
| }</pre></div><p class="paragraph"/>Once this is done you can configure the Java class as a Spring bean in <code>grails-app/conf/spring/resources.xml</code> (For more information one this see the section on <a href="../guide/single.html#14. Grails and Spring" class="guide">Grails and Spring</a>):<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><bean id=<span class="xml-quote">"bookConsumer"</span> class=<span class="xml-quote">"bookstore.BookConsumer"</span>></span> |
| <span class="xml-tag"><property name=<span class="xml-quote">"bookStore"</span> ref=<span class="xml-quote">"bookService"</span> /></span> |
| <span class="xml-tag"></bean></span></pre></div><p class="paragraph"/><h1><a name="9. Testing">9. Testing</a></h1>Automated testing is seen as a key part of Grails, implemented using <a href="http://groovy.codehaus.org/Testing+Guide" target="blank">Groovy Tests</a>. 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 in terms of testing.<p class="paragraph"/>The first thing to be aware of is that all of the <code>create-*</code> commands actually end up creating <code>unit</code> tests automatically for you. For example say you run the <a href="../ref/Command Line/create-controller.html" class="commandLine">create-controller</a> command as follows:<p class="paragraph"/><div class="code"><pre>grails create-controller com.yourcompany.yourapp.simple</pre></div><p class="paragraph"/>Not only will Grails create a controller at <code>grails-app/controllers/com/yourcompany/yourapp/SimpleController.groovy</code>, but also an unit test at <code>test/unit/com/yourcompany/yourapp/SimpleControllerTests.groovy</code>. What Grails won't do however is populate the logic inside the test! That is left up to you.<p class="paragraph"/><blockquote class="note"> |
| As of Grails 1.2.2,the suffix of <code>Test</code> is also supported for test cases. |
| </blockquote><p class="paragraph"/><h4>Running Tests</h4><p class="paragraph"/>Test are run with the <a href="../ref/Command Line/test-app.html" class="commandLine">test-app</a> command:<p class="paragraph"/><div class="code"><pre>grails test-app</pre></div><p class="paragraph"/>The above command will produce output such as:<p class="paragraph"/><div class="code"><pre>------------------------------------------------------- |
| Running Unit Tests… |
| Running test FooTests...FAILURE |
| Unit Tests Completed in 464ms … |
| -------------------------------------------------------<p class="paragraph"/>Tests failed: 0 errors, 1 failures</pre></div><p class="paragraph"/>Whilst reports will have been written out the <code>target/test-reports</code> directory.<p class="paragraph"/><blockquote class="note"> |
| You can force a clean before running tests by passing <code>-clean</code> to the <code>test-app</code> command. |
| </blockquote><p class="paragraph"/><h5>Targeting Tests</h5><p class="paragraph"/>You can selectively target the test(s) to be run in different ways. To run all tests for a controller named <code>SimpleController</code> you would run:<p class="paragraph"/><div class="code"><pre>grails test-app SimpleController</pre></div><p class="paragraph"/>This will run any tests for the class named <code>SimpleController</code>. Wildcards can be used...<p class="paragraph"/><div class="code"><pre>grails test-app *Controller</pre></div><p class="paragraph"/>This will test all classes ending in <code>Controller</code>. Package names can optionally be specified...<p class="paragraph"/><div class="code"><pre>grails test-app some.org.*Controller</pre></div><p class="paragraph"/>or to run all tests in a package...<p class="paragraph"/><div class="code"><pre>grails test-app some.org.*</pre></div><p class="paragraph"/>or to run all tests in a package including subpackages...<p class="paragraph"/><div class="code"><pre>grails test-app some.org.**</pre></div><p class="paragraph"/>You can also target particular test methods...<p class="paragraph"/><div class="code"><pre>grails test-app SimpleController.testLogin</pre></div><p class="paragraph"/>This will run the <code>testLogin</code> test in the <code>SimpleController</code> tests. You can specify as many patterns in combination as you like...<p class="paragraph"/><div class="code"><pre>grails test-app some.org.* SimpleController.testLogin BookController</pre></div><p class="paragraph"/><h5>Targeting Test Types and/or Phases</h5><p class="paragraph"/>In addition to targeting certain tests, you can also target test <em class="italic">types</em> and/or <em class="italic">phases</em> by using the <code>phase:type</code> syntax.<p class="paragraph"/><blockquote class="note"> |
| Grails organises tests by phase and by type. A test phase relates to the state of the Grails application during the tests, and the type relates to the testing mechanism.<p class="paragraph"/>Grails comes with support for 4 test phases (<code>unit</code>, <code>integration</code>, <code>functional</code> and <code>other</code>) and JUnit test types for the <code>unit</code> and <code>integration</code> phases. These test types have the same name as the phase.<p class="paragraph"/>Testing plugins may provide new test phases or new test types for existing phases. Refer to the plugin documentation. |
| </blockquote><p class="paragraph"/>To execute the JUnit <code>integration</code> tests you can run:<p class="paragraph"/><div class="code"><pre>grails test-app integration:integration</pre></div><p class="paragraph"/>Both <code>phase</code> and <code>type</code> are optional. Their absence acts as a wildcard. The following command will run all test types in the <code>unit</code> phase:<p class="paragraph"/><div class="code"><pre>grails test-app unit:</pre></div><p class="paragraph"/>The Grails <a href="http://grails.org/plugin/spock" target="blank">Spock Plugin</a> is one plugin that adds new test types to Grails. It adds a <code>spock</code> test type to the <code>unit</code>, <code>integration</code> and <code>functional</code> phases. To run all spock tests in all phases you would run the following:<p class="paragraph"/><div class="code"><pre>grails test-app :spock</pre></div><p class="paragraph"/>To run the all of the spock tests in the <code>functional</code> phase you would run...<p class="paragraph"/><div class="code"><pre>grails test-app functional:spock</pre></div><p class="paragraph"/>More than one pattern can be specified...<p class="paragraph"/><div class="code"><pre>grails test-app unit:spock integration:spock</pre></div><p class="paragraph"/><h5>Targeting Tests in Types and/or Phases</h5><p class="paragraph"/>Test and type/phase targetting can be applied at the same time:<p class="paragraph"/><div class="code"><pre>grails test-app integration: unit: some.org.**</pre></div><p class="paragraph"/>This would run all tests in the <code>integration</code> and <code>unit</code> phases that are in the page <code>some.org</code> or a subpackage of.<h2><a name="9.1 Unit Testing">9.1 Unit Testing</a></h2>Unit testing are tests at the "unit" level. In other words you are testing individual methods or blocks of code without considering for surrounding infrastructure. In Grails you need to be particularity aware of the difference between unit and integration tests because in unit tests Grails <strong class="bold">does not</strong> inject any of the dynamic methods present during integration tests and at runtime.<p class="paragraph"/>This makes sense if you consider that the methods injected by Grails typically communicate with the database (with GORM) or the underlying Servlet engine (with Controllers). |
| For example say you have service like the following in <code>BookController</code>:<p class="paragraph"/><div class="code"><pre>class MyService { |
| def otherService<p class="paragraph"/> <span class="java-object">String</span> createSomething() { |
| def stringId = otherService.newIdentifier() |
| def item = <span class="java-keyword">new</span> Item(code: stringId, name: <span class="java-quote">"Bangle"</span>) |
| item.save() |
| <span class="java-keyword">return</span> stringId |
| }<p class="paragraph"/> <span class="java-object">int</span> countItems(<span class="java-object">String</span> name) { |
| def items = Item.findAllByName(name) |
| <span class="java-keyword">return</span> items.size() |
| } |
| }</pre></div><p class="paragraph"/> |
| As you can see the service takes advantage of GORM methods. So how do you go about testing the above code in a unit test? The answer can be found in Grails' testing support classes.<p class="paragraph"/><h3>The Testing Framework</h3><p class="paragraph"/>The core of the testing plugin is the <code>grails.test.GrailsUnitTestCase</code> class. This is a sub-class of <code>GroovyTestCase</code> geared towards Grails applications and their artifacts. It provides several methods for mocking particular types as well as support for general mocking a la Groovy's MockFor and StubFor classes.<p class="paragraph"/>Normally you might look at the <code>MyService</code> example shown previously and the dependency on another service and the use of dynamic domain class methods with a bit of a groan. You can use meta-class programming and the "map as object" idiom, but these can quickly get ugly. How might we write the test with GrailsUnitTestCase ?<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.test.GrailsUnitTestCase<p class="paragraph"/>class MyServiceTests <span class="java-keyword">extends</span> GrailsUnitTestCase { |
| void testCreateSomething() { |
| // Mock the domain class. |
| mockDomain(Item)<p class="paragraph"/> // Mock the <span class="java-quote">"other"</span> service. |
| <span class="java-object">String</span> testId = <span class="java-quote">"NH-12347686"</span> |
| def otherControl = mockFor(OtherService) |
| otherControl.demand.newIdentifier(1..1) {-> <span class="java-keyword">return</span> testId }<p class="paragraph"/> // Initialise the service and test the target method. |
| def testService = <span class="java-keyword">new</span> MyService() |
| testService.otherService = otherControl.createMock()<p class="paragraph"/> def retval = testService.createSomething()<p class="paragraph"/> // Check that the method returns the identifier returned by the |
| // mock <span class="java-quote">"other"</span> service and also that a <span class="java-keyword">new</span> Item instance has |
| // been saved. |
| def testInstances = Item.list() |
| assertEquals testId, retval |
| assertEquals 1, testInstances.size() |
| assertTrue testInstances[0] <span class="java-keyword">instanceof</span> Item |
| }<p class="paragraph"/> void testCountItems() { |
| // Mock the domain class, <span class="java-keyword">this</span> time providing a list of test |
| // Item instances that can be searched. |
| def testInstances = [ <span class="java-keyword">new</span> Item(code: <span class="java-quote">"NH-4273997"</span>, name: <span class="java-quote">"Laptop"</span>), |
| <span class="java-keyword">new</span> Item(code: <span class="java-quote">"EC-4395734"</span>, name: <span class="java-quote">"Lamp"</span>), |
| <span class="java-keyword">new</span> Item(code: <span class="java-quote">"TF-4927324"</span>, name: <span class="java-quote">"Laptop"</span>) ] |
| mockDomain(Item, testInstances)<p class="paragraph"/> // Initialise the service and test the target method. |
| def testService = <span class="java-keyword">new</span> MyService()<p class="paragraph"/> assertEquals 2, testService.countItems(<span class="java-quote">"Laptop"</span>) |
| assertEquals 1, testService.countItems(<span class="java-quote">"Lamp"</span>) |
| assertEquals 0, testService.countItems(<span class="java-quote">"Chair"</span>) |
| } |
| }</pre></div><p class="paragraph"/>OK, so a fair bit of new stuff there, but once we break it down you should quickly see how easy it is to use the methods available to you. Take a look at the "testCreateSomething()" test method. The first thing you will probably notice is the <code>mockDomain()</code> method, which is one of several provided by <code>GrailsUnitTestCase</code>:<p class="paragraph"/><div class="code"><pre>def testInstances = [] |
| mockDomain(Item, testInstances)</pre></div><p class="paragraph"/>It adds all the common domain methods (both instance and static) to the given class so that any code using it sees it as a full-blown domain class. So for example, once the <code>Item</code> class has been mocked, we can safely call the <code>save()</code> method on instances of it. Invoking the <code>save()</code> method doesn't really save the instance to any database but it will cache the object in the testing framework so the instance will be visible to certain queries. The following code snippet demonstrates the effect of calling the <code>save()</code> method.<p class="paragraph"/><div class="code"><pre>void testSomething() { |
| def testInstances=[] |
| mockDomain(Song, testInstances) |
| assertEquals(0, Song.count()) |
| <span class="java-keyword">new</span> Song(name:<span class="java-quote">"Supper's Ready"</span>).save() |
| assertEquals(1, Song.count()) |
| }</pre></div><p class="paragraph"/>The next bit we want to look at is centered on the <code>mockFor</code> method:<p class="paragraph"/><div class="code"><pre>def otherControl = mockFor(OtherService) |
| otherControl.demand.newIdentifier(1..1) {-> <span class="java-keyword">return</span> testId }</pre></div><p class="paragraph"/>This is analagous to the <code>MockFor</code> and <code>StubFor</code> classes that come with Groovy and it can be used to mock any class you want. In fact, the "demand" syntax is identical to that used by Mock/StubFor, so you should feel right at home. Of course you often need to inject a mock instance as a dependency, but that is pretty straight forward with the <code>createMock()</code> method, which you simply call on the mock control as shown. For those familiar with EasyMock, the name <code>otherControl</code> highlights the role of the object returned by <code>mockFor()</code> - it is a control object rather than the mock itself.<p class="paragraph"/>The rest of the <code>testCreateSomething()</code> method should be pretty familiar, particularly as you now know that the mock <code>save()</code> method adds instances to <code>testInstances</code> list. However, there is an important technique missing from the test method. We can determine that the mock <code>newIdentifier()</code> method is called because its return value has a direct impact on the result of the <code>createSomething()</code> method. But what if that weren't the case? How would we know whether it had been called or not? With Mock/StubFor the check would be performed at the end of the <code>use()</code> closure, but that's not available here. Instead, you can call <code>verify()</code> on the control object - in this case <code>otherControl</code>. This will perform the check and throw an assertion error if it hasn't been called when it should have been.<p class="paragraph"/>Lastly, <code>testCountItems()</code> in the example demonstrates another facet of the <code>mockDomain()</code> method:<p class="paragraph"/><div class="code"><pre>def testInstances = [ <span class="java-keyword">new</span> Item(code: <span class="java-quote">"NH-4273997"</span>, name: <span class="java-quote">"Laptop"</span>), |
| <span class="java-keyword">new</span> Item(code: <span class="java-quote">"EC-4395734"</span>, name: <span class="java-quote">"Lamp"</span>), |
| <span class="java-keyword">new</span> Item(code: <span class="java-quote">"TF-4927324"</span>, name: <span class="java-quote">"Laptop"</span>) ] |
| mockDomain(Item, testInstances)</pre></div><p class="paragraph"/>It is normally quite fiddly to mock the dynamic finders manually, and you often have to set up different data sets for each invocation. On top of that, if you decide a different finder should be used then you have to update the tests to check for the new method! Thankfully the <code>mockDomain()</code> method provides a lightweight implementation of the dynamic finders backed by a list of domain instances. Simply provide the test data as the second argument of the method and the mock finders will just work.<p class="paragraph"/><h3>GrailsUnitTestCase - the mock methods</h3><p class="paragraph"/>You have already seen a couple of examples in the introduction of the <code>mock..()</code> methods provided by the <code>GrailsUnitTestCase</code> class. Here we will look at all the available methods in some detail, starting with the all-purpose <code>mockFor()</code>. But before we do, there is a very important point to make: using these methods ensures that any changes you make to the given classes do not leak into other tests! This is a common and serious problem when you try to perform the mocking yourself via meta-class programming, but that headache just disappears as long as you use at least one of <code>mock..()</code> methods on each class you want to mock.<p class="paragraph"/><div class="code"><pre>mockFor(class, loose = <span class="java-keyword">false</span>)</pre></div><p class="paragraph"/>General purpose mocking that allows you to set up either strict or loose demands on a class.<p class="paragraph"/>This method is surprisingly intuitive to use. By default it will create a strict mock control object (one for which the order in which methods are called is important) that you can use to specify demands:<p class="paragraph"/><div class="code"><pre>def strictControl = mockFor(MyService) |
| strictControl.demand.someMethod(0..2) { <span class="java-object">String</span> arg1, <span class="java-object">int</span> arg2 -> … } |
| strictControl.demand.<span class="java-keyword">static</span>.aStaticMethod {-> … }</pre></div><p class="paragraph"/>Notice that you can mock static methods as well as instance ones simply by using the "static" property after "demand". You then specify the name of the method that you want to mock with an optional range as its argument. This range determines how many times you expect the method to be called, so if the number of invocations falls outside of that range (either too few or too many) then an assertion error will be thrown. If no range is specified, a default of "1..1" is assumed, i.e. that the method must be called exactly once.<p class="paragraph"/>The last part of a demand is a closure representing the implementation of the mock method. The closure arguments should match the number and types of the mocked method, but otherwise you are free to add whatever you want in the body.<p class="paragraph"/>As we mentioned before, if you want an actual mock instance of the class that you are mocking, then you need to call <code>mockControl.createMock()</code>. In fact, you can call this as many times as you like to create as many mock instances as you need. And once you have executed the test method, you can call <code>mockControl.verify()</code> to check whether the expected methods were actually called or not.<p class="paragraph"/>Lastly, the call:<p class="paragraph"/><div class="code"><pre>def looseControl = mockFor(MyService, <span class="java-keyword">true</span>)</pre></div><p class="paragraph"/>will create a mock control object that has only loose expectations, i.e. the order that methods are invoked does not matter.<p class="paragraph"/><h4>mockDomain(class, testInstances = )</h4><p class="paragraph"/>Takes a class and makes mock implementations of all the domain class methods (both instance- and static-level) accessible on it.<p class="paragraph"/>Mocking domain classes is one of the big wins from using the testing plugin. Manually doing it is fiddly at best, so it's great that mockDomain() takes that burden off your shoulders.<p class="paragraph"/>In effect, <code>mockDomain()</code> provides a lightweight version of domain classes in which the "database" is simply a list of domain instances held in memory. All the mocked methods ( <code>save()</code> , <code>get()</code> , <code>findBy*()</code> , etc.) work against that list, generally behaving as you would expect them to. In addition to that, both the mocked <code>save()</code> and validate() methods will perform real validation (support for the unique constraint included!) and populate an errors object on the corresponding domain instance.<p class="paragraph"/>There isn't much else to say other than that the plugin does not support the mocking of criteria or HQL queries. If you use either of those, simply mock the corresponding methods manually (for example with <code>mockFor()</code> ) or use an integration test with real data.<p class="paragraph"/><h4>mockForConstraintsTests(class, testInstances = )</h4><p class="paragraph"/>Highly specialised mocking for domain classes and command objects that allows you to check whether the constraints are behaving as you expect them to.<p class="paragraph"/>Do you test your domain constraints? If not, why not? If your answer is that they don't need testing, think again. Your constraints contain logic and that logic is highly susceptible to bugs - the kind of bugs that can be tricky to track down (particularly as save() doesn't throw an exception when it fails). If your answer is that it's too hard or fiddly, that is no longer an excuse. Enter the <code>mockForConstraintsTests()</code> method.<p class="paragraph"/>This is like a much reduced version of the <code>mockDomain()</code> method that simply adds a <code>validate()</code> method to a given domain class. All you have to do is mock the class, create an instance with field values, and then call <code>validate()</code>. You can then access the errors property on your domain instance to find out whether the validation failed or not. So if all we are doing is mocking the <code>validate()</code> method, why the optional list of test instances? That is so that we can test unique constraints as you will soon see.<p class="paragraph"/>So, suppose we have a simple domain class like so:<p class="paragraph"/><div class="code"><pre>class Book { |
| <span class="java-object">String</span> title |
| <span class="java-object">String</span> author<p class="paragraph"/> <span class="java-keyword">static</span> constraints = { |
| title(blank: <span class="java-keyword">false</span>, unique: <span class="java-keyword">true</span>) |
| author(blank: <span class="java-keyword">false</span>, minSize: 5) |
| } |
| }</pre></div><p class="paragraph"/>Don't worry about whether the constraints are sensible or not (they're not!), they are for demonstration only. To test these constraints we can do the following:<p class="paragraph"/><div class="code"><pre>class BookTests <span class="java-keyword">extends</span> GrailsUnitTestCase { |
| void testConstraints() { |
| def existingBook = <span class="java-keyword">new</span> Book(title: <span class="java-quote">"Misery"</span>, author: <span class="java-quote">"Stephen King"</span>) |
| mockForConstraintsTests(Book, [ existingBook ])<p class="paragraph"/> // Validation should fail <span class="java-keyword">if</span> both properties are <span class="java-keyword">null</span>. |
| def book = <span class="java-keyword">new</span> Book() |
| assertFalse book.validate() |
| assertEquals <span class="java-quote">"nullable"</span>, book.errors[<span class="java-quote">"title"</span>] |
| assertEquals <span class="java-quote">"nullable"</span>, book.errors[<span class="java-quote">"author"</span>]<p class="paragraph"/> // So let's demonstrate the unique and minSize constraints. |
| book = <span class="java-keyword">new</span> Book(title: <span class="java-quote">"Misery"</span>, author: <span class="java-quote">"JK"</span>) |
| assertFalse book.validate() |
| assertEquals <span class="java-quote">"unique"</span>, book.errors[<span class="java-quote">"title"</span>] |
| assertEquals <span class="java-quote">"minSize"</span>, book.errors[<span class="java-quote">"author"</span>]<p class="paragraph"/> // Validation should pass! |
| book = <span class="java-keyword">new</span> Book(title: <span class="java-quote">"The Shining"</span>, author: <span class="java-quote">"Stephen King"</span>) |
| assertTrue book.validate() |
| } |
| }</pre></div><p class="paragraph"/>You can probably look at that code and work out what's happening without any further explanation. The one thing we will explain is the way the errors property is used. First, it does return a real Spring <code>Errors</code> instance, so you can access all the properties and methods you would normally expect. Second, this particular <code>Errors</code> object also has map/property access as shown. Simply specify the name of the field you are interested in and the map/property access will return the name of the constraint that was violated. Note that it is the constraint name , not the message code (as you might expect).<p class="paragraph"/>That's it for testing constraints. One final thing we would like to say is that testing the constraints in this way catches a common error: typos in the "constraints" property! It is currently one of the hardest bugs to track down normally, and yet a unit test for your constraints will highlight the problem straight away.<p class="paragraph"/><h4>mockLogging(class, enableDebug = false)</h4><p class="paragraph"/>Adds a mock "log" property to a class. Any messages passed to the mock logger are echoed to the console.<p class="paragraph"/><h4>mockController(class)</h4><p class="paragraph"/>Adds mock versions of the dynamic controller properties and methods to the given class. This is typically used in conjunction with the <code>ControllerUnitTestCase</code> class.<p class="paragraph"/><h4>mockTagLib(class)</h4><p class="paragraph"/>Adds mock versions of the dynamic taglib properties and methods to the given class. This is typically used in conjunction with the <code>TagLibUnitTestCase</code> class. |
| <h2><a name="9.2 Integration Testing">9.2 Integration Testing</a></h2>Integration tests differ from unit tests in that you have full access to the Grails environment within the test. Grails will use an in-memory HSQLDB database for integration tests and clear out all the data from the database in between each test.<p class="paragraph"/><h4>Testing Controllers</h4><p class="paragraph"/>To test controllers you first have to understand the Spring Mock Library.<p class="paragraph"/>Essentially Grails automatically configures each test with a <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/mock/web/MockHttpServletRequest.html" class="api">MockHttpServletRequest</a>, <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/mock/web/MockHttpServletResponse.html" class="api">MockHttpServletResponse</a>, and <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/mock/web/MockHttpSession.html" class="api">MockHttpSession</a> which you can then use to perform your tests. For example consider the following controller:<p class="paragraph"/><div class="code"><pre>class FooController {<p class="paragraph"/> def text = { |
| render <span class="java-quote">"bar"</span> |
| }<p class="paragraph"/> def someRedirect = { |
| redirect(action:<span class="java-quote">"bar"</span>) |
| } |
| }</pre></div><p class="paragraph"/>The tests for this would be:<p class="paragraph"/><div class="code"><pre>class FooControllerTests <span class="java-keyword">extends</span> GroovyTestCase {<p class="paragraph"/> void testText() { |
| def fc = <span class="java-keyword">new</span> FooController() |
| fc.text() |
| assertEquals <span class="java-quote">"bar"</span>, fc.response.contentAsString |
| }<p class="paragraph"/> void testSomeRedirect() {<p class="paragraph"/> def fc = <span class="java-keyword">new</span> FooController() |
| fc.someRedirect() |
| assertEquals <span class="java-quote">"/foo/bar"</span>, fc.response.redirectedUrl |
| } |
| }</pre></div><p class="paragraph"/>In the above case the response is an instance of <code>MockHttpServletResponse</code> which we can use to obtain the <code>contentAsString</code> (when writing to the response) or the URL redirected to for example. These mocked versions of the Servlet API are, unlike the real versions, all completely mutable and hence you can set properties on the request such as the <code>contextPath</code> and so on.<p class="paragraph"/>Grails <strong class="bold">does not</strong> invoke <a href="../guide/single.html#6.1.5 Controller Interceptors" class="guide">interceptors</a> or servlet filters automatically when calling actions during integration testing. You should test interceptors and filters in isolation, and via <a href="../guide/single.html#9.3 Functional Testing" class="guide">functional testing</a> if necessary.<p class="paragraph"/><h4>Testing Controllers with Services</h4><p class="paragraph"/>If your controller references a service (or other Spring beans), you have to explicitly initialise the service from your test.<p class="paragraph"/>Given a controller using a service:<p class="paragraph"/><div class="code"><pre>class FilmStarsController { |
| def popularityService<p class="paragraph"/> def update = { |
| // <span class="java-keyword">do</span> something with popularityService |
| } |
| }</pre></div><p class="paragraph"/>The test for this would be:<p class="paragraph"/><div class="code"><pre>class FilmStarsTests <span class="java-keyword">extends</span> GroovyTestCase { |
| def popularityService<p class="paragraph"/> void testInjectedServiceInController () { |
| def fsc = <span class="java-keyword">new</span> FilmStarsController() |
| fsc.popularityService = popularityService |
| fsc.update() |
| } |
| }</pre></div><p class="paragraph"/><h4>Testing Controller Command Objects</h4><p class="paragraph"/>With command objects you just supply parameters to the request and it will automatically do the command object work for you when you call your action with no parameters:<p class="paragraph"/>Given a controller using a command object:<p class="paragraph"/><div class="code"><pre>class AuthenticationController { |
| def signup = { SignupForm form -> |
| … |
| } |
| }</pre></div><p class="paragraph"/>You can then test it like this:<p class="paragraph"/><div class="code"><pre>def controller = <span class="java-keyword">new</span> AuthenticationController() |
| controller.params.login = <span class="java-quote">"marcpalmer"</span> |
| controller.params.password = <span class="java-quote">"secret"</span> |
| controller.params.passwordConfirm = <span class="java-quote">"secret"</span> |
| controller.signup()</pre></div><p class="paragraph"/>Grails auto-magically sees your call to <code>signup()</code> as a call to the action and populates the command object from the mocked request parameters. During controller testing, the <code>params</code> are mutable with a mocked request supplied by Grails.<p class="paragraph"/><h4>Testing Controllers and the render Method</h4><p class="paragraph"/>The <a href="../ref/Controllers/render.html" class="controllers">render</a> method allows you to render a custom view at any point within the body of an action. For instance, consider the example below:<p class="paragraph"/><div class="code"><pre>def save = { |
| def book = Book(params) |
| <span class="java-keyword">if</span>(book.save()) { |
| // handle |
| } |
| <span class="java-keyword">else</span> { |
| render(view:<span class="java-quote">"create"</span>, model:[book:book]) |
| } |
| }</pre></div><p class="paragraph"/>In the above example the result of the model of the action is not available as the return value, but instead is stored within the <code>modelAndView</code> property of the controller. The <code>modelAndView</code> property is an instance of Spring MVC's <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/ModelAndView.html" target="blank">ModelAndView</a> class and you can use it to the test the result of an action:<p class="paragraph"/><div class="code"><pre>def bookController = <span class="java-keyword">new</span> BookController() |
| bookController.save() |
| def model = bookController.modelAndView.model.book</pre></div><p class="paragraph"/><h4>Simulating Request Data</h4><p class="paragraph"/>If you're testing an action that requires request data such as a REST web service you can use the Spring <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/mock/web/MockHttpServletRequest.html" class="api">MockHttpServletRequest</a> object to do so. For example consider this action which performs data binding from an incoming request:<p class="paragraph"/><div class="code"><pre>def create = { |
| [book: <span class="java-keyword">new</span> Book(params['book']) ] |
| }</pre></div><p class="paragraph"/>If you wish the simulate the 'book' parameter as an XML request you could do something like the following:<p class="paragraph"/><div class="code"><pre>void testCreateWithXML() { |
| def controller = <span class="java-keyword">new</span> BookController() |
| controller.request.contentType = 'text/xml' |
| controller.request.content = '''<?xml version=<span class="java-quote">"1.0"</span> encoding=<span class="java-quote">"ISO-8859-1"</span>?> |
| <book> |
| <title>The Stand</title> |
| … |
| </book> |
| '''.getBytes() // note we need the bytes<p class="paragraph"/> def model = controller.create() |
| assert model.book |
| assertEquals <span class="java-quote">"The Stand"</span>, model.book.title |
| }</pre></div><p class="paragraph"/>The same can be achieved with a JSON request:<p class="paragraph"/><div class="code"><pre>void testCreateWithJSON() { |
| def controller = <span class="java-keyword">new</span> BookController() |
| controller.request.contentType = <span class="java-quote">"text/json"</span> |
| controller.request.content = '{<span class="java-quote">"id"</span>:1,<span class="java-quote">"class"</span>:<span class="java-quote">"Book"</span>,<span class="java-quote">"title"</span>:<span class="java-quote">"The Stand"</span>}'.getBytes()<p class="paragraph"/> def model = controller.create() |
| assert model.book |
| assertEquals <span class="java-quote">"The Stand"</span>, model.book.title |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| With JSON don't forget the <code>class</code> property to specify the name the target type to bind too. In the XML this is implicit within the name of the <code><book></code> node, but with JSON you need this property as part of the JSON packet. |
| </blockquote><p class="paragraph"/>For more information on the subject of REST web services see the section on <a href="../guide/single.html#13.1 REST" class="guide">REST</a>.<p class="paragraph"/><h4>Testing Web Flows</h4><p class="paragraph"/>Testing <a href="../guide/single.html#6.5 Web Flow" class="guide">Web Flows</a> requires a special test harness called <code>grails.test.WebFlowTestCase</code> which sub classes Spring Web Flow's <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/webflow/test/execution/AbstractFlowExecutionTests.html" class="api">AbstractFlowExecutionTests</a> class.<p class="paragraph"/><blockquote class="note"> |
| Subclasses of <code>WebFlowTestCase</code> <strong class="bold">must</strong> be integration tests |
| </blockquote><p class="paragraph"/>For example given this trivial flow:<p class="paragraph"/><div class="code"><pre>class ExampleController { |
| def exampleFlow = { |
| start { |
| on(<span class="java-quote">"go"</span>) { |
| flow.hello = <span class="java-quote">"world"</span> |
| }.to <span class="java-quote">"next"</span> |
| } |
| next { |
| on(<span class="java-quote">"back"</span>).to <span class="java-quote">"start"</span> |
| on(<span class="java-quote">"go"</span>).to <span class="java-quote">"end"</span> |
| } |
| end() |
| } |
| }</pre></div><p class="paragraph"/>You need to tell the test harness what to use for the "flow definition". This is done via overriding the abstract <code>getFlow</code> |
| method:<p class="paragraph"/><div class="code"><pre>class ExampleFlowTests <span class="java-keyword">extends</span> grails.test.WebFlowTestCase { |
| def getFlow() { <span class="java-keyword">new</span> ExampleController().exampleFlow } |
| … |
| }</pre></div><p class="paragraph"/>If you need to specify the flow id you can do so by overriding the getFlowId method otherwise the default is <code>test</code>: |
| <div class="code"><pre>class ExampleFlowTests <span class="java-keyword">extends</span> grails.test.WebFlowTestCase { |
| <span class="java-object">String</span> getFlowId() { <span class="java-quote">"example"</span> } |
| … |
| }</pre></div><p class="paragraph"/>Once this is done in your test you need to kick off the flow with the <code>startFlow</code> method which returns a <code>ViewSelection</code> object:<p class="paragraph"/><div class="code"><pre>void testExampleFlow() { |
| def viewSelection = startFlow()<p class="paragraph"/> assertEquals <span class="java-quote">"start"</span>, viewSelection.viewName |
| … |
| }</pre></div><p class="paragraph"/>As demonstrated above you can check you're on the right state using the <code>viewName</code> property of the <code>ViewSelection</code> object. To trigger and event you need to use the <code>signalEvent</code> method:<p class="paragraph"/><div class="code"><pre>void testExampleFlow() { |
| … |
| viewSelection = signalEvent(<span class="java-quote">"go"</span>) |
| assertEquals <span class="java-quote">"next"</span>, viewSelection.viewName |
| assertEquals <span class="java-quote">"world"</span>, viewSelection.model.hello |
| }</pre></div><p class="paragraph"/>Here we have signaled to the flow to execute the event "go" this causes a transition to the "next" state. In the example a transition action placed a <code>hello</code> variable into the flow scope. We can test the value of this variable by inspecting the <code>model</code> property of the <code>ViewSelection</code> as above.<p class="paragraph"/> |
| <h4>Testing Tag Libraries</h4><p class="paragraph"/>Testing tag libraries is actually pretty trivial because when a tag is invoked as a method it returns its result as a string. So for example if you have a tag library like this:<p class="paragraph"/><div class="code"><pre>class FooTagLib { |
| def bar = { attrs, body -> |
| out << <span class="java-quote">"<p>Hello World!</p>"</span> |
| }<p class="paragraph"/> def bodyTag = { attrs, body -> |
| out << <span class="java-quote">"<${attrs.name}>"</span> |
| out << body() |
| out << <span class="java-quote">"</${attrs.name}>"</span> |
| } |
| }</pre></div><p class="paragraph"/>The tests would look like:<p class="paragraph"/><div class="code"><pre>class FooTagLibTests <span class="java-keyword">extends</span> GroovyTestCase {<p class="paragraph"/> void testBarTag() { |
| assertEquals <span class="java-quote">"<p>Hello World!</p>"</span>, <span class="java-keyword">new</span> FooTagLib().bar(<span class="java-keyword">null</span>,<span class="java-keyword">null</span>).toString() |
| }<p class="paragraph"/> void testBodyTag() { |
| assertEquals <span class="java-quote">"<p>Hello World!</p>"</span>, <span class="java-keyword">new</span> FooTagLib().bodyTag(name:<span class="java-quote">"p"</span>) { |
| <span class="java-quote">"Hello World!"</span> |
| }.toString() |
| } |
| }</pre></div><p class="paragraph"/>Notice that for the second example, <code>testBodyTag</code>, we pass a block that returns the body of the tag. This is handy for representing the body as a String.<p class="paragraph"/><h4>Testing Tag Libraries with GroovyPagesTestCase</h4><p class="paragraph"/>In addition to doing simply testing of tag libraries like the above you can also use the <code>grails.test.GroovyPagesTestCase</code> class to test tag libraries.<p class="paragraph"/>The <code>GroovyPagesTestCase</code> class is a sub class of the regular <code>GroovyTestCase</code> class and provides utility methods for testing the output of a GSP rendering.<p class="paragraph"/><blockquote class="note"> |
| <code>GroovyPagesTestCase</code> can only be used in an integration test. |
| </blockquote><p class="paragraph"/>As an example given a date formatting tag library such as the one below:<p class="paragraph"/><div class="code"><pre>class FormatTagLib { |
| def dateFormat = { attrs, body -> |
| out << <span class="java-keyword">new</span> java.text.SimpleDateFormat(attrs.format) << attrs.date |
| } |
| }</pre></div><p class="paragraph"/>This can be easily tested as follows:<p class="paragraph"/><div class="code"><pre>class FormatTagLibTests <span class="java-keyword">extends</span> GroovyPagesTestCase { |
| void testDateFormat() { |
| def template = '<g:dateFormat format=<span class="java-quote">"dd-MM-yyyy"</span> date=<span class="java-quote">"${myDate}"</span> />'<p class="paragraph"/> def testDate = … // create the date |
| assertOutputEquals( '01-01-2008', template, [myDate:testDate] ) |
| } |
| }</pre></div><p class="paragraph"/>You can also obtain the result of a GSP using the <code>applyTemplate</code> method of the <code>GroovyPagesTestCase</code> class:<p class="paragraph"/><div class="code"><pre>class FormatTagLibTests <span class="java-keyword">extends</span> GroovyPagesTestCase { |
| void testDateFormat() { |
| def template = '<g:dateFormat format=<span class="java-quote">"dd-MM-yyyy"</span> date=<span class="java-quote">"${myDate}"</span> />'<p class="paragraph"/> def testDate = … // create the date |
| def result = applyTemplate( template, [myDate:testDate] )<p class="paragraph"/> assertEquals '01-01-2008', result |
| } |
| }</pre></div><p class="paragraph"/><h4>Testing Domain Classes</h4><p class="paragraph"/>Testing domain classes is typically a simple matter of using the <a href="../guide/single.html#5. Object Relational Mapping (GORM)" class="guide">GORM API</a>, however there are some things to be aware of. Firstly, if you are testing queries you will often need to "flush" in order to ensure the correct state has been persisted to the database. For example take the following example:<p class="paragraph"/><div class="code"><pre>void testQuery() { |
| def books = [ <span class="java-keyword">new</span> Book(title:<span class="java-quote">"The Stand"</span>), <span class="java-keyword">new</span> Book(title:<span class="java-quote">"The Shining"</span>)] |
| books*.save()<p class="paragraph"/> assertEquals 2, Book.list().size() |
| }</pre></div><p class="paragraph"/>This test will actually fail, because calling <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> does not actually persist the <code>Book</code> instances when called. Calling <code>save</code> merely indicates to Hibernate that at some point in the future these instances should be persisted. If you wish to commit changes immediately you need to "flush" them:<p class="paragraph"/><div class="code"><pre>void testQuery() { |
| def books = [ <span class="java-keyword">new</span> Book(title:<span class="java-quote">"The Stand"</span>), <span class="java-keyword">new</span> Book(title:<span class="java-quote">"The Shining"</span>)] |
| books*.save(flush:<span class="java-keyword">true</span>)<p class="paragraph"/> assertEquals 2, Book.list().size() |
| }</pre></div><p class="paragraph"/>In this case since we're passing the argument <code>flush</code> with a value of <code>true</code> the updates will be persisted immediately and hence will be available to the query later on. |
| <h2><a name="9.3 Functional Testing">9.3 Functional Testing</a></h2>Functional tests involve making HTTP requests against the running application and verifying the resultant behaviour. Grails does not ship with any support for writing functional tests directly, but there are several plugins available for this. |
| <ul class="star"> |
| <li><code>Canoo Webtest</code> - <a href="http://grails.org/plugin/webtest" target="blank">http://grails.org/plugin/webtest</a></li> |
| <li><code>G-Func</code> - <a href="http://grails.org/plugin/functional-test" target="blank">http://grails.org/plugin/functional-test</a></li> |
| <li><code>Selenium-RC</code> - <a href="http://grails.org/plugin/selenium-rc" target="blank">http://grails.org/plugin/selenium-rc</a></li> |
| <li><code>WebDriver</code> - <a href="http://grails.org/plugin/webdriver" target="blank">http://grails.org/plugin/webdriver</a></li> |
| <li><code>Geb</code> - <a href="http://grails.org/plugin/geb" target="blank">http://grails.org/plugin/geb</a></li> |
| </ul><p class="paragraph"/>Consult the documentation for each plugin for it's capabilities.<p class="paragraph"/><h4>Common Options</h4><p class="paragraph"/>There are options that are common to all plugins that control how the Grails application is launched, if at all.<p class="paragraph"/><h5>inline</h5><p class="paragraph"/>The <code>-inline</code> option specifies that the grails application should be started inline (i.e. like <code>run-app</code>).<p class="paragraph"/><strong class="bold">This option is implicitly set unless the <code>baseUrl</code> or <code>war</code> options are set</strong><p class="paragraph"/><h5>war</h5><p class="paragraph"/>The <code>-war</code> option specifies that the grails application should be packaged as a war and started. This is useful as it tests your application in a production like state, but it has a longer startup time than the <code>-inline</code> option. It also runs the war in a forked JVM, meaning that you cannot access any internal application objects.<p class="paragraph"/><div class="code"><pre>grails test-app functional: -war</pre></div><p class="paragraph"/>Note that the same build/config options for the <a href="../ref/Command Line/run-war.html" class="commandLine">run-war</a> command apply to functional testing against the WAR.<p class="paragraph"/><h5>https</h5><p class="paragraph"/>The <code>-https</code> option results in the application being able to receive https requests as well as http requests. It is compatible with both the <code>-inline</code> and <code>-war</code> options.<p class="paragraph"/><div class="code"><pre>grails test-app functional: -https</pre></div><p class="paragraph"/>Note that this does not change the test <em class="italic">base url</em> to be https, it will still be http unless the <code>-httpsBaseUrl</code> option is also given.<p class="paragraph"/><h5>httpsBaseUrl</h5><p class="paragraph"/>The <code>-httpsBaseUrl</code> causes the implicit base url to be used for tests to be a https url.<p class="paragraph"/><div class="code"><pre>grails test-app functional: -httpsBaseUrl</pre></div><p class="paragraph"/>This option is ignored if the <code>-baseUrl</code> option is given.<p class="paragraph"/><h5>baseUrl</h5><p class="paragraph"/>The <code>baseUrl</code> option allows the base url for tests to be specified.<p class="paragraph"/><div class="code"><pre>grails test-app functional: -baseUrl=http://mycompany.com/grailsapp</pre></div><p class="paragraph"/>This option will prevent the local grails application being started unless <code>-inline</code> or <code>-war</code> are given as well. If you want to use a custom base url, but still want to test against the local Grails application you <strong class="bold">must</strong> specify one of either the <code>-inline</code> or <code>-war</code> options.<h1><a name="10. Internationalization">10. Internationalization</a></h1>Grails supports Internationalization (i18n) out of the box through the underlying Spring MVC support for internationalization. With Grails you are able to customize the text that appears in any view based on the users Locale. To quote the javadoc for the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Locale.html" class="api">Locale</a> class in Java:<p class="paragraph"/><blockquote class="quote"> |
| A Locale object represents a specific geographical, political, or cultural region. An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user. For example, displaying a number is a locale-sensitive operation--the number should be formatted according to the customs/conventions of the user's native country, region, or culture. |
| </blockquote><p class="paragraph"/>A Locale is made up of a <a href="http://www.loc.gov/standards/iso639-2/englangn.html" target="blank">language code</a> and a <a href="http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html" target="blank">country code</a>. For example "en_US" is the code for US english, whilst "en_GB" is the for British English.<h2><a name="10.1 Understanding Message Bundles">10.1 Understanding Message Bundles</a></h2>Now that you have an idea of locales, to take advantage of them in Grails you have to create message bundles that contain the different languages that you wish to render. Message bundles in Grails are located inside the <code>grails-app/i18n</code> directory and are simple Java properties files.<p class="paragraph"/>Each bundle starts with the name <code>messages</code> by convention and ends with the locale. Grails ships with a bunch of built in message bundles for a whole range of languages within the <code>grails-app/i18n</code> directory. For example:<p class="paragraph"/><div class="code"><pre>messages.properties |
| messages_de.properties |
| messages_es.properties |
| etc.</pre></div><p class="paragraph"/>By default Grails will look in <code>messages.properties</code> for messages, unless the user has specified a custom locale. You can create your own message bundle by simply creating a new properties file that ends with the locale you are interested. For example <code>messages_en_GB.properties</code> for British English.<h2><a name="10.2 Changing Locales">10.2 Changing Locales</a></h2>By default the user locale is detected from the incoming <code>Accept-Language</code> header. However, you can provide users the capability to switch locales by simply passing a parameter called <code>lang</code> to Grails as a request parameter:<p class="paragraph"/><div class="code"><pre>/book/list?lang=es</pre></div><p class="paragraph"/>Grails will automatically switch the user locale and store it in a cookie so subsequent requests will have the new header.<h2><a name="10.3 Reading Messages">10.3 Reading Messages</a></h2><h4>Reading Messages in the View</h4><p class="paragraph"/>The most common place that you need messages is inside the view. To read messages from the view just use the <a href="../ref/Tags/message.html" class="tags">message</a> tag:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:message code=<span class="xml-quote">"my.localized.content"</span> /></span></pre></div><p class="paragraph"/>As long as you have a key in your <code>messages.properties</code> (with appropriate locale suffix) such as the one below then Grails will look-up the message:<p class="paragraph"/><div class="code"><pre>my.localized.content=Hola, Me llamo John. Hoy es domingo.</pre></div><p class="paragraph"/>Note that sometimes you may need to pass arguments to the message. This is also possible with the <code>message</code> tag:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:message code=<span class="xml-quote">"my.localized.content"</span> args=<span class="xml-quote">"${ ['Juan', 'lunes'] }"</span> /></span></pre></div><p class="paragraph"/>And then use positional parameters in the message:<p class="paragraph"/><div class="code"><pre>my.localized.content=Hola, Me llamo {0}. Hoy es {1}.</pre></div><p class="paragraph"/><h4>Reading Messages in Controllers and Tag Libraries</h4><p class="paragraph"/>Since you can invoke tags as methods from controllers it is also trivial to read messages within in a controller:<p class="paragraph"/><div class="code"><pre>def show = { |
| def msg = message(code:<span class="java-quote">"my.localized.content"</span>, args:['Juan', 'lunes']) |
| }</pre></div><p class="paragraph"/>The same technique can be used on <a href="../guide/single.html#6.3 Tag Libraries" class="guide">tag libraries</a>, but note if your tag library has a different <a href="../guide/single.html#6.3.5 Tag Namespaces" class="guide">namespace</a> then you will need to <code>g.</code> prefix:<p class="paragraph"/><div class="code"><pre>def myTag = { attrs, body -> |
| def msg = g.message(code:<span class="java-quote">"my.localized.content"</span>, args:['Juan', 'lunes']) |
| }</pre></div><h2><a name="10.4 Scaffolding and i18n">10.4 Scaffolding and i18n</a></h2>Grails does not ship with i18n aware <a href="../guide/single.html#16. Scaffolding" class="guide">scaffolding</a> templates to generate the controller and views. However, i18n aware templates are available via the i18n templates plugin. The templates are identical to the default scaffolding templates, except that they are i18n aware using the <a href="../ref/Tags/message.html" class="tags">message</a> tag for labels, buttons etc.<p class="paragraph"/>To get started install the i18n templates with the following command:<p class="paragraph"/><div class="code"><pre>grails install-plugin i18n-templates</pre></div><p class="paragraph"/>Then refer to the <a href="http://grails.org/I18n+Templates+Plugin" target="blank">reference on the wiki</a> which explains how to use the i18n templates.<h1><a name="11. Security">11. Security</a></h1>Grails is no more or less secure than Java Servlets. However, Java servlets (and hence Grails) are extremely secure and largely immune to common buffer overrun and malformed URL exploits due to the nature of the Java Virtual Machine underpinning the code.<p class="paragraph"/>Web security problems typically occur due to developer naivety or mistakes, and there is a little Grails can do to avoid common mistakes and make writing secure applications easier to write.<p class="paragraph"/><h4>What Grails Automatically Does</h4><p class="paragraph"/>Grails has a few built in safety mechanisms by default. |
| <ol> |
| <li>All standard database access via <a href="../guide/single.html#5. Object Relational Mapping (GORM)" class="guide">GORM</a> domain objects is automatically SQL escaped to prevent SQL injection attacks</li> |
| <li>The default <a href="../guide/single.html#16. Scaffolding" class="guide">scaffolding</a> templates HTML escape all data fields when displayed</li> |
| <li>Grails link creating tags (<a href="../ref/Tags/link.html" class="tags">link</a>, <a href="../ref/Tags/form.html" class="tags">form</a>, <a href="../ref/Tags/createLink.html" class="tags">createLink</a>, <a href="../ref/Tags/createLinkTo.html" class="tags">createLinkTo</a> and others) all use appropriate escaping mechanisms to prevent code injection</li> |
| <li>Grails provides <a href="../guide/single.html#11.2 Encoding and Decoding Objects" class="guide">codecs</a> to allow you to trivially escape data when rendered as HTML, JavaScript and URLs to prevent injection attacks here.</li> |
| </ol><p class="paragraph"/><h2><a name="11.1 Securing Against Attacks">11.1 Securing Against Attacks</a></h2><h4>SQL injection</h4><p class="paragraph"/>Hibernate, which is the technology underlying GORM domain classes, automatically escapes data when committing to database so this is not an issue. However it is still possible to write bad dynamic HQL code that uses unchecked request parameters. For example doing the following is vulnerable to HQL injection attacks:<p class="paragraph"/><div class="code"><pre>def vulnerable = { |
| def books = Book.find(<span class="java-quote">"from Book as b where b.title ='"</span> + params.title + <span class="java-quote">"'"</span>) |
| }</pre></div><p class="paragraph"/>Do <strong class="bold">not</strong> do this. If you need to pass in parameters use named or positional parameters instead:<p class="paragraph"/><div class="code"><pre>def safe = { |
| def books = Book.find(<span class="java-quote">"from Book as b where b.title =?"</span>, [params.title]) |
| }</pre></div><p class="paragraph"/> |
| <h4>Phishing</h4><p class="paragraph"/>This really a public relations issue in terms of avoiding hijacking of your branding and a declared communication policy with your customers. Customers need to know how to identify bonafide emails received.<p class="paragraph"/><h4>XSS - cross-site scripting injection</h4><p class="paragraph"/>It is important that your application verifies as much as possible that incoming requests were originated from your application and not from another site. Ticketing and page flow systems can help this and Grails' support for <a href="http://www.springsource.org/webflow" target="blank">Spring Web Flow</a> includes security like this by default.<p class="paragraph"/>It is also important to ensure that all data values rendered into views are escaped correctly. For example when rendering to HTML or XHTML you must call <a href="../guide/single.html#11.2 Encoding and Decoding Objects" class="guide">encodeAsHTML</a> on every object to ensure that people cannot maliciously inject JavaScript or other HTML into data or tags viewed by others. Grails supplies several <a href="../guide/single.html#11.2 Encoding and Decoding Objects" class="guide">Dynamic Encoding Methods</a> for this purpose and if your output escaping format is not supported you can easily write your own codec.<p class="paragraph"/>You must also avoid the use of request parameters or data fields for determining the next URL to redirect the user to. If you use a <code>successURL</code> parameter for example to determine where to redirect a user to after a successful login, attackers can imitate your login procedure using your own site, and then redirect the user back to their own site once logged in, potentially allowing JS code to then exploit the logged-in account on the site.<p class="paragraph"/><h4>HTML/URL injection</h4><p class="paragraph"/>This is where bad data is supplied such that when it is later used to create a link in a page, clicking it will not cause the expected behaviour, and may redirect to another site or alter request parameters.<p class="paragraph"/>HTML/URL injection is easily handled with the <a href="../guide/single.html#11.2 Encoding and Decoding Objects" class="guide">codecs</a> supplied by Grails, and the tag libraries supplied by Grails all use <a href="../guide/single.html#11.2 Encoding and Decoding Objects" class="guide">encodeAsURL</a> where appropriate. If you create your own tags that generate URLs you will need to be mindful of doing this too.<p class="paragraph"/><h4>Denial of service</h4><p class="paragraph"/>Load balancers and other appliances are more likely to be useful here, but there are also issues relating to excessive queries for example where a link is created by an attacker to set the maximum value of a result set so that a query could exceed the memory limits of the server or slow the system down. The solution here is to always sanitize request parameters before passing them to dynamic finders or other GORM query methods:<p class="paragraph"/><div class="code"><pre>def safeMax = <span class="java-object">Math</span>.max(params.max?.toInteger(), 100) // limit to 100 results |
| <span class="java-keyword">return</span> Book.list(max:safeMax)</pre></div><p class="paragraph"/><h4>Guessable IDs</h4><p class="paragraph"/>Many applications use the last part of the URL as an "id" of some object to retrieve from GORM or elsewhere. Especially in the case of GORM these are easily guessable as they are typically sequential integers.<p class="paragraph"/>Therefore you must assert that the requesting user is allowed to view the object with the requested id before returning the response to the user.<p class="paragraph"/>Not doing this is "security through obscurity" which is inevitably breached, just like having a default password of "letmein" and so on.<p class="paragraph"/>You must assume that every unprotected URL is publicly accessible one way or another.<h2><a name="11.2 Encoding and Decoding Objects">11.2 Encoding and Decoding Objects</a></h2>Grails supports the concept of dynamic encode/decode methods. A set of standard codecs are bundled with Grails. Grails also supports a simple mechanism for developers to contribute their own codecs that will be recognized at runtime.<p class="paragraph"/><h4>Codec Classes</h4><p class="paragraph"/>A Grails codec class is a class that may contain an encode closure, a decode closure or both. When a Grails application starts up the Grails framework will dynamically load codecs from the <code>grails-app/utils/</code> directory.<p class="paragraph"/>The framework will look 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 ship with Grails is <code>HTMLCodec</code>.<p class="paragraph"/>If a codec contains an <code>encode</code> property assigned a block of code Grails will create a dynamic <code>encode</code> method and add that method to the Object class with a name representing the codec that defined the encode closure. For example, the <code>HTMLCodec</code> class defines an <code>encode</code> block so Grails will attach that closure to the <code>Object</code> class with the name <code>encodeAsHTML</code>.<p class="paragraph"/>The <code>HTMLCodec</code> and <code>URLCodec</code> classes also define a <code>decode</code> block so Grails will attach those with the names <code>decodeHTML</code> and <code>decodeURL</code>. 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' and that description may contain special characters that need to be escaped to be presented in an HTML document. One way to deal with that in a GSP is to encode the description property using the dynamic encode method as shown below:<p class="paragraph"/><div class="code"><pre>${report.description.encodeAsHTML()}</pre></div><p class="paragraph"/>Decoding is performed using <code>value.decodeHTML()</code> syntax.<p class="paragraph"/><h4>Standard Codecs</h4><p class="paragraph"/><strong class="bold">HTMLCodec</strong><p class="paragraph"/>This codec perfoms HTML escaping and unescaping, so that values you provide can be rendered safely in an HTML page without creating any HTML tags or damaging the page layout. For example, given a value "Don't you know that 2 > 1?" you wouldn't be able to show this safely within an HTML page because the > will look like it closes a tag, which is especially bad if you render this data within an attribute, such as the value attribute of an input field.<p class="paragraph"/>Example of usage:<p class="paragraph"/><div class="code"><pre><input name=<span class="java-quote">"comment.message"</span> value=<span class="java-quote">"${comment.message.encodeAsHTML()}"</span>/></pre></div><p class="paragraph"/> |
| <blockquote class="note"> |
| Note that the HTML encoding does not re-encode apostrophe/single quote so you must use double quotes on attribute values to avoid text with apostrophes messing up your page. |
| </blockquote><p class="paragraph"/><strong class="bold">URLCodec</strong><p class="paragraph"/>URL encoding is required when creating URLs in links or form actions, or any time data may be used to create a URL. It prevents illegal characters getting into the URL to change its meaning, for example a "Apple & Blackberry" is not going to work well as a parameter in a GET request as the ampersand will break the parsing of parameters.<p class="paragraph"/>Example of usage:<p class="paragraph"/><div class="code"><pre><a href=<span class="java-quote">"/mycontroller/find?searchKey=${lastSearch.encodeAsURL()}"</span>>Repeat last search</a></pre></div><p class="paragraph"/> |
| <strong class="bold">Base64Codec</strong><p class="paragraph"/>Performs Base64 encode/decode functions. Example of usage:<p class="paragraph"/><div class="code"><pre>Your registration code is: ${user.registrationCode.encodeAsBase64()}</pre></div><p class="paragraph"/> |
| <strong class="bold">JavaScriptCodec</strong><p class="paragraph"/>Will escape Strings so they can be used as valid JavaSctipt strings. Example of usage:<p class="paragraph"/><div class="code"><pre>Element.update('${elementId}', '${render(template: <span class="java-quote">"/common/message"</span>).encodeAsJavaScript()}')</pre></div><p class="paragraph"/> |
| <strong class="bold">HexCodec</strong><p class="paragraph"/>Will encode byte arrays or lists of integers to lowercase hexadecimal strings, and can decode hexadecimal strings into byte arrays. Example of usage:<p class="paragraph"/><div class="code"><pre>Selected colour: #${[255,127,255].encodeAsHex()}</pre></div><p class="paragraph"/> |
| <strong class="bold">MD5Codec</strong><p class="paragraph"/>Will use the MD5 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encoding), as a lowercase hexadecimal string. Example of usage:<p class="paragraph"/><div class="code"><pre>Your API Key: ${user.uniqueID.encodeAsMD5()}</pre></div><p class="paragraph"/><strong class="bold">MD5BytesCodec</strong><p class="paragraph"/>Will use the MD5 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encoding), as a byte array. Example of usage:<p class="paragraph"/><div class="code"><pre><span class="java-object">byte</span>[] passwordHash = params.password.encodeAsMD5Bytes()</pre></div><p class="paragraph"/> |
| <strong class="bold">SHA1Codec</strong><p class="paragraph"/>Will use the SHA1 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encoding), as a lowercase hexadecimal string. Example of usage:<p class="paragraph"/><div class="code"><pre>Your API Key: ${user.uniqueID.encodeAsSHA1()}</pre></div><p class="paragraph"/><strong class="bold">SHA1BytesCodec</strong><p class="paragraph"/>Will use the SHA1 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encoding), as a byte array. Example of usage:<p class="paragraph"/><div class="code"><pre><span class="java-object">byte</span>[] passwordHash = params.password.encodeAsSHA1Bytes()</pre></div><p class="paragraph"/> |
| <strong class="bold">SHA256Codec</strong><p class="paragraph"/>Will use the SHA256 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encoding), as a lowercase hexadecimal string. Example of usage:<p class="paragraph"/><div class="code"><pre>Your API Key: ${user.uniqueID.encodeAsSHA256()}</pre></div><p class="paragraph"/><strong class="bold">SHA256BytesCodec</strong><p class="paragraph"/>Will use the SHA256 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encoding), as a byte array. Example of usage:<p class="paragraph"/><div class="code"><pre><span class="java-object">byte</span>[] passwordHash = params.password.encodeAsSHA256Bytes()</pre></div><p class="paragraph"/> |
| <h4>Custom Codecs</h4><p class="paragraph"/>Applications may define their own codecs and Grails will load them along with the standard codecs. A custom codec class must be defined in the <code>grails-app/utils/</code> directory and the class name must end with <code>Codec</code>. The codec may contain a <code>static</code> <code>encode</code> block, a <code>static</code> <code>decode</code> block or both. The block should expect a single argument which will be the object that the dynamic method was invoked on. For Example:<p class="paragraph"/><div class="code"><pre>class PigLatinCodec { |
| <span class="java-keyword">static</span> encode = { str -> |
| // convert the string to piglatin and <span class="java-keyword">return</span> the result |
| } |
| }</pre></div><p class="paragraph"/> |
| With the above codec in place an application could do something like this:<p class="paragraph"/><div class="code"><pre>${lastName.encodeAsPigLatin()}</pre></div><p class="paragraph"/><h2><a name="11.3 Authentication">11.3 Authentication</a></h2>Although there is no current default mechanism for authentication as it is possible to implement authentication in literally thousands of different ways. It is however, trivial to implement a simple authentication mechanism using either <a href="../guide/single.html#6.1.5 Controller Interceptors" class="guide">interceptors</a> or <a href="../guide/single.html#6.6 Filters" class="guide">filters</a>.<p class="paragraph"/>Filters allow you to apply authentication across all controllers or across a URI space. For example you can create a new set of filters in a class called <code>grails-app/conf/SecurityFilters.groovy</code>:<p class="paragraph"/><div class="code"><pre>class SecurityFilters { |
| def filters = { |
| loginCheck(controller:'*', action:'*') { |
| before = { |
| <span class="java-keyword">if</span>(!session.user && actionName != <span class="java-quote">"login"</span>) { |
| redirect(controller:<span class="java-quote">"user"</span>,action:<span class="java-quote">"login"</span>) |
| <span class="java-keyword">return</span> <span class="java-keyword">false</span> |
| } |
| }<p class="paragraph"/> } |
| } |
| }</pre></div><p class="paragraph"/>Here the <code>loginCheck</code> filter will intercept execution <em class="italic">before</em> an action executed and if their is no user in the session and the action being executed is not the <code>login</code> action then redirect to the <code>login</code> action.<p class="paragraph"/>The <code>login</code> action itself is trivial too:<p class="paragraph"/><div class="code"><pre>def login = { |
| <span class="java-keyword">if</span>(request.get) render(view:<span class="java-quote">"login"</span>) |
| <span class="java-keyword">else</span> { |
| def u = User.findByLogin(params.login) |
| <span class="java-keyword">if</span>(u) { |
| <span class="java-keyword">if</span>(u.password == params.password) { |
| session.user = u |
| redirect(action:<span class="java-quote">"home"</span>) |
| } |
| <span class="java-keyword">else</span> { |
| render(view:<span class="java-quote">"login"</span>, model:[message:<span class="java-quote">"Password incorrect"</span>]) |
| } |
| } |
| <span class="java-keyword">else</span> { |
| render(view:<span class="java-quote">"login"</span>, model:[message:<span class="java-quote">"User not found"</span>]) |
| } |
| } |
| }</pre></div><h2><a name="11.4 Security Plug-ins">11.4 Security Plug-ins</a></h2>If you need more advanced functionality beyond simple authentication such as authorization, roles etc. then you may want to consider using one of the available security plug-ins.<h2><a name="11.4.1 Spring Security">11.4.1 Spring Security</a></h2>The Spring Security plugins are built on the <a href="http://static.springsource.org/spring-security/site/" target="blank">Spring Security</a> project which provides a flexible, extensible framework for building all sorts of authentication and authorization schemes. The plugins are modular so you can install just the functionality that you need for your application. There is a Core plugin which supports form-based authentication, encrypted/salted passwords, HTTP Basic authentication, etc. and secondary dependent plugins provide alternate functionality such as OpenID authentication, ACL support, etc.<p class="paragraph"/>See the <a href="http://grails.org/plugin/spring-security-core" target="blank">plugin page</a> for basic information and the <a href="http://burtbeckwith.github.com/grails-spring-security-core/" target="blank">user guide</a> for detailed information. |
| <h2><a name="11.4.2 Shiro">11.4.2 Shiro</a></h2><a href="http://incubator.apache.org/shiro/" target="blank">Shiro</a> is a Java POJO oriented security framework that provides a default domain model that models realms, users, roles and permissions. With Shiro you have to extends a controller base called called <code>JsecAuthBase</code> in each controller you want secured and then provide an <code>accessControl</code> block to setup the roles. An example below:<p class="paragraph"/><div class="code"><pre>class ExampleController <span class="java-keyword">extends</span> JsecAuthBase { |
| <span class="java-keyword">static</span> accessControl = { |
| // All actions require the 'Observer' role. |
| role(name: 'Observer')<p class="paragraph"/> // The 'edit' action requires the 'Administrator' role. |
| role(name: 'Administrator', action: 'edit')<p class="paragraph"/> // Alternatively, several actions can be specified. |
| role(name: 'Administrator', only: [ 'create', 'edit', 'save', 'update' ]) |
| }<p class="paragraph"/> … |
| }</pre></div><p class="paragraph"/>For more information on the Shiro plugin refer to the <a href="http://grails.org/plugin/shiro" target="blank">documentation</a>. |
| <h1><a name="12. Plug-ins">12. Plug-ins</a></h1>Grails provides a number of extension points that allow you to extend anything from the command line interface to the runtime configuration engine. The following sections detail how to go about it.<h2><a name="12.1 Creating and Installing Plug-ins">12.1 Creating and Installing Plug-ins</a></h2><h4>Creating Plugins</h4><p class="paragraph"/>Creating a Grails plugin is a simple matter of running the command:<p class="paragraph"/><div class="code"><pre>grails create-plugin [PLUGIN NAME]</pre></div><p class="paragraph"/>This will create a plugin project for the name you specify. Say for example you run <code>grails create-plugin example</code>. This would create a new plugin project called <code>example</code>.<p class="paragraph"/>The structure of a Grails plugin is exactly the same as a regular Grails project's directory structure, except that in the root of the plugin directory you will find a plugin Groovy file called the "plugin descriptor".<p class="paragraph"/>Being a regular Grails project has a number of benefits in that you can immediately get going testing your plugin by running:<p class="paragraph"/><div class="code"><pre>grails run-app</pre></div><p class="paragraph"/>The plugin descriptor itself ends with the convention <code>GrailsPlugin</code> and is found in the root of the plugin project. For example:<p class="paragraph"/><div class="code"><pre>class ExampleGrailsPlugin { |
| def version = 0.1<p class="paragraph"/> … |
| }</pre></div><p class="paragraph"/>All plugins must have this class in the root of their directory structure to be valid. The plugin class defines the version of the plugin and optionally various hooks into plugin extension points (covered shortly).<p class="paragraph"/>You can also provide additional information about your plugin using several special properties: |
| <ul class="star"> |
| <li><code>title</code> - short one sentence description of your plugin</li> |
| <li><code>version</code> - The version of your problem. Valid versions are for example "0.1", "0.2-SNAPSHOT", "0.1.4" etc.</li> |
| <li><code>grailsVersion</code> - The version of version range of Grails that the plugin supports. eg. "1.1 > *"</li> |
| <li><code>author</code> - plug-in author's name</li> |
| <li><code>authorEmail</code> - plug-in author's contact e-mail</li> |
| <li><code>description</code> - full multi-line description of plug-in's features</li> |
| <li><code>documentation</code> - URL where plug-in's documentation can be found</li> |
| </ul><p class="paragraph"/>Here is an example from <a href="http://grails.org/Quartz+plugin:" target="blank">Quartz Grails plugin</a><p class="paragraph"/><div class="code"><pre>class QuartzGrailsPlugin { |
| def version = <span class="java-quote">"0.1"</span> |
| def grailsVersion = <span class="java-quote">"1.1 > *"</span> |
| def author = <span class="java-quote">"Sergey Nebolsin"</span> |
| def authorEmail = <span class="java-quote">"nebolsin@gmail.com"</span> |
| def title = <span class="java-quote">"This plugin adds Quartz job scheduling features to Grails application."</span> |
| def description = ''' |
| Quartz plugin allows your Grails application to schedule jobs to be |
| executed using a specified interval or cron expression. The underlying |
| system uses the Quartz Enterprise Job Scheduler configured via Spring, |
| but is made simpler by the coding by convention paradigm. |
| ''' |
| def documentation = <span class="java-quote">"http://grails.org/Quartz+plugin"</span><p class="paragraph"/> … |
| }</pre></div><p class="paragraph"/><h4>Installing & Distributing Plugins</h4><p class="paragraph"/>To distribute a plugin you need to navigate to its root directory in a terminal window and then type:<p class="paragraph"/><div class="code"><pre>grails <span class="java-keyword">package</span>-plugin</pre></div><p class="paragraph"/>This will create a zip file of the plugin starting with <code>grails-</code> then the plugin name and version. For example with the example plug-in created earlier this would be <code>grails-example-0.1.zip</code>. The <code>package-plugin</code> command will also generate <code>plugin.xml</code> file which contains machine-readable information about plugin's name, version, author, and so on.<p class="paragraph"/>Once you have a plugin distribution file you can navigate to a Grails project and type:<p class="paragraph"/><div class="code"><pre>grails install-plugin /path/to/plugin/grails-example-0.1.zip</pre></div><p class="paragraph"/>If the plugin is hosted on a remote HTTP server you can also do:<p class="paragraph"/><div class="code"><pre>grails install-plugin http://myserver.com/plugins/grails-example-0.1.zip</pre></div><p class="paragraph"/><h4>Notes on excluded Artefacts</h4><p class="paragraph"/>Although the <a href="../ref/Command Line/create-plugin.html" class="commandLine">create-plugin</a> command creates certain files for you so that the plug-in can be run as a Grails application, not all of these files are included when packaging a plug-in. The following is a list of artefacts created, but not included by <a href="../ref/Command Line/package-plugin.html" class="commandLine">package-plugin</a>: |
| <ul class="star"> |
| <li><code>grails-app/conf/DataSource.groovy</code></li> |
| <li><code>grails-app/conf/UrlMappings.groovy</code></li> |
| <li><code>build.xml</code></li> |
| <li>Everything within <code>/web-app/WEB-INF</code></li> |
| </ul><p class="paragraph"/>If you need artefacts within <code>WEB-INF</code> it is recommended you use the <code>_Install.groovy</code> script (covered later), which is executed when a plug-in is installed, to provide such artefacts. In addition, although <code>UrlMappings.groovy</code> is excluded you are allowed to include a <code>UrlMappings</code> definition with a different name, such as <code>FooUrlMappings.groovy</code>.<p class="paragraph"/><h4>Specifying Plugin Locations</h4><p class="paragraph"/>An application can load plugins from anywhere on the file system, even if they have not been installed. Simply add the location of the (unpacked) plugin to the application's <code>grails-app/conf/BuildConfig.groovy</code> file:<p class="paragraph"/><div class="code"><pre>// Useful to test plugins you are developing. |
| grails.plugin.location.jsecurity = <span class="java-quote">"/home/dilbert/dev/plugins/grails-jsecurity"</span><p class="paragraph"/>// Useful <span class="java-keyword">for</span> modular applications where all plugins and |
| // applications are in the same directory. |
| grails.plugin.location.'grails-ui' = <span class="java-quote">"../grails-grails-ui"</span></pre></div><p class="paragraph"/>This is particularly useful in two cases: |
| <ul class="star"> |
| <li>You are developing a plugin and want to test it in a real application without packaging and installing it first.</li> |
| <li>You have split an application into a set of plugins and an application, all in the same "super-project" directory.</li> |
| </ul><p class="paragraph"/> |
| <h2><a name="12.2 Plugin Repositories">12.2 Plugin Repositories</a></h2><h4>Distributing Plugins in the Grails Central Plugins Repository</h4><p class="paragraph"/>The preferred way of plugin distribution is to publish your under Grails Plugins Repository. This will make your plugin visible to the <a href="../ref/Command Line/list-plugins.html" class="commandLine">list-plugins</a> command:<p class="paragraph"/><div class="code"><pre>grails list-plugins</pre></div><p class="paragraph"/>Which lists all plugins in the Grails Plugin repository and also the <a href="../ref/Command Line/plugin-info.html" class="commandLine">plugin-info</a> command:<p class="paragraph"/><div class="code"><pre>grails plugin-info [plugin-name]</pre></div><p class="paragraph"/>Which outputs more information based on the meta info entered into the plug-in descriptor.<p class="paragraph"/><blockquote class="note"> |
| If you have created a Grails plugin and want it to be hosted in the central repository take a look at the wiki page <a href="http://grails.org/Creating+Plugins" target="blank"></a>, which details how to go about releasing your plugin in the repository. |
| </blockquote><p class="paragraph"/>When you have access to the Grails Plugin repository to release your plugin you simply have to execute the <a href="../ref/Command Line/release-plugin.html" class="commandLine">release-plugin</a> command:<p class="paragraph"/><div class="code"><pre>grails release-plugin</pre></div><p class="paragraph"/>This will automatically commit changes to SVN, do some tagging and make your changes available via the <a href="../ref/Command Line/list-plugins.html" class="commandLine">list-plugins</a> command.<p class="paragraph"/><h4>Configuring Additional Repositories</h4><p class="paragraph"/>The way in which you configure repositories in Grails differs between Grails versions. For version of Grails 1.2 and earlier please refer to the <a href="https://grails.apache.org/docs/1.2.x/guide/12.%20Plug-ins.html#12.2%20Plugin%20Repositories" target="blank">Grails 1.2 documentation</a> on the subject. The following sections cover Grails 1.3 and above.<p class="paragraph"/>Grails 1.3 and above use Ivy under the hood to resolve plugin dependencies. The mechanism for defining additional plugin repositories is largely the same as <a href="../guide/single.html#3.7 Dependency Resolution" class="guide">defining repositories for JAR dependencies</a>. For example you can define a remote Maven repository that contains Grails plugins using the following syntax in <code>grails-app/conf/BuildConfig.groovy</code>:<p class="paragraph"/><div class="code"><pre>repositories { |
| mavenRepo <span class="java-quote">"http://repository.codehaus.org"</span> |
| }</pre></div><p class="paragraph"/>You can also define a SVN-based Grails repository (such as the one hosted at https://grails.apache.org/plugins.html/) using the <code>grailsRepo</code> method:<p class="paragraph"/><div class="code"><pre>repositories { |
| grailsRepo <span class="java-quote">"http://myserver/mygrailsrepo"</span> |
| }</pre></div><p class="paragraph"/>There is a shortcut to setup the Grails central repository:<p class="paragraph"/><div class="code"><pre>repositories { |
| grailsCentral() |
| }</pre></div><p class="paragraph"/>The order in which plugins are resolved is based on the ordering of the repositories. So for example in this case the Grails central repository will be searched last:<p class="paragraph"/><div class="code"><pre>repositories { |
| grailsRepo <span class="java-quote">"http://myserver/mygrailsrepo"</span> |
| grailsCentral() |
| }</pre></div><p class="paragraph"/>All of the above examples use HTTP, however you can specify any <a href="http://ant.apache.org/ivy/history/latest-milestone/settings/resolvers.html" target="blank">Ivy resolver</a> to resolve plugins with. Below is an example that uses an SSH resolver:<p class="paragraph"/><div class="code"><pre>def sshResolver = <span class="java-keyword">new</span> SshResolver(user:<span class="java-quote">"myuser"</span>, host:<span class="java-quote">"myhost.com"</span>) |
| sshResolver.addArtifactPattern(<span class="java-quote">"/path/to/repo/grails-[artifact]/tags/LATEST_RELEASE/grails-[artifact]-[revision].[ext]"</span>) |
| sshResolver.latestStrategy = <span class="java-keyword">new</span> org.apache.ivy.plugins.latest.LatestTimeStrategy() |
| sshResolver.changingPattern = <span class="java-quote">".*SNAPSHOT"</span> |
| sshResolver.setCheckmodified(<span class="java-keyword">true</span>)</pre></div><p class="paragraph"/>The above example defines an artifact pattern which tells Ivy how to resolve a plugin zip file. For a more detailed explanation on Ivy patterns see the <a href="http://ant.apache.org/ivy/history/2.1.0/concept.html#patterns" target="blank">relevant section</a> in the Ivy user guide.<p class="paragraph"/><h4>Publishing to Maven Compatible Repositories</h4><p class="paragraph"/>In general it is recommended for Grails 1.3 and above to use standard Maven-style repositories to self host plugins. The benefits of doing so include the ability for existing tooling and repository managers to interpret the structure of a Maven repository. In addition Maven compatible repositories are not tied to SVN as Grails repositories are.<p class="paragraph"/>In order to publish a plugin to a Maven repository you need to use the Maven publisher plugin. Please refer to the section of the <a href="../guide/single.html#3.7.9 Deploying to a Maven Repository" class="guide">Maven deployment</a> user guide on the subject.<p class="paragraph"/><h4>Publishing to Grails Compatible Repositories</h4><p class="paragraph"/>To publish a Grails plugin to a Grails compatible repository you specify the <code>grails.plugin.repos.distribution.myRepository</code> setting within the grails-app/conf/BuildConfig.groovy file:<p class="paragraph"/><div class="code"><pre>grails.plugin.repos.distribution.myRepository=<span class="java-quote">"https://svn.codehaus.org/grails/trunk/grails-test-plugin-repo"</span></pre></div><p class="paragraph"/>You can also provide this settings in the USER_HOME/.grails/settings.groovy file if you prefer to share the same settings across multiple projects.<p class="paragraph"/>Once this is done you need to use the <code>repository</code> argument of the <code>release-plugin</code> command to specify the repository you want to release the plugin into:<p class="paragraph"/><div class="code"><pre>grails release-plugin -repository=myRepository</pre></div><p class="paragraph"/><p class="paragraph"/><h2><a name="12.3 Understanding a Plug-ins Structure">12.3 Understanding a Plug-ins Structure</a></h2>As as mentioned previously, a plugin is merely a regular Grails application with a contained plug-in descriptors. However when installed, the structure of a plugin differs slightly. For example, take a look at this plugin directory structure:<p class="paragraph"/><div class="code"><pre>+ grails-app |
| + controllers |
| + domain |
| + taglib |
| etc. |
| + lib |
| + src |
| + java |
| + groovy |
| + web-app |
| + js |
| + css</pre></div><p class="paragraph"/>Essentially when a plugin is installed into a project, the contents of the <code>grails-app</code> directory will go into a directory such as <code>plugins/example-1.0/grails-app</code>. They <strong class="bold">will not</strong> be copied into the main source tree. A plugin never interferes with a project's primary source tree.<p class="paragraph"/>Dealing with static resources is slightly different. When developing a plugin, just like an application, all static resources can go in the <code>web-app</code> directory. You can then link to static resources just like in an application (example below links to a javascript source):<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><g:resource dir=<span class="xml-quote">"js"</span> file=<span class="xml-quote">"mycode.js"</span> /></span></pre></div><p class="paragraph"/>When you run the plugin in development mode the link to the resource will resolve to something like <code>/js/mycode.js</code>. However, when the plugin is installed into an application the path will automatically change to something like <code>/plugin/example-0.1/js/mycode.js</code> and Grails will deal with making sure the resources are in the right place.<p class="paragraph"/>There is a special <code>pluginContextPath</code> variable that can be used whilst both developing the plugin and when in the plugin is installed into the application to find out what the correct path to the plugin is.<p class="paragraph"/>At runtime the <code>pluginContextPath</code> variable will either evaluate to an empty string or <code>/plugins/example</code> depending on whether the plugin is running standalone or has been installed in an application<p class="paragraph"/>Java & Groovy code that the plugin provides within the lib and <code>src/java</code> and <code>src/groovy</code> directories will be compiled into the main project's <code>web-app/WEB-INF/classes</code> directory so that they are made available at runtime. |
| <h2><a name="12.4 Providing Basic Artefacts">12.4 Providing Basic Artefacts</a></h2><h4>Adding a new Script</h4><p class="paragraph"/>A plugin can add a new script simply by providing the relevant Gant script within the scripts directory of the plugin:<p class="paragraph"/><div class="code"><pre>+ MyPlugin.groovy |
| + scripts <-- additional scripts here |
| + grails-app |
| + controllers |
| + services |
| + etc. |
| + lib</pre></div><p class="paragraph"/><h4>Adding a new Controller, Tag Library or Service</h4><p class="paragraph"/>A plugin can add a new controller, tag libraries, service or whatever by simply creating the relevant file within the <code>grails-app</code> tree. Note that when the plugin is installed it will be loaded from where it is installed and not copied into the main application tree.<p class="paragraph"/><div class="code"><pre>+ ExamplePlugin.groovy |
| + scripts |
| + grails-app |
| + controllers <-- additional controllers here |
| + services <-- additional services here |
| + etc. <-- additional XXX here |
| + lib</pre></div><p class="paragraph"/><h4>Providing Views, Templates and View resolution</h4><p class="paragraph"/>When a plug-in provides a controller it may also provide default views to be rendered. This is an excellent way to modularize your application through plugins. The way it works is that Grails' view resolution mechanism will first look the view in the application it is installed into and if that fails will attempt to look for the view within the plug-in.<p class="paragraph"/>For example given a <code>AmazonGrailsPlugin</code> plug-n provided controller called <code>BookController</code> 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 will look for the same view relative to the plug-in.<p class="paragraph"/>Note however that if the view uses templates that are also provided by the plugin then the following syntax may be necessary:<p class="paragraph"/><div class="code"><pre><g:render template=<span class="java-quote">"fooTemplate"</span> plugin=<span class="java-quote">"amazon"</span>/></pre></div><p class="paragraph"/>Note the usage of the <code>plugin</code> attribute, which contains the name of the plugin where the template resides. If this is not specified then Grails will look for the template relative to the application.<p class="paragraph"/><h4>Excluded Artefacts</h4><p class="paragraph"/>Note that by default, when packaging a plug-in, Grails will excludes the following files from the packaged plug-in: |
| <ul class="star"> |
| <li>grails-app/conf/DataSource.groovy</li> |
| <li>grails-app/conf/UrlMappings.groovy</li> |
| <li>Everything under web-app/WEB-INF</li> |
| </ul><p class="paragraph"/>If your plug-in does require files under the <code>web-app/WEB-INF</code> directory it is recommended that you modify the plug-in's <code>scripts/_Install.groovy</code> Gant script to install these artefacts into the target project's directory tree.<p class="paragraph"/>In addition, the default <code>UrlMappings.groovy</code> file is excluded to avoid naming conflicts, however you are free to add a UrlMappings definition under a different name which <strong class="bold">will</strong> be included. For example a file called <code>grails-app/conf/BlogUrlMappings.groovy</code> is fine.<p class="paragraph"/>Additionally the list of includes is extensible via the <code>pluginExcludes</code> property:<p class="paragraph"/><div class="code"><pre>// resources that are excluded from plugin packaging |
| def pluginExcludes = [ |
| <span class="java-quote">"grails-app/views/error.gsp"</span> |
| ]</pre></div><p class="paragraph"/>This is useful, for example, if you want to include demo or test resources in the plugin repository, but not include them in the final distribution.<p class="paragraph"/> |
| <h2><a name="12.5 Evaluating Conventions">12.5 Evaluating Conventions</a></h2>Before moving onto looking at providing runtime configuration based on conventions you first need to understand how to evaluated those conventions from a plug-in. Essentially every plugin has an implicit <code>application</code> variable which is an instance of the <a href="../api/org/codehaus/groovy/grails/commons/GrailsApplication.html" class="api">GrailsApplication</a> interface.<p class="paragraph"/>The <code>GrailsApplication</code> interface provides methods to evaluate the conventions within the project and internally stores references to all classes within a GrailsApplication using the <a href="../api/org/codehaus/groovy/grails/commons/GrailsClass.html" class="api">GrailsClass</a> interface.<p class="paragraph"/>A <code>GrailsClass</code> represents a physical Grails resources such as a controller or a tag library. For example to get all <code>GrailsClass</code> instances you can do:<p class="paragraph"/><div class="code"><pre>application.allClasses.each { println it.name }</pre></div><p class="paragraph"/>There are a few "magic" properties that the <code>GrailsApplication</code> instance possesses that allow you to narrow the type of artefact you are interested in. For example if you only want to controllers you can do:<p class="paragraph"/><div class="code"><pre>application.controllerClasses.each { println it.name }</pre></div><p class="paragraph"/>The dynamic method conventions are as follows: |
| <ul class="star"> |
| <li><code>*Classes</code> - Retrieves all the classes for a particular artefact name. Example <code>application.controllerClasses</code>.</li> |
| <li><code>get*Class</code> - Retrieves a named class for a particular artefact. Example <code>application.getControllerClass("ExampleController")</code></li> |
| <li><code>is*Class</code> - Returns true if the given class is of the given artefact type. Example <code>application.isControllerClass(ExampleController.class)</code></li> |
| </ul><p class="paragraph"/>The <code>GrailsClass</code> interface itself provides a number of useful methods that allow you to further evaluate and work with the conventions. These include: |
| <ul class="star"> |
| <li><code>getPropertyValue</code> - Gets the initial value of the given property on the class</li> |
| <li><code>hasProperty</code> - Returns true if the class has the specified property</li> |
| <li><code>newInstance</code> - Creates a new instance of this class.</li> |
| <li><code>getName</code> - Returns the logical name of the class in the application without the trailing convention part if applicable</li> |
| <li><code>getShortName</code> - Returns the short name of the class without package prefix</li> |
| <li><code>getFullName</code> - Returns the full name of the class in the application with the trailing convention part and with the package name</li> |
| <li><code>getPropertyName</code> - Returns the name of the class as a property name</li> |
| <li><code>getLogicalPropertyName</code> - Returns the logical property name of the class in the application without the trailing convention part if applicable</li> |
| <li><code>getNaturalName</code> - Returns the name of the property in natural terms (eg. 'lastName' becomes 'Last Name')</li> |
| <li><code>getPackageName</code> - Returns the package name</li> |
| </ul><p class="paragraph"/>For a full reference refer to the <a href="../api/org/codehaus/groovy/grails/commons/GrailsClass.html" class="api">javadoc API</a>.<h2><a name="12.6 Hooking into Build Events">12.6 Hooking into Build Events</a></h2><h4>Post-Install Configuration and Participating in Upgrades</h4><p class="paragraph"/>Grails plug-ins can do post-install configuration and participate in application upgrade process (the <a href="../ref/Command Line/upgrade.html" class="commandLine">upgrade</a> command). This is achieved via two specially named scripts under <code>scripts</code> directory of the plugin - <code>_Install.groovy</code> and <code>_Upgrade.groovy</code>.<p class="paragraph"/><code>_Install.groovy</code> is executed after the plugin has been installed and <code>_Upgrade.groovy</code> is executed each time the user upgrades his application with <a href="../ref/Command Line/upgrade.html" class="commandLine">upgrade</a> command.<p class="paragraph"/>These scripts are normal <a href="../guide/single.html#4. The Command Line" class="guide">Gant</a> scripts so you can use the full power of Gant. An addition to the standard Gant variables is the <code>pluginBasedir</code> variable which points at the plugin installation basedir.<p class="paragraph"/>As an example the below <code>_Install.groovy</code> script will create a new directory type under the <code>grails-app</code> directory and install a configuration template:<p class="paragraph"/><div class="code"><pre>Ant.mkdir(dir:<span class="java-quote">"${basedir}/grails-app/jobs"</span>) |
| Ant.copy(file:<span class="java-quote">"${pluginBasedir}/src/samples/SamplePluginConfiguration.groovy"</span>, |
| todir:<span class="java-quote">"${basedir}/grails-app/conf"</span>)<p class="paragraph"/>// To access Grails home you can use following code: |
| // Ant.property(environment:<span class="java-quote">"env"</span>) |
| // grailsHome = Ant.antProject.properties.<span class="java-quote">"env.GRAILS_HOME"</span></pre></div><p class="paragraph"/> |
| <h4>Scripting events</h4><p class="paragraph"/>It is also possible to hook into command line scripting events through plug-ins. These are events triggered during execution of Grails target and plugin scripts.<p class="paragraph"/>For example, you can hook into status update output (i.e. "Tests passed", "Server running") and the creation of files or artefacts.<p class="paragraph"/>A plug-in merely has to provide an <code>_Events.groovy</code> script to listen to the required events. Refer the documentation on <a href="../guide/single.html#4.3 Hooking into Events" class="guide">Hooking into Events</a> for further information.<h2><a name="12.7 Hooking into Runtime Configuration">12.7 Hooking into Runtime Configuration</a></h2>Grails provides a number of hooks to leverage the different parts of the system and perform runtime configuration by convention.<p class="paragraph"/><h4>Hooking into the Grails Spring configuration</h4><p class="paragraph"/>First, you can hook in Grails runtime configuration by providing a property called <code>doWithSpring</code> which is assigned a block of code. For example the following snippet is from one of the core Grails plugins that provides <a href="../guide/single.html#10. Internationalization" class="guide">i18n</a> support:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.springframework.web.servlet.i18n.CookieLocaleResolver; |
| <span class="java-keyword">import</span> org.springframework.web.servlet.i18n.LocaleChangeInterceptor; |
| <span class="java-keyword">import</span> org.springframework.context.support.ReloadableResourceBundleMessageSource;<p class="paragraph"/>class I18nGrailsPlugin {<p class="paragraph"/> def version = 0.1<p class="paragraph"/> def doWithSpring = { |
| messageSource(ReloadableResourceBundleMessageSource) { |
| basename = <span class="java-quote">"WEB-INF/grails-app/i18n/messages"</span> |
| } |
| localeChangeInterceptor(LocaleChangeInterceptor) { |
| paramName = <span class="java-quote">"lang"</span> |
| } |
| localeResolver(CookieLocaleResolver) |
| } |
| }</pre></div><p class="paragraph"/>This plugin sets up the Grails <code>messageSource</code> bean and a couple of other beans to manage Locale resolution and switching. It using the <a href="../guide/single.html#14. Grails and Spring" class="guide">Spring Bean Builder</a> syntax to do so.<p class="paragraph"/><h4>Participating in web.xml Generation</h4><p class="paragraph"/>Grails generates the <code>WEB-INF/web.xml</code> file at load time, and although plugins cannot change this file directly, they can participate in the generation of the file. Essentially a plugin can provide a <code>doWithWebDescriptor</code> property that is assigned a block of code that gets passed the <code>web.xml</code> as a <code>XmlSlurper</code> <code>GPathResult</code>.<p class="paragraph"/>Consider the below example from the <code>ControllersPlugin</code>:<p class="paragraph"/><div class="code"><pre>def doWithWebDescriptor = { webXml -> |
| def mappingElement = webXml.'servlet-mapping' |
| def lastMapping = mappingElement[mappingElement.size()-1] |
| lastMapping + { |
| 'servlet-mapping' { |
| 'servlet-name'(<span class="java-quote">"grails"</span>) |
| 'url-pattern'(<span class="java-quote">"*.dispatch"</span>) |
| } |
| } |
| }</pre></div><p class="paragraph"/>Here the plugin goes through gets a reference to the last <code><servlet-mapping></code> element and appends Grails' servlet to the end of it using XmlSlurper's ability to programmatically modify XML using closures and blocks.<p class="paragraph"/> |
| <h4>Doing Post Initialisation Configuration</h4><p class="paragraph"/>Sometimes it is useful to be able do some runtime configuration after the Spring <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/ApplicationContext.html" class="api">ApplicationContext</a> has been built. In this case you can define a <code>doWithApplicationContext</code> closure property.<p class="paragraph"/><div class="code"><pre>class SimplePlugin { |
| def name=<span class="java-quote">"simple"</span> |
| def version = 1.1<p class="paragraph"/> def doWithApplicationContext = { appCtx -> |
| SessionFactory sf = appCtx.getBean(<span class="java-quote">"sessionFactory"</span>) |
| // <span class="java-keyword">do</span> something here with session factory |
| } |
| }</pre></div><p class="paragraph"/><h2><a name="12.8 Adding Dynamic Methods at Runtime">12.8 Adding Dynamic Methods at Runtime</a></h2><h4>The Basics</h4><p class="paragraph"/>Grails plugins allow you to register dynamic methods with any Grails managed or other class at runtime. New methods can only be added within a <code>doWithDynamicMethods</code> closure of a plugin.<p class="paragraph"/>For Grails managed classes like controllers, tag libraries and so forth you can add methods, constructors etc. using the <a href="http://groovy.codehaus.org/ExpandoMetaClass" target="blank">ExpandoMetaClass</a> mechanism by accessing each controller's <a href="api:http://groovy.codehaus.org/api/groovy/lang/MetaObjectProtocol.html" target="blank">MetaClass</a>:<p class="paragraph"/><div class="code"><pre>class ExamplePlugin { |
| def doWithDynamicMethods = { applicationContext -> |
| application.controllerClasses.each { controllerClass -> |
| controllerClass.metaClass.myNewMethod = {-> println <span class="java-quote">"hello world"</span> } |
| } |
| } |
| }</pre></div><p class="paragraph"/>In this case we use the implicit application object to get a reference to all of the controller classes' MetaClass instances and then add a new method called <code>myNewMethod</code> to each controller. |
| Alternatively, if you know before hand the class you wish the add a method to you can simple reference that classes <code>metaClass</code> property:<p class="paragraph"/><div class="code"><pre>class ExamplePlugin {<p class="paragraph"/> def doWithDynamicMethods = { applicationContext -> |
| <span class="java-object">String</span>.metaClass.swapCase = {-> |
| def sb = <span class="java-keyword">new</span> <span class="java-object">StringBuffer</span>() |
| delegate.each { |
| sb << (<span class="java-object">Character</span>.isUpperCase(it as <span class="java-object">char</span>) ? |
| <span class="java-object">Character</span>.toLowerCase(it as <span class="java-object">char</span>) : |
| <span class="java-object">Character</span>.toUpperCase(it as <span class="java-object">char</span>)) |
| } |
| sb.toString() |
| }<p class="paragraph"/> assert <span class="java-quote">"UpAndDown"</span> == <span class="java-quote">"uPaNDdOWN"</span>.swapCase() |
| } |
| }</pre></div><p class="paragraph"/>In this example we add a new method <code>swapCase</code> to <code>java.lang.String</code> directly by accessing its <code>metaClass</code>.<p class="paragraph"/><h4>Interacting with the ApplicationContext</h4><p class="paragraph"/>The <code>doWithDynamicMethods</code> closure gets passed the Spring <code>ApplicationContext</code> instance. This is useful as it allows you to interact with objects within it. For example if you where implementing a method to interact with Hibernate you could use the <code>SessionFactory</code> instance in combination with a <code>HibernateTemplate</code>:<p class="paragraph"/> |
| <div class="code"><pre><span class="java-keyword">import</span> org.springframework.orm.hibernate3.HibernateTemplate<p class="paragraph"/>class ExampleHibernatePlugin {<p class="paragraph"/> def doWithDynamicMethods = { applicationContext -><p class="paragraph"/> application.domainClasses.each { domainClass -><p class="paragraph"/> domainClass.metaClass.<span class="java-keyword">static</span>.load = { <span class="java-object">Long</span> id-> |
| def sf = applicationContext.sessionFactory |
| def template = <span class="java-keyword">new</span> HibernateTemplate(sf) |
| template.load(delegate, id) |
| } |
| } |
| } |
| }</pre></div><p class="paragraph"/>Also because of the autowiring and dependency injection capability of the Spring container you can implement more powerful dynamic constructors that use the application context to wire dependencies into your object at runtime:<p class="paragraph"/><div class="code"><pre>class MyConstructorPlugin {<p class="paragraph"/> def doWithDynamicMethods = { applicationContext -> |
| application.domainClasses.each { domainClass -> |
| domainClass.metaClass.constructor = {-> |
| <span class="java-keyword">return</span> applicationContext.getBean(domainClass.name) |
| } |
| }<p class="paragraph"/> } |
| }</pre></div><p class="paragraph"/>Here we actually replace the default constructor with one that looks up prototyped Spring beans instead!<p class="paragraph"/><h2><a name="12.9 Participating in Auto Reload Events">12.9 Participating in Auto Reload Events</a></h2><h4>Monitoring Resources for Changes</h4><p class="paragraph"/>Often it is valuable to monitor resources for changes and then reload those changes when they occur. This is how Grails implements advanced reloading of application state at runtime. For example, consider the below simplified snippet from the <code>ServicesPlugin</code> that Grails comes with:<p class="paragraph"/><div class="code"><pre>class ServicesGrailsPlugin { |
| … |
| def watchedResources = <span class="java-quote">"file:./grails-app/services/*Service.groovy"</span><p class="paragraph"/> … |
| def onChange = { event -> |
| <span class="java-keyword">if</span>(event.source) { |
| def serviceClass = application.addServiceClass(event.source) |
| def serviceName = <span class="java-quote">"${serviceClass.propertyName}"</span> |
| def beans = beans { |
| <span class="java-quote">"$serviceName"</span>(serviceClass.getClazz()) { bean -> |
| bean.autowire = <span class="java-keyword">true</span> |
| } |
| } |
| <span class="java-keyword">if</span>(event.ctx) { |
| event.ctx.registerBeanDefinition(serviceName, |
| beans.getBeanDefinition(serviceName)) |
| } |
| } |
| } |
| }</pre></div><p class="paragraph"/>Firstly it defines a set of <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 is a Groovy file, when it is changed it will automatically be reloaded and passed into the <code>onChange</code> closure inside the <code>event</code> object.<p class="paragraph"/>The <code>event</code> object defines a number of useful properties: |
| <ul class="star"> |
| <li><code>event.source</code> - The source of the event which is either the reloaded class or a Spring Resource</li> |
| <li><code>event.ctx</code> - The Spring <code>ApplicationContext</code> instance</li> |
| <li><code>event.plugin</code> - The plugin object that manages the resource (Usually this)</li> |
| <li><code>event.application</code> - The <code>GrailsApplication</code> instance</li> |
| </ul><p class="paragraph"/>From these objects you can evaluate the conventions and then apply the appropriate changes to the <code>ApplicationContext</code> and so forth based on the conventions, etc. In the "Services" example above, a new services bean is re-registered with the <code>ApplicationContext</code> when one of the service classes changes.<p class="paragraph"/><h4>Influencing Other Plugins</h4><p class="paragraph"/>As well as being able to react to changes that occur when a plugin changes, sometimes one plugin needs to "influence" another plugin.<p class="paragraph"/>Take for example the Services & Controllers plugins. When a service is reloaded, unless you reload the controllers too, problems will occur when you try to auto-wire the reloaded service into an older controller Class.<p class="paragraph"/>To get round this, you can specify which plugins another plugin "influences". What this means is that when one plugin detects a change, it will reload itself and then reload all influenced plugins. See this snippet from the <code>ServicesGrailsPlugin</code>:<p class="paragraph"/><div class="code"><pre>def influences = ['controllers']</pre></div><p class="paragraph"/><h4>Observing other plugins</h4><p class="paragraph"/>If there is a particular plugin that you would like to observe for changes but not necessary watch the resources that it monitors you can use the "observe" property:<p class="paragraph"/><div class="code"><pre>def observe = [<span class="java-quote">"controllers"</span>]</pre></div><p class="paragraph"/>In this case when a controller is changed you will also receive the event chained from the controllers plugin. It is also possible for a plugin to observe all loaded plugins by using a wildcard:<p class="paragraph"/><div class="code"><pre>def observe = [<span class="java-quote">"*"</span>]</pre></div><p class="paragraph"/>The Logging plugin does exactly this so that it can add the <code>log</code> property back to <em class="italic">any</em> artefact that changes while the application is running.<h2><a name="12.10 Understanding Plug-in Load Order">12.10 Understanding Plug-in Load Order</a></h2><h4>Controlling Plug-in Dependencies</h4><p class="paragraph"/>Plug-ins often depend on the presence of other plugins and can also adapt depending on the presence of others. To cover this, a plugin can define two properties. The first is called <code>dependsOn</code>. For example, take a look at this snippet from the Grails Hibernate plugin:<p class="paragraph"/><div class="code"><pre>class HibernateGrailsPlugin { |
| def version = 1.0 |
| def dependsOn = [dataSource:1.0, |
| domainClass:1.0, |
| i18n:1.0, |
| core: 1.0]<p class="paragraph"/>}</pre></div><p class="paragraph"/>As the above example demonstrates the Hibernate plugin is dependent on the presence of 4 plugins: The <code>dataSource</code> plugin, The <code>domainClass</code> plugin, the <code>i18n</code> plugin and the <code>core</code> plugin.<p class="paragraph"/>Essentially the dependencies will be loaded first and then the Hibernate plugin. If all dependencies do not load, then the plugin will not load.<p class="paragraph"/>The <code>dependsOn</code> property also supports a mini expression language for specifying version ranges. A few examples of the syntax can be seen below:<p class="paragraph"/><div class="code"><pre>def dependsOn = [foo:<span class="java-quote">"* > 1.0"</span>] |
| def dependsOn = [foo:<span class="java-quote">"1.0 > 1.1"</span>] |
| def dependsOn = [foo:<span class="java-quote">"1.0 > *"</span>]</pre></div><p class="paragraph"/>When the wildcard * character is used it denotes "any" version. The expression syntax also excludes any suffixes such as -BETA, -ALPHA etc. so for example the expression "1.0 > 1.1" would match any of the following versions: |
| <ul class="star"> |
| <li>1.1</li> |
| <li>1.0</li> |
| <li>1.0.1</li> |
| <li>1.0.3-SNAPSHOT</li> |
| <li>1.1-BETA2</li> |
| </ul><p class="paragraph"/><h4>Controlling Load Order </h4><p class="paragraph"/>Using <code>dependsOn</code> establishes a "hard" dependency in that if the dependency is not resolved, the plugin will give up and won't load. It is possible though to have a "weaker" dependency using the <code>loadAfter</code> property:<p class="paragraph"/><div class="code"><pre>def loadAfter = ['controllers']</pre></div><p class="paragraph"/>Here the plugin will be loaded after the <code>controllers</code> plugin if it exists, otherwise it will just be loaded. The plugin can then adapt to the presence of the other plugin, for example the Hibernate plugin has this code in the <code>doWithSpring</code> closure:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">if</span>(manager?.hasGrailsPlugin(<span class="java-quote">"controllers"</span>)) { |
| openSessionInViewInterceptor(OpenSessionInViewInterceptor) { |
| flushMode = HibernateAccessor.FLUSH_MANUAL |
| sessionFactory = sessionFactory |
| } |
| grailsUrlHandlerMapping.interceptors << openSessionInViewInterceptor |
| }</pre></div><p class="paragraph"/>Here the Hibernate plugin will only register an <code>OpenSessionInViewInterceptor</code> if the <code>controllers</code> plugin has been loaded. The manager variable is an instance of the <a href="../api/org/codehaus/groovy/grails/plugins/GrailsPluginManager.html" class="api">GrailsPluginManager</a> interface and it provides methods to interact with other plugins and the <code>GrailsPluginManager</code> itself from any plugin.<h1><a name="13. Web Services">13. Web Services</a></h1>Web services are all about providing a web API onto your web application and are typically implemented in either <a href="http://en.wikipedia.org/wiki/SOAP" target="blank">SOAP</a> or <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer" target="blank">REST</a>. |
| <h2><a name="13.1 REST">13.1 REST</a></h2>REST is not really a technology in itself, but more an architectural pattern. REST is extremely simple and just involves using plain XML or JSON as a communication medium, combined with URL patterns that are "representational" of the underlying system and HTTP methods such as GET, PUT, POST and DELETE.<p class="paragraph"/>Each HTTP method maps to an action. For example GET for retrieving data, PUT for creating data, POST for updating and so on. In this sense REST fits quite well with <a href="../guide/single.html#16. Scaffolding" class="guide">CRUD</a>.<p class="paragraph"/><h4>URL patterns</h4><p class="paragraph"/>The first step to implementing REST with Grails is to provide RESTful <a href="../guide/single.html#6.4 URL Mappings" class="guide">URL mappings</a>:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">static</span> mappings = { |
| <span class="java-quote">"/product/$id?"</span>(resource:<span class="java-quote">"product"</span>) |
| }</pre></div><p class="paragraph"/>What this does is map the URI <code>/product</code> onto a <code>ProductController</code>. Each HTTP method such as GET, PUT, POST and DELETE map to unique actions within the controller as outlined by the table below:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Method</th><th>Action</th></tr><tr class="table-odd"><td><code>GET</code></td><td><code>show</code></td></tr><tr class="table-even"><td><code>PUT</code></td><td><code>update</code></td></tr><tr class="table-odd"><td><code>POST</code></td><td><code>save</code></td></tr><tr class="table-even"><td><code>DELETE</code></td><td><code>delete</code></td></tr></table><p class="paragraph"/>You can alter how HTTP methods by using the capability of URL Mappings to <a href="../guide/single.html#6.4.5 Mapping to HTTP methods" class="guide">map to HTTP methods</a>:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/product/$id"</span>(controller:<span class="java-quote">"product"</span>){ |
| action = [GET:<span class="java-quote">"show"</span>, PUT:<span class="java-quote">"update"</span>, DELETE:<span class="java-quote">"delete"</span>, POST:<span class="java-quote">"save"</span>] |
| }</pre></div><p class="paragraph"/>However, unlike the <code>resource</code> argument used previously, in this case Grails will not provide automatic XML or JSON marshaling for you unless you specify the <code>parseRequest</code> argument in the URL mapping:<p class="paragraph"/><div class="code"><pre><span class="java-quote">"/product/$id"</span>(controller:<span class="java-quote">"product"</span>, parseRequest:<span class="java-keyword">true</span>){ |
| action = [GET:<span class="java-quote">"show"</span>, PUT:<span class="java-quote">"update"</span>, DELETE:<span class="java-quote">"delete"</span>, POST:<span class="java-quote">"save"</span>] |
| }</pre></div><p class="paragraph"/><h4>HTTP Methods</h4><p class="paragraph"/>In the previous section you saw how you can easily define URL mappings that map specific HTTP methods onto specific controller actions. Writing a REST client that then sends a specific HTTP method is then trivial (example in Groovy's HTTPBuilder module):<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> groovyx.net.http.* |
| <span class="java-keyword">import</span> <span class="java-keyword">static</span> groovyx.net.http.ContentType.JSON<p class="paragraph"/>def http = <span class="java-keyword">new</span> HTTPBuilder(<span class="java-quote">"http://localhost:8080/amazon"</span>)<p class="paragraph"/> http.request(Method.GET, JSON) { |
| url.path = '/book/list' |
| response.success = {resp, json -> |
| json.books.each { book -> |
| println book.title |
| } |
| } |
| }</pre></div><p class="paragraph"/>However, issuing a request with a method other than <code>GET</code> or <code>POST</code> from a regular browser is not possible without some help from Grails. When defining a <a href="../ref/Tags/form.html" class="tags">form</a> you can specify an alternative method such as <code>DELETE</code>:<p class="paragraph"/><div class="code"><pre><g:form controller=<span class="java-quote">"book"</span> method=<span class="java-quote">"DELETE"</span>> |
| .. |
| </g:form></pre></div><p class="paragraph"/>Grails will send a hidden parameter called <code>_method</code>, which will be used as the request's HTTP method. Another alternative for changing the method for non-browser clients is to use the <code>X-HTTP-Method-Override</code> to specify the alternative method name.<p class="paragraph"/><h4>XML Marshaling - Reading</h4><p class="paragraph"/>The controller implementation itself can use Grails' <a href="../guide/single.html#6.1.7 XML and JSON Responses" class="guide">XML marshaling</a> support to implement the GET method:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.converters.* |
| class ProductController { |
| def show = { |
| <span class="java-keyword">if</span>(params.id && Product.exists(params.id)) { |
| def p = Product.findByName(params.id) |
| render p as XML |
| } |
| <span class="java-keyword">else</span> { |
| def all = Product.list() |
| render all as XML |
| } |
| } |
| .. |
| }</pre></div><p class="paragraph"/>Here what we do is if there is an <code>id</code> we search for the <code>Product</code> by name and return it otherwise we return all Products. This way if we go to <code>/products</code> we get all products, otherwise if we go to <code>/product/MacBook</code> we only get a MacBook.<p class="paragraph"/><h4>XML Marshalling - Updating</h4><p class="paragraph"/>To support updates such as <code>PUT</code> and <code>POST</code> you can use the <a href="../ref/Controllers/params.html" class="controllers">params</a> object which Grails enhances with the ability to read an incoming XML packet. Given an incoming XML packet of:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><?xml version=<span class="xml-quote">"1.0"</span> encoding=<span class="xml-quote">"ISO-8859-1"</span>?></span> |
| <span class="xml-tag"><product></span> |
| <span class="xml-tag"><name></span>MacBook<span class="xml-tag"></name></span> |
| <span class="xml-tag"><vendor id=<span class="xml-quote">"12"</span>></span> |
| <span class="xml-tag"><name></span>Apple<span class="xml-tag"></name></span> |
| <span class="xml-tag"></vender></span> |
| <span class="xml-tag"></product></span></pre></div><p class="paragraph"/>You can read this XML packet using the same techniques described in the <a href="../guide/single.html#6.1.6 Data Binding" class="guide">Data Binding</a> section via the <a href="../ref/Controllers/params.html" class="controllers">params</a> object:<p class="paragraph"/><div class="code"><pre>def save = { |
| def p = <span class="java-keyword">new</span> Product(params['product'])<p class="paragraph"/> <span class="java-keyword">if</span>(p.save()) { |
| render p as XML |
| } |
| <span class="java-keyword">else</span> { |
| render p.errors |
| } |
| }</pre></div><p class="paragraph"/>In this example by indexing into the <code>params</code> object using the key <code>'product'</code> we can automatically create and bind the XML using the constructor of the <code>Product</code> class. An interesting aspect of the line: |
| <div class="code"><pre>def p = <span class="java-keyword">new</span> Product(params['product'])</pre></div> |
| Is that it requires no code changes to deal with a form submission that submits form data than it does to deal with an XML request. The exact same technique can be used with a JSON request too.<p class="paragraph"/><blockquote class="note"> |
| If you require different responses to different clients (REST, HTML etc.) you can use <a href="../guide/single.html#6.8 Content Negotiation" class="guide">content negotation</a> |
| </blockquote><p class="paragraph"/>The <code>Product</code> object is then saved and rendered as XML, otherwise an error message is produced using Grails' <a href="../guide/single.html#7. Validation" class="guide">validation</a> capabilities in the form:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><error></span> |
| <span class="xml-tag"><message></span>The property 'title' of class 'Person' must be specified<span class="xml-tag"></message></span> |
| <span class="xml-tag"></error></span></pre></div> <h2><a name="13.2 SOAP">13.2 SOAP</a></h2>There are several plugins that add SOAP support to Grails depending on your preferred approach. For Contract First SOAP services there is a <a href="http://grails.org/plugin/springws" target="blank">Spring WS</a> plugin, whilst if you want to generate a SOAP API from Grails services there are several plugins that do this including: |
| <ul class="star"> |
| <li><a href="http://xfire.codehaus.org/" target="blank">XFire</a> plugin which uses the <a href="http://xfire.codehaus.org/" target="blank">XFire</a> SOAP stack</li> |
| <li><a href="http://grails.org/plugin/cxf/" target="blank">CXF</a> plugin which uses the <a href="http://cxf.apache.org/" target="blank">CXF</a> SOAP stack</li> |
| <li><a href="http://grails.org/plugin/axis2" target="blank">Axis2</a> plugin which uses <a href="http://ws.apache.org/axis2/" target="blank">Axis2</a></li> |
| <li><a href="https://jax-ws-commons.dev.java.net/grails/" target="blank">Metro</a> plugin which uses the <a href="https://jax-ws-commons.dev.java.net/grails/" target="blank">Metro</a> framework (and can also be used for <a href="http://docs.codehaus.org/pages/viewpage.action?pageId=88342530" target="blank">Contract First</a>)</li> |
| </ul><p class="paragraph"/>Most of the SOAP integrations integrate with Grails <a href="../guide/single.html#8. The Service Layer" class="guide">services</a> via the <code>exposes</code> static property. The below example is taken from the XFire plugin:<p class="paragraph"/><div class="code"><pre>class BookService {<p class="paragraph"/> <span class="java-keyword">static</span> expose=['xfire']<p class="paragraph"/> Book[] getBooks(){ |
| Book.list() as Book[] |
| } |
| }</pre></div><p class="paragraph"/>The WSDL can then be accessed at the location: <code>http://127.0.0.1:8080/your_grails_app/services/book?wsdl</code><p class="paragraph"/>For more information on the XFire plug-in refer <a href="http://grails.org/XFire+plugin" target="blank">the documentation</a> on the wiki.<h2><a name="13.3 RSS and Atom">13.3 RSS and Atom</a></h2>No direct support is provided for RSS or Atom within Grails. You could construct RSS or ATOM feeds with the <a href="../ref/Controllers/render.html" class="controllers">render</a> method's XML capability. There is however a <a href="http://docs.codehaus.org/display/GRAILS/Feeds+Plugin" target="blank">Feeds plug-in</a> available for Grails that provides a RSS and Atom builder using the popular <a href="https://rome.dev.java.net/" target="blank">ROME</a> library. An example of its usage can be seen below:<p class="paragraph"/><div class="code"><pre>def feed = { |
| render(feedType:<span class="java-quote">"rss"</span>, feedVersion:<span class="java-quote">"2.0"</span>) { |
| title = <span class="java-quote">"My test feed"</span> |
| link = <span class="java-quote">"http://your.test.server/yourController/feed"</span><p class="paragraph"/> Article.list().each() { |
| entry(it.title) { |
| link = <span class="java-quote">"http://your.test.server/article/${it.id}"</span> |
| it.content // <span class="java-keyword">return</span> the content |
| } |
| } |
| } |
| }</pre></div><h1><a name="14. Grails and Spring">14. Grails and Spring</a></h1>This section is for advanced users and those who are interested in how Grails integrates with and builds on the <a href="http://www.springframework.org/." target="blank">Spring Framework</a> This section is also useful for <a href="../guide/single.html#12. Plug-ins" class="guide">plug-in developers</a> considering doing runtime configuration Grails.<h2><a name="14.1 The Underpinnings of Grails">14.1 The Underpinnings of Grails</a></h2>Grails is actually a <a href="http://www.springframework.org/docs/MVC-step-by-step/Spring-MVC-step-by-step.html" target="blank">Spring MVC</a> application in disguise. Spring MVC is the Spring framework's built-in MVC web application framework. Although Spring MVC suffers from the same difficulties as frameworks like Struts in terms of its ease of use, it is superbly designed and architected and was, for Grails, the perfect framework to build another framework on top of.<p class="paragraph"/>Grails leverages Spring MVC in the following areas: |
| <ul class="star"> |
| <li>Basic controller logic - Grails subclasses Spring's <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html" class="api">DispatcherServlet</a> and uses it to delegate onto Grails <a href="../guide/single.html#6.1 Controllers" class="guide">controllers</a></li> |
| <li>Data Binding and Validation - Grails' <a href="../guide/single.html#7. Validation" class="guide">validation</a> and <a href="../guide/single.html#6.1.6 Data Binding" class="guide">data binding</a> capabilities are built on those provided by Spring</li> |
| <li>Runtime configuration - Grails' entire runtime convention based system is wired together by a Spring <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/ApplicationContext.html" class="api">ApplicationContext</a></li> |
| <li>Transactions - Grails uses Spring's transaction management in <a href="../guide/single.html#5. Object Relational Mapping (GORM)" class="guide">GORM</a></li> |
| </ul><p class="paragraph"/>In other words Grails has Spring embedded running all the way through it.<p class="paragraph"/><h4>The Grails ApplicationContext</h4><p class="paragraph"/>Spring developers are often keen to understand how the Grails <code>ApplicationContext</code> instance is constructed. The basics of it are as follows. |
| <ul class="star"> |
| <li>Grails constructs a parent <code>ApplicationContext</code> from the <code>web-app/WEB-INF/applicationContext.xml</code>. This <code>ApplicationContext</code> sets up the <a href="../api/org/codehaus/groovy/grails/commons/GrailsApplication.html" class="api">GrailsApplication</a> instance and the <a href="../api/org/codehaus/groovy/grails/plugins/GrailsPluginManager.html" class="api">GrailsPluginManager</a>.</li> |
| <li>Using this <code>ApplicationContext</code> as a parent Grails' analyses the conventions with the <code>GrailsApplication</code> instance and constructs a child <code>ApplicationContext</code> that is used as the root <code>ApplicationContext</code> of the web application</li> |
| </ul><p class="paragraph"/><h4>Configured Spring Beans</h4><p class="paragraph"/>Most of Grails' configuration happens at runtime. Each <a href="../guide/single.html#12. Plug-ins" class="guide">plug-in</a> may configure Spring beans that are registered with the <code>ApplicationContext</code>. For a reference as to which beans are configured refer to the reference guide which describes each of the Grails plug-ins and which beans they configure.<h2><a name="14.2 Configuring Additional Beans">14.2 Configuring Additional Beans</a></h2><h4>Using XML</h4><p class="paragraph"/>Beans can be configured using the <code>grails-app/conf/spring/resources.xml</code> file of your Grails application. This file is typical Spring XML file and the Spring documentation has an <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-basics" target="blank">excellent reference</a> on how to go about configuration Spring beans. As a trivial example you can configure a bean with the following syntax:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><bean id=<span class="xml-quote">"myBean"</span> class=<span class="xml-quote">"my.company.MyBeanImpl"</span>></span><span class="xml-tag"></bean></span></pre></div><p class="paragraph"/>Once configured the bean, in this case named <code>myBean</code>, can be auto-wired into most Grails types including controllers, tag libraries, services and so on:<p class="paragraph"/><div class="code"><pre>class ExampleController {<p class="paragraph"/> def myBean |
| }</pre></div><p class="paragraph"/><h4>Referencing Existing Beans</h4><p class="paragraph"/> |
| Beans declared in <code>resources.xml</code> can also reference Grails classes by convention. For example if you need a reference to a service such as <code>BookService</code> in your bean you use the property name representation of the class name. In the case of <code>BookService</code> this would be <code>bookService</code>. For example:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><bean id=<span class="xml-quote">"myBean"</span> class=<span class="xml-quote">"my.company.MyBeanImpl"</span>></span> |
| <span class="xml-tag"><property name=<span class="xml-quote">"bookService"</span> ref=<span class="xml-quote">"bookService"</span> /></span> |
| <span class="xml-tag"></bean></span></pre></div><p class="paragraph"/>The bean itself would of course need a public setter, which in Groovy is defined like this:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> my.company |
| class MyBeanImpl { |
| BookService bookService |
| }</pre></div><p class="paragraph"/>or in Java like this:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> my.company; |
| class MyBeanImpl { |
| <span class="java-keyword">private</span> BookService bookService; |
| <span class="java-keyword">public</span> void setBookService(BookService theBookService) { |
| <span class="java-keyword">this</span>.bookService = theBookService; |
| } |
| }</pre></div><p class="paragraph"/>Since much of Grails configuration is done at runtime by convention many of the beans are not declared anywhere, but can still be referenced inside your Spring configuration. For example if you need a reference to the Grails <code>DataSource</code> you could do:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><bean id=<span class="xml-quote">"myBean"</span> class=<span class="xml-quote">"my.company.MyBeanImpl"</span>></span> |
| <span class="xml-tag"><property name=<span class="xml-quote">"bookService"</span> ref=<span class="xml-quote">"bookService"</span> /></span> |
| <span class="xml-tag"><property name=<span class="xml-quote">"dataSource"</span> ref=<span class="xml-quote">"dataSource"</span> /></span> |
| <span class="xml-tag"></bean></span></pre></div><p class="paragraph"/>Or if you need the Hibernate <code>SessionFactory</code> this will work:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><bean id=<span class="xml-quote">"myBean"</span> class=<span class="xml-quote">"my.company.MyBeanImpl"</span>></span> |
| <span class="xml-tag"><property name=<span class="xml-quote">"bookService"</span> ref=<span class="xml-quote">"bookService"</span> /></span> |
| <span class="xml-tag"><property name=<span class="xml-quote">"sessionFactory"</span> ref=<span class="xml-quote">"sessionFactory"</span> /></span> |
| <span class="xml-tag"></bean></span></pre></div><p class="paragraph"/>For a full reference of the available beans see the Plug-in reference in the reference guide.<p class="paragraph"/> |
| <h4>Using the Spring DSL</h4><p class="paragraph"/>If you want to use the <a href="../guide/single.html#14.3 Runtime Spring with the Beans DSL" class="guide">Spring DSL</a> that Grails provides then you need to create a <code>grails-app/conf/spring/resources.groovy</code> file and define a property called <code>beans</code> that is assigned a block:<p class="paragraph"/><div class="code"><pre>beans = { |
| // beans here |
| }</pre></div><p class="paragraph"/>The same configuration for the XML example could be represented as:<p class="paragraph"/><div class="code"><pre>beans = { |
| myBean(my.company.MyBeanImpl) { |
| bookService = ref(<span class="java-quote">"bookService"</span>) |
| } |
| }</pre></div><p class="paragraph"/>The main advantage of this way is that you can now mix logic in within your bean definitions, for example based on the <a href="../guide/single.html#3.2 Environments" class="guide">environment</a>:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.util.* |
| beans = { |
| <span class="java-keyword">switch</span>(GrailsUtil.environment) { |
| <span class="java-keyword">case</span> <span class="java-quote">"production"</span>: |
| myBean(my.company.MyBeanImpl) { |
| bookService = ref(<span class="java-quote">"bookService"</span>) |
| }<p class="paragraph"/> <span class="java-keyword">break</span> |
| <span class="java-keyword">case</span> <span class="java-quote">"development"</span>: |
| myBean(my.company.mock.MockImpl) { |
| bookService = ref(<span class="java-quote">"bookService"</span>) |
| } |
| <span class="java-keyword">break</span> |
| } |
| }</pre></div><p class="paragraph"/>The <code>GrailsApplication</code> object can be accessed by the <code>application</code> variable, which can be used to access config (amongst other things):<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> grails.util.* |
| beans = { |
| <span class="java-keyword">if</span> (application.config.my.company.mockService) { |
| myBean(my.company.mock.MockImpl) { |
| bookService = ref(<span class="java-quote">"bookService"</span>) |
| } |
| } <span class="java-keyword">else</span> { |
| myBean(my.company.MyBeanImpl) { |
| bookService = ref(<span class="java-quote">"bookService"</span>) |
| } |
| } |
| }</pre></div><h2><a name="14.3 Runtime Spring with the Beans DSL">14.3 Runtime Spring with the Beans DSL</a></h2>This Bean builder in Grails aims to provide a simplified way of wiring together dependencies that uses Spring at its core.<p class="paragraph"/> In addition, Spring's regular way of configuration (via XML) is essentially static and very difficult to modify and configure at runtime other than programmatic XML creation which is both error prone and verbose. Grails' <a href="../api/grails/spring/BeanBuilder.html" class="api">BeanBuilder</a> changes all that by making it possible to programmatically wire together components at runtime thus allowing you to adapt the logic based on system properties or environment variables.<p class="paragraph"/> This enables the code to adapt to its environment and avoids unnecessary duplication of code (having different Spring configs for test, development and production environments)<p class="paragraph"/><h4>The BeanBuilder class</h4><p class="paragraph"/>Grails provides a <a href="../api/grails/spring/BeanBuilder.html" class="api">grails.spring.BeanBuilder</a> class that uses dynamic Groovy to construct bean definitions. The basics are as follows:<p class="paragraph"/><div class="code"><pre><span class="java-keyword">import</span> org.apache.commons.dbcp.BasicDataSource |
| <span class="java-keyword">import</span> org.codehaus.groovy.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean; |
| <span class="java-keyword">import</span> org.springframework.context.ApplicationContext;<p class="paragraph"/>def bb = <span class="java-keyword">new</span> grails.spring.BeanBuilder()<p class="paragraph"/>bb.beans { |
| dataSource(BasicDataSource) { |
| driverClassName = <span class="java-quote">"org.hsqldb.jdbcDriver"</span> |
| url = <span class="java-quote">"jdbc:hsqldb:mem:grailsDB"</span> |
| username = <span class="java-quote">"sa"</span> |
| password = <span class="java-quote">""</span> |
| } |
| sessionFactory(ConfigurableLocalSessionFactoryBean) { |
| dataSource = dataSource |
| hibernateProperties = [ <span class="java-quote">"hibernate.hbm2ddl.auto"</span>:<span class="java-quote">"create-drop"</span>, |
| <span class="java-quote">"hibernate.show_sql"</span>:<span class="java-keyword">true</span> ] |
| } |
| }<p class="paragraph"/>ApplicationContext appContext = bb.createApplicationContext()</pre></div><p class="paragraph"/><blockquote class="note"> |
| Within <a href="../guide/single.html#12. Plug-ins" class="guide">plug-ins</a> and the <a href="../guide/single.html#14.2 Configuring Additional Beans" class="guide">grails-app/conf/spring/resources.groovy</a> file you don't need to create a new instance of <code>BeanBuilder</code>. Instead the DSL is implicitly available inside the <code>doWithSpring</code> and <code>beans</code> blocks respectively. |
| </blockquote><p class="paragraph"/>The above example shows how you would configure Hibernate with an appropriate data source with the <code>BeanBuilder</code> class.<p class="paragraph"/>Essentially, each method call (in this case <code>dataSource</code> and <code>sessionFactory</code> calls) map to the name of the bean in Spring. The first argument to the method is the bean's class, whilst the last argument is a block. Within the body of the block you can set properties on the bean using standard Groovy syntax<p class="paragraph"/>Bean references are resolved automatically be using the name of the bean. This can be seen in the example above with the way the <code>sessionFactory</code> bean resolves the <code>dataSource</code> reference.<p class="paragraph"/>Certain special properties related to bean management can also be set by the builder, as seen in the following code:<p class="paragraph"/><div class="code"><pre>sessionFactory(ConfigurableLocalSessionFactoryBean) { bean -> |
| bean.autowire = 'byName' // Autowiring behaviour. The other option is 'byType'. [autowire] |
| bean.initMethod = 'init' // Sets the initialisation method to 'init'. [init-method] |
| bean.destroyMethod = 'destroy' // Sets the destruction method to 'destroy'. [destroy-method] |
| bean.scope = 'request' // Sets the scope of the bean. [scope] |
| dataSource = dataSource |
| hibernateProperties = [ <span class="java-quote">"hibernate.hbm2ddl.auto"</span>:<span class="java-quote">"create-drop"</span>, |
| <span class="java-quote">"hibernate.show_sql"</span>:<span class="java-keyword">true</span> ] |
| }</pre></div><p class="paragraph"/>The strings in square brackets are the names of the equivalent bean attributes in Spring's XML definition.<p class="paragraph"/><h4>Using BeanBuilder with Spring MVC</h4><p class="paragraph"/>If you want to take advantage of BeanBuilder in a regular Spring MVC application you need to make sure the <code>grails-spring-<version>.jar</code> file is in your classpath. Once that is done you can need to set the following <code><context-param></code> values in your <code>/WEB-INF/web.xml</code> file:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><context-param></span> |
| <span class="xml-tag"><param-name></span>contextConfigLocation<span class="xml-tag"></param-name></span> |
| <span class="xml-tag"><param-value></span>/WEB-INF/applicationContext.groovy<span class="xml-tag"></param-value></span> |
| <span class="xml-tag"></context-param></span> |
| <span class="xml-tag"><context-param></span> |
| <span class="xml-tag"><param-name></span>contextClass<span class="xml-tag"></param-name></span> |
| <span class="xml-tag"><param-value></span>org.codehaus.groovy.grails.commons.spring.GrailsWebApplicationContext<span class="xml-tag"></param-value></span> |
| <span class="xml-tag"></context-param></span></pre></div><p class="paragraph"/>With that done you can then create a /WEB-INF/applicationContext.groovy file that does the rest:<p class="paragraph"/><div class="code"><pre>beans { |
| dataSource(org.apache.commons.dbcp.BasicDataSource) { |
| driverClassName = <span class="java-quote">"org.hsqldb.jdbcDriver"</span> |
| url = <span class="java-quote">"jdbc:hsqldb:mem:grailsDB"</span> |
| username = <span class="java-quote">"sa"</span> |
| password = <span class="java-quote">""</span> |
| } |
| }</pre></div><p class="paragraph"/><h4>Loading Bean Definitions from the File System</h4><p class="paragraph"/>You can use the <code>BeanBuilder</code> class to load external Groovy scripts that define beans using the same path matching syntax defined here. Example:<p class="paragraph"/><div class="code"><pre>def bb = <span class="java-keyword">new</span> BeanBuilder() |
| bb.loadBeans(<span class="java-quote">"classpath:*SpringBeans.groovy"</span>)<p class="paragraph"/>def applicationContext = bb.createApplicationContext()</pre></div><p class="paragraph"/>Here the <code>BeanBuilder</code> will load all Groovy files on the classpath ending with <code>SpringBeans.groovy</code> and parse them into bean definitions. An example script can be seen below:<p class="paragraph"/><div class="code"><pre>beans { |
| dataSource(BasicDataSource) { |
| driverClassName = <span class="java-quote">"org.hsqldb.jdbcDriver"</span> |
| url = <span class="java-quote">"jdbc:hsqldb:mem:grailsDB"</span> |
| username = <span class="java-quote">"sa"</span> |
| password = <span class="java-quote">""</span> |
| } |
| sessionFactory(ConfigurableLocalSessionFactoryBean) { |
| dataSource = dataSource |
| hibernateProperties = [ <span class="java-quote">"hibernate.hbm2ddl.auto"</span>:<span class="java-quote">"create-drop"</span>, |
| <span class="java-quote">"hibernate.show_sql"</span>:<span class="java-keyword">true</span> ] |
| } |
| }</pre></div><p class="paragraph"/> |
| <h4>Adding Variables to the Binding (Context)</h4><p class="paragraph"/>If you're loading beans from a script you can set the binding to use by creating a Groovy Binding object:<p class="paragraph"/><div class="code"><pre>def binding = <span class="java-keyword">new</span> Binding() |
| binding.foo = <span class="java-quote">"bar"</span><p class="paragraph"/>def bb = <span class="java-keyword">new</span> BeanBuilder() |
| bb.binding = binding |
| bb.loadBeans(<span class="java-quote">"classpath:*SpringBeans.groovy"</span>)<p class="paragraph"/>def ctx = bb.createApplicationContext()</pre></div> |
| <h2><a name="14.4 The BeanBuilder DSL Explained">14.4 The BeanBuilder DSL Explained</a></h2><h4>Using Constructor Arguments</h4><p class="paragraph"/>Constructor arguments can be defined using parameters to each method that reside between the class of the bean and the last closure: |
| <div class="code"><pre>bb.beans { |
| exampleBean(MyExampleBean, <span class="java-quote">"firstArgument"</span>, 2) { |
| someProperty = [1,2,3] |
| } |
| }</pre></div><p class="paragraph"/><h4>Configuring the BeanDefinition (Using factory methods)</h4><p class="paragraph"/>The first argument to the closure is a reference to the bean configuration instance, which you can use to configure factory methods and invoke any method on the <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/support/AbstractBeanDefinition.html" class="api">AbstractBeanDefinition</a> class:<p class="paragraph"/><div class="code"><pre>bb.beans { |
| exampleBean(MyExampleBean) { bean -> |
| bean.factoryMethod = <span class="java-quote">"getInstance"</span> |
| bean.singleton = <span class="java-keyword">false</span> |
| someProperty = [1,2,3] |
| } |
| }</pre></div><p class="paragraph"/>As an alternative you can also use the return value of the bean defining method to configure the bean:<p class="paragraph"/><div class="code"><pre>bb.beans { |
| def example = exampleBean(MyExampleBean) { |
| someProperty = [1,2,3] |
| } |
| example.factoryMethod = <span class="java-quote">"getInstance"</span> |
| }</pre></div><p class="paragraph"/><h4>Using Factory beans</h4><p class="paragraph"/>Spring defines the concept of factory beans and often a bean is created not from a class, but from one of these factories. In this case the bean has no class and instead you must pass the name of the factory bean to the bean:<p class="paragraph"/><div class="code"><pre>bb.beans { |
| myFactory(ExampleFactoryBean) { |
| someProperty = [1,2,3] |
| } |
| myBean(myFactory) { |
| name = <span class="java-quote">"blah"</span> |
| } |
| }</pre></div><p class="paragraph"/>Note in the example above instead of a class we pass a reference to the <code>myFactory</code> bean into the bean defining method. Another common task is provide the name of the factory method to call on the factory bean. This can be done using Groovy's named parameter syntax:<p class="paragraph"/><div class="code"><pre>bb.beans { |
| myFactory(ExampleFactoryBean) { |
| someProperty = [1,2,3] |
| } |
| myBean(myFactory:<span class="java-quote">"getInstance"</span>) { |
| name = <span class="java-quote">"blah"</span> |
| } |
| }</pre></div><p class="paragraph"/>Here the <code>getInstance</code> method on the <code>ExampleFactoryBean</code> bean will be called in order to create the <code>myBean</code> bean.<p class="paragraph"/><h4>Creating Bean References at Runtime</h4><p class="paragraph"/>Sometimes you don't know the name of the bean to be created until runtime. In this case you can use a string interpolation to invoke a bean defining method dynamically:<p class="paragraph"/><div class="code"><pre>def beanName = <span class="java-quote">"example"</span> |
| bb.beans { |
| <span class="java-quote">"${beanName}Bean"</span>(MyExampleBean) { |
| someProperty = [1,2,3] |
| } |
| }</pre></div><p class="paragraph"/>In this case the <code>beanName</code> variable defined earlier is used when invoking a bean defining method.<p class="paragraph"/>Furthermore, because sometimes bean names are not known until runtime you may need to reference them by name when wiring together other beans. In this case using the <code>ref</code> method:<p class="paragraph"/><div class="code"><pre>def beanName = <span class="java-quote">"example"</span> |
| bb.beans { |
| <span class="java-quote">"${beanName}Bean"</span>(MyExampleBean) { |
| someProperty = [1,2,3] |
| } |
| anotherBean(AnotherBean) { |
| example = ref(<span class="java-quote">"${beanName}Bean"</span>) |
| } |
| }</pre></div><p class="paragraph"/> |
| Here the example property of <code>AnotherBean</code> is set using a runtime reference to the <code>exampleBean</code>. The <code>ref</code> method can also be used to refer to beans from a parent <code>ApplicationContext</code> that is provided in the constructor of the <code>BeanBuilder</code>:<p class="paragraph"/><div class="code"><pre>ApplicationContext parent = ...// |
| der bb = <span class="java-keyword">new</span> BeanBuilder(parent) |
| bb.beans { |
| anotherBean(AnotherBean) { |
| example = ref(<span class="java-quote">"${beanName}Bean"</span>, <span class="java-keyword">true</span>) |
| } |
| }</pre></div><p class="paragraph"/>Here the second parameter <code>true</code> specifies that the reference will look for the bean in the parent context.<p class="paragraph"/><h4>Using Anonymous (Inner) Beans</h4><p class="paragraph"/>You can use anonymous inner beans by setting a property of the bean to a block that takes an argument that is the bean type:<p class="paragraph"/><div class="code"><pre>bb.beans { |
| marge(Person.class) { |
| name = <span class="java-quote">"marge"</span> |
| husband = { Person p -> |
| name = <span class="java-quote">"homer"</span> |
| age = 45 |
| props = [overweight:<span class="java-keyword">true</span>, height:<span class="java-quote">"1.8m"</span>] |
| } |
| children = [bart, lisa] |
| } |
| bart(Person) { |
| name = <span class="java-quote">"Bart"</span> |
| age = 11 |
| } |
| lisa(Person) { |
| name = <span class="java-quote">"Lisa"</span> |
| age = 9 |
| } |
| }</pre></div><p class="paragraph"/>In the above example we set the <code>marge</code> bean's husband property to a block that creates an inner bean reference. Alternatively if you have a factory bean you can ommit the type and just use passed bean definition instead to setup the factory:<p class="paragraph"/><div class="code"><pre>bb.beans { |
| personFactory(PersonFactory.class) |
| marge(Person.class) { |
| name = <span class="java-quote">"marge"</span> |
| husband = { bean -> |
| bean.factoryBean = <span class="java-quote">"personFactory"</span> |
| bean.factoryMethod = <span class="java-quote">"newInstance"</span> |
| name = <span class="java-quote">"homer"</span> |
| age = 45 |
| props = [overweight:<span class="java-keyword">true</span>, height:<span class="java-quote">"1.8m"</span>] |
| } |
| children = [bart, lisa] |
| } |
| }</pre></div><p class="paragraph"/><h4>Abstract Beans and Parent Bean Definitions</h4><p class="paragraph"/>To create an abstract bean definition define a bean that takes no class:<p class="paragraph"/><div class="code"><pre>class HolyGrailQuest { |
| def start() { println <span class="java-quote">"lets begin"</span> } |
| } |
| class KnightOfTheRoundTable { |
| <span class="java-object">String</span> name |
| <span class="java-object">String</span> leader |
| KnightOfTheRoundTable(<span class="java-object">String</span> n) { |
| <span class="java-keyword">this</span>.name = n |
| } |
| HolyGrailQuest quest<p class="paragraph"/> def embarkOnQuest() { |
| quest.start() |
| } |
| }<p class="paragraph"/>def bb = <span class="java-keyword">new</span> grails.spring.BeanBuilder() |
| bb.beans { |
| abstractBean { |
| leader = <span class="java-quote">"Lancelot"</span> |
| } |
| … |
| }</pre></div><p class="paragraph"/>Here we define an abstract bean that sets that has a <code>leader</code> property with the value of <code>"Lancelot"</code>. Now to use the abstract bean set it as the parent of the child bean:<p class="paragraph"/><div class="code"><pre>bb.beans { |
| … |
| quest(HolyGrailQuest) |
| knights(KnightOfTheRoundTable, <span class="java-quote">"Camelot"</span>) { bean -> |
| bean.parent = abstractBean |
| quest = quest |
| } |
| }</pre></div><p class="paragraph"/><blockquote class="note"> |
| When using a parent bean you must set the parent property of the bean before setting any other properties on the bean! |
| </blockquote><p class="paragraph"/>If you want an abstract bean that has a class you can do it this way:<p class="paragraph"/><div class="code"><pre>def bb = <span class="java-keyword">new</span> grails.spring.BeanBuilder() |
| bb.beans { |
| abstractBean(KnightOfTheRoundTable) { bean -> |
| bean.'<span class="java-keyword">abstract</span>' = <span class="java-keyword">true</span> |
| leader = <span class="java-quote">"Lancelot"</span> |
| } |
| quest(HolyGrailQuest) |
| knights(<span class="java-quote">"Camelot"</span>) { bean -> |
| bean.parent = abstractBean |
| quest = quest |
| } |
| }</pre></div><p class="paragraph"/>In the above 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 class, but inherits the class from the parent bean.<p class="paragraph"/><h4>Using Spring Namespaces</h4><p class="paragraph"/>Since Spring 2.0, users of Spring have been granted easier access to key features via XML namespaces. With BeanBuilder you can use any Spring namespace by first declaring it:<p class="paragraph"/><div class="code"><pre>xmlns context:<span class="java-quote">"http://www.springframework.org/schema/context"</span></pre></div><p class="paragraph"/>And then invoking a method that matches the names of the Spring namespace tag and its associated attributes:<p class="paragraph"/><div class="code"><pre>context.'component-scan'( 'base-<span class="java-keyword">package</span>' :<span class="java-quote">"my.company.domain"</span> )</pre></div><p class="paragraph"/>You can do some useful things with Spring namespaces, such as looking up a JNDI resource:<p class="paragraph"/><div class="code"><pre>xmlns jee:<span class="java-quote">"http://www.springframework.org/schema/jee"</span><p class="paragraph"/>jee.'jndi-lookup'(id:<span class="java-quote">"dataSource"</span>, 'jndi-name':<span class="java-quote">"java:comp/env/myDataSource"</span>)</pre></div><p class="paragraph"/>The example above will create a Spring bean with the identifier of <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 the following two classes:<p class="paragraph"/><div class="code"><pre>class Person { |
| <span class="java-object">int</span> age; |
| <span class="java-object">String</span> name;<p class="paragraph"/> void birthday() { |
| ++age; |
| } |
| } |
| class BirthdayCardSender { |
| List peopleSentCards = [] |
| void onBirthday(Person person) { |
| peopleSentCards << person |
| } |
| }</pre></div><p class="paragraph"/>You can define an AOP aspect that uses a pointcut to detect whenever the <code>birthday()</code> method is called:<p class="paragraph"/><div class="code"><pre>xmlns aop:<span class="java-quote">"http://www.springframework.org/schema/aop"</span> |
| fred(Person) { |
| name = <span class="java-quote">"Fred"</span> |
| age = 45 |
| }<p class="paragraph"/>birthdayCardSenderAspect(BirthdayCardSender)<p class="paragraph"/>aop { |
| config(<span class="java-quote">"proxy-target-class"</span>:<span class="java-keyword">true</span>) { |
| aspect( id:<span class="java-quote">"sendBirthdayCard"</span>,ref:<span class="java-quote">"birthdayCardSenderAspect"</span> ) { |
| after method:<span class="java-quote">"onBirthday"</span>, pointcut: <span class="java-quote">"execution(void ..Person.birthday()) and <span class="java-keyword">this</span>(person)"</span> |
| } |
| } |
| }</pre></div><h2><a name="14.5 Property Placeholder Configuration">14.5 Property Placeholder Configuration</a></h2>Grails supports the notion of property placeholder configuration through an extended version of Spring's <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html" class="api">PropertyPlaceholderConfigurer</a>, which is typically useful when used in combination with <a href="../guide/single.html#3.4 Externalized Configuration" class="guide">externalized configuration</a>.<p class="paragraph"/>Settings defined in either <a href="http://groovy.codehaus.org/ConfigSlurper" target="blank">ConfigSlurper</a> scripts of Java properties files can be used as placeholder values for Spring configuration in <code>grails-app/conf/spring/resources.xml</code>. For example given the following entries in <code>grails-app/conf/Config.groovy</code> (or an externalized config):<p class="paragraph"/><div class="code"><pre>database.driver=<span class="java-quote">"com.mysql.jdbc.Driver"</span> |
| database.dbname=<span class="java-quote">"mysql:mydb"</span></pre></div><p class="paragraph"/>You can then specify placeholders in <code>resources.xml</code> as follows using the familiar ${..} syntax:<p class="paragraph"/><div class="code"><pre><span class="xml-tag"><bean id=<span class="xml-quote">"dataSource"</span> class=<span class="xml-quote">"org.springframework.jdbc.datasource.DriverManagerDataSource"</span>></span> |
| <span class="xml-tag"><property name=<span class="xml-quote">"driverClassName"</span>></span><span class="xml-tag"><value></span>${database.driver}<span class="xml-tag"></value></span><span class="xml-tag"></property></span> |
| <span class="xml-tag"><property name=<span class="xml-quote">"url"</span>></span><span class="xml-tag"><value></span>jdbc:${database.dbname}<span class="xml-tag"></value></span><span class="xml-tag"></property></span> |
| <span class="xml-tag"></bean></span></pre></div><h2><a name="14.6 Property Override Configuration">14.6 Property Override Configuration</a></h2>Grails supports setting of bean properties via <a href="../guide/single.html#3. Configuration" class="guide">configuration</a>. This is often useful when used in combination with <a href="../guide/single.html#3.4 Externalized Configuration" class="guide">externalized configuration</a>.<p class="paragraph"/>Essentially you define a <code>beans</code> block with the names of beans and their values:<p class="paragraph"/><div class="code"><pre>beans { |
| bookService { |
| webServiceURL = <span class="java-quote">"http://www.amazon.com"</span> |
| } |
| }</pre></div><p class="paragraph"/>The general format is:<p class="paragraph"/><div class="code"><pre>[bean name].[property name] = [value]</pre></div><p class="paragraph"/>The same configuration in a Java properties file would be:<p class="paragraph"/><div class="code"><pre>beans.bookService.webServiceURL=http://www.amazon.com</pre></div><h1><a name="15. Grails and Hibernate">15. Grails and Hibernate</a></h1>If <a href="../guide/single.html#5. Object Relational Mapping (GORM)" class="guide">GORM</a> (Grails Object Relational Mapping) is not flexible enough for your liking you can alternatively map your domain classes using Hibernate, either via XML mapping files or JPA annotations. You will be able to map Grails domain classes onto a wider range of legacy systems and be more flexible in the creation of your database schema. Best of all, you will still be able to call all of the dynamic persistent and query methods provided by GORM! |
| <h2><a name="15.1 Using Hibernate XML Mapping Files">15.1 Using Hibernate XML Mapping Files</a></h2>Mapping your domain classes via XML is pretty straightforward. Simply create a <code>hibernate.cfg.xml</code> file in your project's <code>grails-app/conf/hibernate</code> directory, either manually or via the <a href="../ref/Command Line/create-hibernate-cfg-xml.html" class="commandLine">create-hibernate-cfg-xml</a> command, that contains the following: |
| <div class="code"><pre><span class="xml-tag"><?xml version='1.0' encoding='UTF-8'?></span> |
| <!DOCTYPE hibernate-configuration PUBLIC |
| <span class="xml-quote">"-//Hibernate/Hibernate Configuration DTD 3.0//EN"</span> |
| <span class="xml-quote">"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"</span>> |
| <span class="xml-tag"><hibernate-configuration></span> |
| <span class="xml-tag"><session-factory></span> |
| <span class="xml-comment"><!-- Example mapping file inclusion --></span> |
| <span class="xml-tag"><mapping resource=<span class="xml-quote">"org.example.Book.hbm.xml"</span>/></span> |
| … |
| <span class="xml-tag"></session-factory></span> |
| <span class="xml-tag"></hibernate-configuration></span></pre></div><p class="paragraph"/>The individual mapping files, like 'org.example.Book.hbm.xml' in the above example, also go into the <code>grails-app/conf/hibernate</code> directory. To find out how to map domain classes via XML, check out the <a href="http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html" target="blank">Hibernate manual</a>.<p class="paragraph"/>If the default location of the <code>hibernate.cfg.xml</code> file doesn't suit you, you can change it by specifying an alternative location in <code>grails-app/conf/DataSource.groovy</code>:<p class="paragraph"/><div class="code"><pre>hibernate { |
| config.location = <span class="java-quote">"file:/path/to/my/hibernate.cfg.xml"</span> |
| }</pre></div><p class="paragraph"/>or even a list of locations:<p class="paragraph"/><div class="code"><pre>hibernate { |
| config.location = [<span class="java-quote">"file:/path/to/one/hibernate.cfg.xml"</span>,<span class="java-quote">"file:/path/to/two/hibernate.cfg.xml"</span>] |
| }</pre></div><p class="paragraph"/>Grails also allows you to write your domain model in Java or re-use an existing one that already has Hibernate mapping files. Simply place the mapping files into <code>grails-app/conf/hibernate</code> and either put the Java files in <code>src/java</code> or (if the domain model is stored in a JAR) the packaged classes into the project's <code>lib</code> directory. You still need the <code>hibernate.cfg.xml</code> though! |
| <h2><a name="15.2 Mapping with Hibernate Annotations">15.2 Mapping with Hibernate Annotations</a></h2>To map a domain class via annotations, create a new class in <code>src/java</code> and use the annotations defined as part of the EJB 3.0 spec (for more info on this see the <a href="http://annotations.hibernate.org/" target="blank">Hibernate Annotations Docs</a>):<p class="paragraph"/><div class="code"><pre><span class="java-keyword">package</span> com.books; |
| @Entity |
| <span class="java-keyword">public</span> class Book { |
| <span class="java-keyword">private</span> <span class="java-object">Long</span> id; |
| <span class="java-keyword">private</span> <span class="java-object">String</span> title; |
| <span class="java-keyword">private</span> <span class="java-object">String</span> description; |
| <span class="java-keyword">private</span> Date date;<p class="paragraph"/> @Id |
| @GeneratedValue |
| <span class="java-keyword">public</span> <span class="java-object">Long</span> getId() { |
| <span class="java-keyword">return</span> id; |
| }<p class="paragraph"/> <span class="java-keyword">public</span> void setId(<span class="java-object">Long</span> id) { |
| <span class="java-keyword">this</span>.id = id; |
| }<p class="paragraph"/> <span class="java-keyword">public</span> <span class="java-object">String</span> getTitle() { |
| <span class="java-keyword">return</span> title; |
| }<p class="paragraph"/> <span class="java-keyword">public</span> void setTitle(<span class="java-object">String</span> title) { |
| <span class="java-keyword">this</span>.title = title; |
| }<p class="paragraph"/> <span class="java-keyword">public</span> <span class="java-object">String</span> getDescription() { |
| <span class="java-keyword">return</span> description; |
| }<p class="paragraph"/> <span class="java-keyword">public</span> void setDescription(<span class="java-object">String</span> description) { |
| <span class="java-keyword">this</span>.description = description; |
| } |
| }</pre></div><p class="paragraph"/>Once that is done you need to register the class with the Hibernate <code>sessionFactory</code> by adding relevant entries to the <code>grails-app/conf/hibernate/hibernate.cfg.xml</code> file as follows:<p class="paragraph"/><div class="code"><pre><!DOCTYPE hibernate-configuration SYSTEM |
| <span class="xml-quote">"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"</span>> |
| <span class="xml-tag"><hibernate-configuration></span> |
| <span class="xml-tag"><session-factory></span> |
| <span class="xml-tag"><mapping package=<span class="xml-quote">"com.books"</span> /></span> |
| <span class="xml-tag"><mapping class=<span class="xml-quote">"com.books.Book"</span> /></span> |
| <span class="xml-tag"></session-factory></span> |
| <span class="xml-tag"></hibernate-configuration></span></pre></div> |
| See the previous section for more information on the <code>hibernate.cfg.xml</code> file.<p class="paragraph"/>When Grails loads it will register the necessary dynamic methods with the class. To see what else you can do with a Hibernate domain class see the section on <a href="../guide/single.html#16. Scaffolding" class="guide">Scaffolding</a>.<p class="paragraph"/><h2><a name="15.3 Adding Constraints">15.3 Adding Constraints</a></h2>Even if you use a Java domain model, you can still take advantage of GORM validation. Grails allows you to define constraints through a separate script that you place in the <code>src/java</code> directory. The script should be in a directory that matches the package of the corresponding domain class and its name should have a <em class="italic">Constraints</em> suffix. For example, if you had a domain class <code>org.example.Book</code>, then you would create the script <code>src/java/org/example/BookConstraints.groovy</code>.<p class="paragraph"/>The contents of the script should contain a standard GORM constraints block like so: |
| <div class="code"><pre>constraints = { |
| title(blank: <span class="java-keyword">false</span>) |
| author(blank: <span class="java-keyword">false</span>) |
| }</pre></div> |
| Once the script is in place, you'll be able to validate instances of your domain class! |
| <h2><a name="15.4 Further Reading">15.4 Further Reading</a></h2>Grails committer, Jason Rudolph, took the time to write many useful articles about using Grails with custom Hibernate mappings including: |
| <ul class="star"> |
| <li><a href="http://jasonrudolph.com/blog/2006/06/20/hoisting-grails-to-your-legacy-db/" target="blank">Hoisting Grails to Your Legacy DB</a> - An excellent article about using Grails with Hibernate XML</li> |
| <li><a href="http://www.infoq.com/articles/grails-ejb-tutorial" target="blank">Grails + EJB3 Domain Models</a> - Another great article about using Grails with EJB3-style annotated domain models</li> |
| </ul><p class="paragraph"/><h1><a name="16. Scaffolding">16. Scaffolding</a></h1>Scaffolding allows you to auto-generate a whole application for a given domain class including: |
| <ul class="star"> |
| <li>The necessary <a href="../guide/single.html#6.2 Groovy Server Pages" class="guide">views</a></li> |
| <li>Controller actions for create/read/update/delete (CRUD) operations</li> |
| </ul><p class="paragraph"/><h4>Enabling Scaffolding</h4><p class="paragraph"/>The simplest way to get started with scaffolding is to enable scaffolding via the <code>scaffold</code> property. For the <code>Book</code> domain class, you need to set the <code>scaffold</code> property on a controller to true:<p class="paragraph"/><div class="code"><pre>class BookController { |
| def scaffold = <span class="java-keyword">true</span> |
| }</pre></div><p class="paragraph"/>The above works because the <code>BookController</code> follows the same naming convention as the <code>Book</code> domain class, if we wanted to scaffold a specific domain class you can reference the class directly in the scaffold property:<p class="paragraph"/><div class="code"><pre>def scaffold = Author</pre></div><p class="paragraph"/>With that done if you run this grails application the necessary actions and views will be auto-generated at runtime. The following actions are dynamically implemented by default by the runtime scaffolding mechanism: |
| <ul class="star"> |
| <li>list</li> |
| <li>show</li> |
| <li>edit</li> |
| <li>delete</li> |
| <li>create</li> |
| <li>save</li> |
| <li>update</li> |
| </ul><p class="paragraph"/>As well as this a CRUD interface will be generated. To access the interface in the above example simply go to <code>http://localhost:8080/app/book</code><p class="paragraph"/>If you prefer to keep your domain model in Java and <a href="../guide/single.html#15. Grails and Hibernate" class="guide">mapped with Hibernate</a> you can still use scaffolding, simply import the necessary class and set the scaffold property to it.<p class="paragraph"/><h4>Dynamic Scaffolding</h4><p class="paragraph"/>Note that when using the scaffold property Grails does not use code templates, or code generation to achieve this so you can add your own actions to the scaffolded controller that interact with the scaffolded actions. For example, in the below example, <code>changeAuthor</code> redirects to the <code>show</code> action which doesn't actually exist physically:<p class="paragraph"/><div class="code"><pre>class BookController { |
| def scaffold = Book<p class="paragraph"/> def changeAuthor = { |
| def b = Book.get( params[<span class="java-quote">"id"</span>] ) |
| b.author = Author.get( params[<span class="java-quote">"author.id"</span>] ) |
| b.save()<p class="paragraph"/> // redirect to a scaffolded action |
| redirect(action:show) |
| } |
| }</pre></div><p class="paragraph"/>You can also override the scaffolded actions with your own actions if necessary:<p class="paragraph"/><div class="code"><pre>class BookController { |
| def scaffold = Book<p class="paragraph"/> // overrides scaffolded action to <span class="java-keyword">return</span> both authors and books |
| def list = { |
| [ <span class="java-quote">"books"</span> : Book.list(), <span class="java-quote">"authors"</span>: Author.list() ] |
| } |
| }</pre></div><p class="paragraph"/>All of this is what is known as "dynamic scaffolding" where the CRUD interface is generated dynamically at runtime. Grails also supports "static" scaffolding which will be discussed in the following sections.<p class="paragraph"/><h4>Customizing the Generated Views</h4><p class="paragraph"/>The views that Grails generates have some form of intelligence in that they adapt to the <a href="../guide/single.html#7.1 Declaring Constraints" class="guide">Validation constraints</a>. For example you can change the order that fields appear in the views simply by re-ordering the constraints in the builder:<p class="paragraph"/><div class="code"><pre>def constraints = { |
| title() |
| releaseDate() |
| }</pre></div><p class="paragraph"/>You can also get the generator to generate lists instead of text inputs if you use the <code>inList</code> constraint:<p class="paragraph"/><div class="code"><pre>def constraints = { |
| title() |
| category(inList:[<span class="java-quote">"Fiction"</span>, <span class="java-quote">"Non-fiction"</span>, <span class="java-quote">"Biography"</span>]) |
| releaseDate() |
| }</pre></div><p class="paragraph"/>Or if you use the <code>range</code> constraint on a number:<p class="paragraph"/><div class="code"><pre>def constraints = { |
| age(range:18..65) |
| }</pre></div><p class="paragraph"/>Restricting the size via a constraint also effects how many characters can be entered in the generated view:<p class="paragraph"/><div class="code"><pre>def constraints = { |
| name(size:0..30) |
| }</pre></div><p class="paragraph"/><h4>Generating Controllers & Views</h4><p class="paragraph"/>The above scaffolding features are useful but in real world situations its likely that you will want to customize the logic and views. Grails allows you to generate a controller and the views used to create the above interface via the command line. To generate a controller type:<p class="paragraph"/><div class="code"><pre>grails generate-controller Book</pre></div><p class="paragraph"/>Or to generate the views type:<p class="paragraph"/><div class="code"><pre>grails generate-views Book</pre></div><p class="paragraph"/>Or to generate everything type:<p class="paragraph"/><div class="code"><pre>grails generate-all Book</pre></div><p class="paragraph"/>If you have a domain class in a package or are generating from a <a href="../guide/single.html#15. Grails and Hibernate" class="guide">Hibernate mapped class</a> remember to include the fully qualified package name:<p class="paragraph"/><div class="code"><pre>grails generate-all com.bookstore.Book</pre></div><p class="paragraph"/><h4>Customizing the Scaffolding templates</h4><p class="paragraph"/>The templates used by Grails to generate the controller and views can be customized by installing the templates with the <a href="../ref/Command Line/install-templates.html" class="commandLine">install-templates</a> command.<h1><a name="17. Deployment">17. Deployment</a></h1>Grails applications can be deployed in a number of ways, each of which has its pros and cons.<p class="paragraph"/><h3>"grails run-app"</h3><p class="paragraph"/>You should be very familiar with this approach by now, since it is the most common method of running an application during the development phase. An embedded Tomcat server is launched that loads the web application from the development sources, thus allowing it to pick up an changes to application files.<p class="paragraph"/>This approach is not recommended at all for production deployment because the performance is poor. Checking for and loading changes places a sizable overhead on the server. Having said that, <code>grails prod run-app</code> removes the per-request overhead and allows you to fine tune how frequently the regular check takes place.<p class="paragraph"/>Setting the system property "disable.auto.recompile" to <code>true</code> disables this regular check completely, while the property "recompile.frequency" controls the frequency. This latter property should be set to the number of seconds you want between each check. The default is currently 3.<p class="paragraph"/><h3>"grails run-war"</h3><p class="paragraph"/>This is very similar to the previous option, but Tomcat runs against the packaged WAR file rather than the development sources. Hot-reloading is disabled, so you get good performance without the hassle of having to deploy the WAR file elsewhere.<p class="paragraph"/><h3>WAR file</h3><p class="paragraph"/>When it comes down to it, current java infrastructures almost mandate that web applications are deployed as WAR files, so this is by far the most common approach to Grails application deployment in production. Creating a WAR file is as simple as executing the <a href="../ref/Command Line/war.html" class="commandLine">war</a> command:<p class="paragraph"/><div class="code"><pre>grails war</pre></div><p class="paragraph"/>There are also many ways in which you can customise the WAR file that is created. For example, you can specify a path (either absolute or relative) to the command that instructs it where to place the file and what name to give it:<p class="paragraph"/><div class="code"><pre>grails war /opt/java/tomcat-5.5.24/foobar.war</pre></div><p class="paragraph"/>Alternatively, you can add a line to <code>grails-app/conf/BuildConfig.groovy</code> that changes the default location and filename:<p class="paragraph"/><div class="code"><pre>grails.project.war.file = <span class="java-quote">"foobar-prod.war"</span></pre></div><p class="paragraph"/>Of course, any command line argument that you provide overrides this setting.<p class="paragraph"/>It is also possible to control what libraries are included in the WAR file, in case you need to avoid conflicts with libraries in a shared folder for example. The default behavior is to include in the WAR file all libraries required by Grails, plus any libraries contained in plugin "lib" directories, plus any libraries contained in the application's "lib" directory. As an alternative to the default behavior you can explicitly specify the complete list of libraries to include in the WAR file by setting the properties <code>grails.war.dependencies</code> and <code>grails.war.java5.dependencies</code> in Config.groovy to either lists of Ant include patterns or closures containing AntBuilder syntax. Closures are invoked from within an Ant "copy" step, so only elements like "fileset" can be included, whereas each item in a pattern list is included. Any closure or pattern assigned to the latter property will be included in addition to <code>grails.war.dependencies</code> only if you are running JDK 1.5 or above.<p class="paragraph"/>Be careful with these properties: if any of the libraries Grails depends on are missing, the application will almost certainly fail. Here is an example that includes a small subset of the standard Grails dependencies:<p class="paragraph"/><div class="code"><pre>def deps = [ |
| <span class="java-quote">"hibernate3.jar"</span>, |
| <span class="java-quote">"groovy-all-*.jar"</span>, |
| <span class="java-quote">"standard-${servletVersion}.jar"</span>, |
| <span class="java-quote">"jstl-${servletVersion}.jar"</span>, |
| <span class="java-quote">"oscache-*.jar"</span>, |
| <span class="java-quote">"commons-logging-*.jar"</span>, |
| <span class="java-quote">"sitemesh-*.jar"</span>, |
| <span class="java-quote">"spring-*.jar"</span>, |
| <span class="java-quote">"log4j-*.jar"</span>, |
| <span class="java-quote">"ognl-*.jar"</span>, |
| <span class="java-quote">"commons-*.jar"</span>, |
| <span class="java-quote">"xstream-1.2.1.jar"</span>, |
| <span class="java-quote">"xpp3_min-1.1.3.4.O.jar"</span> ]<p class="paragraph"/>grails.war.dependencies = { |
| fileset(dir: <span class="java-quote">"libs"</span>) { |
| deps.each { pattern -> |
| include(name: pattern) |
| } |
| } |
| }</pre></div><p class="paragraph"/>This example only exists to demonstrate the syntax for the properties. If you attempt to use it as is in your own application, the application will probably not work. You can find a list of dependencies required by Grails in the "dependencies.txt" file that resides in the root directory of the unpacked distribution. You can also find a list of the default dependencies included in WAR generation in the "War.groovy" script - see the "DEFAULT_DEPS" and "DEFAULT_J5_DEPS" variables.<p class="paragraph"/>The remaining two configuration options available to you are <code>grails.war.copyToWebApp</code> and <code>grails.war.resources</code>. The first of these allows you to customise what files are included in the WAR file from the "web-app" directory. The second allows you to do any extra processing you want before the WAR file is finally created.<p class="paragraph"/><div class="code"><pre>// This closure is passed the command line arguments used to start the |
| // war process. |
| grails.war.copyToWebApp = { args -> |
| fileset(dir:<span class="java-quote">"web-app"</span>) { |
| include(name: <span class="java-quote">"js/**"</span>) |
| include(name: <span class="java-quote">"css/**"</span>) |
| include(name: <span class="java-quote">"WEB-INF/**"</span>) |
| } |
| }<p class="paragraph"/>// This closure is passed the location of the staging directory that |
| // is zipped up to make the WAR file, and the command line arguments. |
| // Here we override the standard web.xml with our own. |
| grails.war.resources = { stagingDir, args -> |
| copy(file: <span class="java-quote">"grails-app/conf/custom-web.xml"</span>, tofile: <span class="java-quote">"${stagingDir}/WEB-INF/web.xml"</span>) |
| }</pre></div><p class="paragraph"/><h2>Application servers</h2><p class="paragraph"/>Ideally you should be able to simply drop a WAR file created by Grails into any application server and it should work straight away. However, things are rarely ever this simple. The <a href="http://grails.org/Deployment" target="blank">Grails website</a> contains an up-to-date list of application servers that Grails has been tested with, along with any additional steps required to get a Grails WAR file working.<p class="paragraph"/> |
| </div> |
| <div id="footer"> |
| Sponsored by <a href="http://springsource.com">SpringSource</a> |
| </div> |
| </body> |
| </html> |