Add another edition? A quick-start guide to building assets in your prevention program Deborah Fisher. Want to Read. Are you sure you want to remove A quick-start guide to building assets in your prevention program from your list? Written in English. Subjects Services for , Social work with youth , Youth , Youth development. Places United States. Table of Contents Introduction : building the web of support all youth need Building assets works 40 Developmental assets : essentials for helping every young person succeed The power of assets Using the five action strategies to transform prevention programs Invigorate programs Engage adults Mobilize young people Activate sectors Influence civic decisions.
Classifications Dewey Decimal Class F The Physical Object Pagination p. Download for print-disabled. Check your local library WorldCat Library. Buy this book Amazon. Share this book Facebook. Edit Last edited by ImportBot April 6, History 1 edition of A quick-start guide to building assets in your prevention pr Some containers have bugs however, which in most cases can be worked around. A list of known deployment issues can be found on the Grails wiki.
In addition, reference the Grails Guides for tips on how to deploy Grails to various popular Cloud services. Grails ships with a few convenience targets such as create-controller , create-domain-class and so on that will create controllers and different artefact types for you.
For example to create the basis of an application you typically need a domain model :. To get started quickly with Grails it is often useful to use a feature called scaffolding to generate the skeleton of an application. If you were using GORM , you will need to update the version defined in gradle. Grails 4. See the migration guide and release notes if you are using Spring specific features. The details of these changes are covered in the GORM upgrade documentation.
What is Data Loss Prevention (DLP)? A Definition of Data Loss Prevention
Please check the Spring Boot Actuator documentation since it has changed substantially from Spring Boot 1. Previous versions of Grails used a reloading agent called Spring Loaded. Since this library is no longer maintained and does not support Java 11 support for Spring Loaded has been removed. As a replacement, Grails 4 applications include Spring Boot Developer Tools dependencies in the build. If you are migrating a Grails 3. Also you should configure the necessary excludes for Spring Developer Tools in application. The above configuration prevents the server from restarting when views or message bundles are changed.
Grails 4 apps are built on top of Spring Boot 2. Starting from Spring Boot 2. Instead, you need to set the sourceResources property to the source set that you want to use. The bootRepackage task has been replaced with bootJar and bootWar tasks for building executable jars and wars respectively. Both tasks extend their equivalent standard Gradle jar or war task, giving you access to all of the usual configuration options and behaviour.
Grails 3 apps by default used Gradle 3. Grails 4 apps use Gradle 5. Due to changes in Gradle 5, transitive dependencies are no longer resolved for plugins. If your project makes use of a plugin that has transitive dependencies, you will need to add those explicitly to your build. Please check Gradle Upgrading your build documentation. Spring Boot 2. Since this is already included in Spring Boot the equivalent feature has been removed from Grails.
Geb 1. Grails 4 is no longer compatible with Java 1.
Trends Driving DLP Policy Adoption
You should migrate to Geb 2. The following classes, which were deprecated in Grails 3. Please, check the list below to find a suitable replacement:. Use the org. MappingContext API instead. MappingContext and org. MappingFactory APIs instead. Use org. AbstractConstraint instead. For those who have added a dependency on the grails-java8 plugin, all you should need to do is simply remove the dependency. All of the classes in the plugin have been moved out to their respective projects. A few of the profiles supported in Grails 3.
When upgrading existing projects, it will be necessary to supply the version for these profiles. In Grails 3 no configuration or additional changes were necessary to use the Spring Scheduled annotation. In Grails 4 you must apply the EnableScheduling annotation to your application class in order for scheduling to work. It may seem odd that in a framework that embraces "convention-over-configuration" that we tackle this topic now. Later sections of the user guide will mention what configuration settings you can use, but not how to set them. The assumption is that you have at least read the first section of this chapter!
Configuration in Grails is generally split across 2 areas: build configuration and runtime configuration. Build configuration is generally done via Gradle and the build. If you prefer to use Grails 2. Use application. This separation is necessary because configuration values defined in application. References to application classes in application.
Location of the home directory for the account that is running the Grails application. Location of the directory where you installed Grails. If you want to read runtime configuration settings, i. The config property of the grailsApplication object is an instance of the Config interface and provides a number of useful methods to read the configuration of the application. Accessing configuration dynamically at runtime can have a small affect on application performance.
An alternative approach is to implement the GrailsConfigurationAware interface, which provides a setConfiguration method that accepts the application configuration as a parameter when the class is initialized. You can then assign relevant configuration properties to instance properties on the class for later usage. The Config instance has the same properties and usage as the injected GrailsApplication config object. Here is the service class from the previous example, using GrailsConfigurationAware instead of injecting GrailsApplication :.
As you can see, when accessing configuration settings you use the same dot notation as when you define them. The application. You will need to have this in build. Grails will read application. Grails has a set of core settings that are worth knowing about. On the runtime front, i. To reduce risk of XSS attacks, set this to 'html'. See createLink. Also used by redirects. Each directive takes a list of strings that are the class names for project source files that should be excluded from reloading behavior or included accordingly when running the application in development with the run-app command.
If the grails. By default logging in Grails 3. For more information on configuring logging refer to the Logback documentation on the subject. Prior to Grails 3. When Grails logs a stacktrace, the log message may include the names and values of all of the request parameters for the current request. To mask out the values of secure request parameters, specify the parameter names in the grails. Request parameter logging may be turned off altogether by setting the grails. If you set the configuration property logging.
ValidationException if validation 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 save method docs for more information. Firstly you need to configure the grails CLI to be aware of the proxy if you wish to use it to create applications and so on. With this configuration in place the grails command can connect and authenticate via a proxy. Secondly, since Grails uses Gradle as the build system, you need to configure Gradle to authenticate via the proxy. For instructions on how to do this see the Gradle user guide section on the topic. The Application class subclasses the GrailsAutoConfiguration class and features a static void main method, meaning it can be run as a regular application.
There are several ways to execute the Application class, if you are using an IDE then you can simply right click on the class and run it directly from your IDE which will start your Grails application. This is also useful for debugging since you can debug directly from the IDE without having to connect a remote debugger when using the run-app --debug-jvm command from the command line. By default Grails will scan all known source directories for controllers, domain class etc.
The Application class can also be used as a source for Spring bean definitions, simply define a method annotated with the Bean and the returned object will become a Spring bean. The name of the method is used as the bean name:. The Application class also implements the GrailsApplicationLifeCycle interface which all plugins implement. This means that the Application class can be used to perform the same functions as a plugin.
You can override the regular plugins hooks such as doWithSpring , doWithApplicationContext and so on by overriding the appropriate method:.
What is Data Loss Prevention (DLP)? | Digital Guardian
Grails supports the concept of per environment configuration. As an example consider the following default application. Notice how the common configuration is provided at the top level and then an environments block specifies per environment settings for the dbCreate and url properties of the DataSource. Grails' command line has built in capabilities to execute any command within the context of a specific environment. The format is:. In addition, there are 3 preset environments known to Grails: dev , prod , and test for development , production and test. For example to create a WAR for the test environment you would run:.
Within your code, such as in a Gant script or a bootstrap class you can detect the environment using the Environment class:. The previous BootStrap example uses the grails. Environment class internally to execute. You can also use this class yourself to execute your own environment specific logic:. Drivers typically come in the form of a JAR archive. Once you have the JAR resolved you need to get familiar with how Grails manages its database configuration.
These files contain the dataSource definition which includes the following settings:. See the org. This only applies to additional datasources. See the Tomcat Pool documentation. There is also a Javadoc format documentation of the properties. Hibernate can automatically create the database tables required for your domain model. You have some control over when and how it does this through the dbCreate property, which can take these values:.
Compares the configuration with the existing database schema and reports warnings. Setting the dbCreate setting to "none" is recommended once your schema is relatively stable and definitely when your application and database are deployed in production. Database changes are then managed through proper migrations, either with SQL scripts or a migration tool like Flyway or Liquibase. The Database Migration plugin uses Liquibase.
The previous example configuration assumes you want the same config for all environments: production, test, development etc. The dbCreate property of the DataSource definition is important as it dictates what Grails should do at runtime with regards to automatically generating the database tables from GORM classes. The options are described in the DataSource section:. The "real" unproxied dataSource is still available to you if you need access to it; its bean name is dataSourceUnproxied.
The URI can be configured using the grails. The console is enabled by default in development mode and can be disabled or enabled in other environments by using the grails. For example, you could enable the console in production like this:. MySQL, Oracle, etc. By default all domain classes share a single DataSource and a single database, but you have the option to partition your domain classes into two or more data sources. This configures a single DataSource with the Spring bean named dataSource. To configure extra data sources, add a dataSources block at the top level, in an environment block, or both, just like the standard DataSource definition with a custom name.
If you need to inject the lookup datasource in a Grails artefact, you can do it like this:. If a domain class has no DataSource configuration, it defaults to the standard 'dataSource'. Set the datasource property in the mapping block to configure a non-default DataSource. For example, if you want to use the ZipCode domain to use the 'lookup' DataSource , configure it like this:.
A domain class can also use two or more data sources. Use the datasources property with a list of names to configure more than one, for example:. For example, consider this class which uses two data sources:. The first DataSource specified is the default when not using an explicit namespace, so in this case we default to 'lookup'. As you can see, you add the DataSource to the method call in both the static case and the instance case. You can also partition annotated Java classes into separate datasources.
To specify that an annotated class uses a non-default datasource, create a hibernate. The process is the same for classes mapped with hbm. To configure a Service to use a different DataSource , use the static datasource property, for example:. A transactional service can only use a single DataSource , so be sure to only make changes for domain classes whose DataSource is the same as the Service.
If you have a Foo domain class in dataSource1 and a Bar domain class in dataSource2 , if WahooService uses dataSource1 , a service method that saves a new Foo and a new Bar will only be transactional for Foo since they share the same datasource. You can enable Grails to use the Best Effort 1PC pattern for handling transactions across multiple datasources. To do so you must set the grails. The Best Efforts 1PC pattern is fairly general but can fail in some circumstances that the developer must be aware of.
This is a non-XA pattern that involves a synchronized single-phase commit of a number of resources. Because the 2PC is not used, it can never be as safe as an XA transaction, but is often good enough if the participants are aware of the compromises. The basic idea is to delay the commit of all resources as late as possible in a transaction so that the only thing that can go wrong is an infrastructure failure not a business-processing error. Systems that rely on Best Efforts 1PC reason that infrastructure failures are rare enough that they can afford to take the risk in return for higher throughput.
If business-processing services are also designed to be idempotent, then little can go wrong in practice. The transactions in additional datasources were basically in auto commit mode. In some cases this might be the wanted behavior.
- Quick-Start Guide to Building Assets in Your Prevention Program.
- A Quick-Start Guide to Building Assets in Your Prevention Program by Deborah Fisher.
- The Grails Framework .
One reason might be performance: on the start of each new transaction, the BE1PC transaction manager creates a new transaction to each datasource. You can exclude transaction manager beans from the BE1PC implementation with this configuration option:. The exclude matching is done on the name of the transaction manager bean. In this case, you can configure a bean with the name transactionManager manually in resources. You can detect the application version using Grails' support for application metadata using the GrailsApplication class.
For example within controllers there is an implicit grailsApplication variable that can be used:. Dependency resolution is handled by the Gradle build tool , all dependencies are defined in the build. Refer to the Gradle user guide for more information. Grails 3. Grails searches the profile repository based on the profile of the current application.
If the profile is for a web application then commands are read from the web profile and the base profile which it inherits from. Since command behavior is profile specific the web profile may provide different behavior for the run-app command then say a profile for running batch applications. The grails command is a front to a gradle invocation, because of this there can be unexpected side-effects. For example, when executing grails -Dapp. This is because bootRun in your build. To make this work you can simply append all System. Or if you only want to pass through a limited set, you can prefix your system properties using an arbitrary prefix and configure bootRun like:.
When you run a script manually and it prompts you for information, you can answer the questions and continue running the script. Interactive mode is a feature of the Grails command line which keeps the JVM running and allows for quicker execution of commands. To activate interactive mode type 'grails' at the command line and then use TAB completion to get a list of commands:. If you need to open a file whilst within interactive mode you can use the open command which will TAB complete file paths:.
Even better, the open command understands the logical aliases 'test-report' and 'dep-report', which will open the most recent test and dependency reports respectively. In other words, to open the test report in a browser simply execute open test-report. If you need to run an external process whilst interactive mode is running you can do so by starting the command with a!
Note that with! To exit interactive mode enter the exit command. Note that if the Grails application has been run with run-app normally it will terminate when the interactive mode console exits because the JVM will be terminated. An exception to this would be if the application were running in forked mode which means the application is running in a different JVM.
In that case the application will be left running after the interactive mode console terminates. If you want to exit interactive mode and stop an application that is running in forked mode, use the quit command. The quit command will stop the running application and then close interactive mode. You can create your own Command scripts by running the create-script command from the root of your project.
The description method is used to define the output seen by grails help and to aid users of the script. The following is a more complete example of providing a description taken from the generate-all command:. As you can see this description profiles usage instructions, a flag and an argument. This allows the command to be used as follows:. Plugins and applications that need to define template generation tasks can do so using scripts.
A example of this is the Scaffolding plugin which defines the generate-all and generate-controllers commands. Every Grails script implements the TemplateRenderer interface which makes it trivial to render templates to the users project workspace. The following is an example of the create-script command written in Groovy:. If a script is defined in a plugin or profile, the template String method will search for the template in the application before using the template provided by your plugin or profile.
This allows users of your plugin or profile to customize what gets generated. It is common to provide an easy way to allow users to copy the templates from your plugin or profile. Here is one example on how the angular scaffolding copies templates. The model contains several properties that can help you generate code. In addition, an asMap method is available to turn all of the properties into a map to pass to the render method.
All scripts have access to methods on the FileSystemInteraction class. It contains helpful methods to copy, delete, and create files. You can create your own commands by running the create-command command from the root of your project. Since Grails 3. If you created a command in a previous version of grails, you can update your command to have those abilities by changing which trait you are implementing.
Commands created in Grails 3. Commands can also be executed using the runCommand gradle task. Note that the gradle task uses camelCase:. If the grails server is a subproject e. 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.
The above will invoke the test-app command. You can also pass arguments using the method arguments:. Instead of invoking another Grails CLI command you can invoke Gradle directory using the gradle property. You can also invoke Ant tasks from scripts which can help if you need to writing code generation and automation tasks:. It is recommended to use Gradle 2. The build is defined by the build. When you invoke the grails command the version of Gradle that ships with Grails 3.
You can invoke Gradle directly using the gradle command and use your own local version of Gradle, however you will need Gradle 2. Dependencies for your project are defined in the dependencies block. In general you can follow the Gradle documentation on dependency management to understand how to configure additional dependencies. Note that version numbers are not present in the majority of the dependencies.
This is thanks to the dependency management plugin which configures a Maven BOM that defines the default dependency versions for certain commonly used dependencies and plugins:. As mentioned previously the grails command uses an embedded version of Gradle and certain Grails commands that existed in previous versions of Grails map onto their Gradle equivalents. The following table shows which Grails command invoke which Gradle task:. Note however that you will need to use a version of Gradle compatible with Grails 3.
If you wish to invoke a Gradle task using the version of Gradle used by Grails you can do so with the grails command:. However, it is recommended you do this via interactive mode, as it greatly speeds up execution and provides TAB completion for the available Gradle tasks:. To find out what Gradle tasks are available without using interactive mode TAB completion you can use the Gradle tasks task:. When you create a new project with the create-app command, a default build. The default build. You can comment out this plugin if you wish to create only a runnable JAR file for standalone deployment.
Many of these are built in plugins provided by Gradle or third party plugins. The Gradle plugins that Grails provides are as follows:. When you create a Grails application with the create-app command by default the "web" profile is used:. Profiles encapsulate the project commands, templates and plugins that are designed to work for a given profile.
- Scattering theory for automorphic functions?
- Constitutional Design for Divided Societies: Integration or Accommodation?.
- Empower Your Content Team!
- Product description.
The source for the profiles can be found on Github , whilst the profiles themselves are published as JAR files to the Grails central repository. To find out what profiles are available use the list-profiles command:. For more information on a particular profile use the profile-info command:. By default Grails will resolve profiles from the Grails central repository. If you want profiles to be resolved with a custom repository in addition to the Grails central repository, you must specify Grails central in the file as well:. With the default values specified, the command to create an application using that profile becomes:.
The idea behind creating a new profile is that you can setup a default set of commands and plugins that are tailored to a particular technology or organisation. To create a new profile you can use the create-profile command which will create a new empty profile that extends the base profile:. The above command will create a new profile in the "mycompany" directory where the command is executed.
If you start interactive mode within the directory you will get a set of commands for creating profiles:. To customize the dependencies for your profile you can specify additional dependencies in profile. With the above configuration in place you can publish the profile to your local repository with gradle install :.
With the above command the application will be created with the "mycompany" profile which includes an additional dependency on the "myplugin" plugin and also includes the "hibernate" and "asset-pipeline" features more on features later. Note that if you customize the dependency coordinates of the profile group, version etc. One profile can extend one or many different parent profiles. To define profile inheritance you can modify the build. For example typically you want to extend the base profile:.
To define the order of inheritance ensure that your dependencies are declared in the correct order. For example:. In the above snippet the skeleton from the "plugin" profile is copied first, followed by the "web" profile. In addition, the "web" profile overrides commands from the "plugin" profile, whilst if the dependency order was reversed the "plugin" profile would override the "web" profile.
Any profile created with the create-profile command already comes configured with a grails-profile-publish plugin defined in build. To publish a profile using this plugin to the Grails central repository first upload the source to Github closed source profiles will not be accepted. The profile will be uploaded to Bintray. In order to publish to an internal repository all you need to do is define the repository in build. A profile is a simple directory that contains a profile. The above example is a snippet of structure of the 'web' profile.
The profile. A list of Maven repositories to include in the buildscript section of the generated build. A map of scopes and dependencies to configure. The excludes scope can be used to exclude from the parent profile. This can be used to create multi-project builds. Which file extensions should be copied from the profile as binary. Inherited and combined from parent profiles. File patterns that should be marked as executable in the resulting application. The patterns are parsed with Ant. When the create-app command runs it takes the skeleton of the parent profiles and copies the skeletons into a new project structure.
The build. The command will also merge any build. Below is an example of the create-controller command defined in YAML:. Commands defined in YAML must define one or many steps. Each step is a command in itself. The available step types are:. Must be a class that implements the Command interface. If you need more flexiblity than what the declarative YAML approach provides you can create Groovy script commands.
Each Command script is extends from the GroovyScriptCommmand class and hence has all of the methods of that class available to it. For more information on creating CLI commands see the section on creating custom scripts in the Command Line section of the user guide. A Profile feature is a shareable set of templates and dependencies that may span multiple profiles. Typically you create a base profile that has multiple features and child profiles that inherit from the parent and hence can use the features available from the parent.
To create a feature use the create-feature command from the root directory of your profile:. As a more concrete example. The following is the feature. The contents of the skeleton get copied into the application tree, whilst the application. With the feature. This allows users to create applications with optional features. The above example will create a new application using your new feature and the "hibernate" feature.
Domain classes are core to any business application. They hold state about business processes and hopefully also implement behavior. They are linked together through relationships; one-to-one, one-to-many, or many-to-many. Under the hood it uses Hibernate a very popular and flexible open source ORM solution and thanks to the dynamic nature of Groovy with its static and dynamic typing, along with the convention of Grails, there is far less configuration involved in creating Grails domain classes.
You can also write Grails domain classes in Java. See the section on Hibernate Integration for how to write domain classes in Java but still use dynamic persistent methods. Below is a preview of GORM in action:. A domain class can be created with the create-domain-class command:. Once you have a domain class try and manipulate it with the shell or console by typing:. To create a domain class use Map constructor to set its properties and call save :. The save method will persist your class to the database using the underlying Hibernate ORM layer. Grails transparently adds an implicit id property to your domain class which you can use for retrieval:.
This uses the get method that expects a database identifier to read the Person object back from the database. You can also load an object in a read-only state by using the read method:. 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 save method then the object is placed back into a read-write state. In addition, you can also load a proxy for an instance by using the load method:. 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. To update an instance, change some properties and then call save again:. A controller handles requests and creates or prepares the response. A controller can generate the response directly or delegate to a view. Controllers can be created with the create-controller or generate-controller command. For example try running the following command from the root of a Grails project:. The action that is called when the default URI is requested is dictated by the following rules:.
Scopes are hash-like objects where you can store variables. The following scopes are available to controllers:. The servletContext is an instance of ServletContext. The session object is an instance of HttpSession. The request object is an instance of HttpServletRequest. You can also access values within scopes using the de-reference operator, making the syntax even more clear:.
Grails supports the concept of flash scope as a temporary store to make attributes available for this request and the next request only. Afterwards the attributes are cleared. This is useful for setting a message directly before redirecting, for example:. When the delete action is requested, the message value will be in scope and can be used to display an information message.
It will be removed from the flash scope after this second request. Note that the attribute name can be anything you want, and the values are often strings used to display messages, but can be any object type. Newly created applications have the grails. You may change this value to any of the supported scopes listed below.
If the property is not assigned a value at all, controllers will default to "prototype" scope. To enable one of the scopes, add a static scope property to your class with one of the valid scope values listed above, for example. You can define the default strategy in application.
A model is a Map that the view uses when rendering. The keys within that Map correspond to variable names accessible by the view. There are a couple of ways to return a model. First, you can explicitly return a Map instance:. A more advanced approach is to return an instance of the Spring ModelAndView class:. Currently, no error will be reported if you do use them, but this will hopefully change in a future version of Grails.
In both of the previous two examples there was no code that specified which view to render. So how does Grails know which one to pick? The answer lies in the conventions. This is convenient, but to access shared views, you use an absolute path instead of a relative one:.
See a Problem?
If a controller defines a namespace for itself with the namespace property that will affect the root directory in which Grails will look for views which are specified with a relative path. If the view is not found in the namespaced directory then Grails will fallback to looking for the view in the non-namespaced directory. For this, the highly flexible render method can be used:.
This will actually call the form tag which will return some text that will be ignored by the MarkupBuilder. Actions can be redirected using the redirect controller method:. In the above example Grails will construct a link using the domain class id if present. Parameters can optionally be passed from one action to the next using the params argument of the method:. These parameters are made available through the params dynamic property that accesses request parameters. If a parameter is specified with the same name as a request parameter, the request parameter is overridden and the controller parameter is used.
Since the params object is a Map, you can use it to pass the current request parameters from one action to the next:. Actions can also be chained. Chaining allows the model to be retained from one action to the next. For example calling the first action in this action:. The model can be accessed in subsequent controller actions in the chain using the chainModel map. This dynamic property only exists in actions following the call to the chain method:. Like the redirect method you can also pass parameters to the chain method:. Data binding is the act of "binding" incoming request parameters onto the properties of an object or an entire graph of objects.
Data binding should deal with all necessary type conversion since request parameters, which are typically delivered by a form submission, are always strings whilst the properties of a Groovy or Java object may well not be. The data binder is capable of converting and assigning values in a Map to properties of an object. The binder will associate entries in the Map to properties of the object using the keys in the Map that have values which correspond to property names on the object.
The following code demonstrates the basics:. To update properties of a domain object you may assign a Map to the properties property of the domain class:. The data binder can populate and update Collections and Maps. The following code shows a simple example of populating a List of objects in a domain class:.
That code would work in the same way if albums were an array instead of a List. In the code example above, if albums were a Set instead of a List , the bindingMap could look exactly the same but 'Foxtrot' might be the first album in the Set or it might be the second. When updating existing elements in a Set the Map being assigned to the Set must have id elements in it which represent the element in the Set being updated, as in the following example:.
When binding to a Map the structure of the binding Map is the same as the structure of a Map used for binding to a List or a Set and the index inside of square brackets corresponds to the key in the Map being bound to. See the following code:. When updating an existing Map , if the key specified in the binding Map does not exist in the Map being bound to then a new value will be created and added to the Map with the specified key as in the following example:.
The params object that is available in a controller has special behavior that helps convert dotted request parameter names into nested Maps that the data binder can work with. For example, if a request includes request parameters named person. Louis' respectively, params would include entries like these:.
There are two ways to bind request parameters onto the properties of a domain class. The first involves using a domain classes' Map constructor:. The data binding happens within the code new Book params. By passing the params 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:. Then the title and author request parameters would automatically be set on the domain class. You can use the properties property to perform data binding onto an existing instance:. When binding an empty String a String with no characters in it, not even spaces , the data binder will convert the empty String to null. When this behavior is not desirable the application may assign the value directly. The mass property binding mechanism will by default automatically trim all Strings at binding time. To disable this behavior set the grails.
The mass property binding mechanism will by default automatically convert all empty Strings to null at binding time. The order of events is that the String trimming happens and then null conversion happens so if trimStrings is true and convertEmptyStringsToNull is true , not only will empty Strings be converted to null but also blank Strings.
A blank String is any String such that the trim method returns an empty String. If you have a one-to-one or many-to-one association you can use Grails' data binding capability to update these relationships too. For example if you have an incoming request such as:. Grails will automatically detect the. An association property can be set to null by passing the literal String "null".
If you have a one-to-many or many-to-many association there are different techniques for data binding depending of the association type. If you have a Set based association the default for a hasMany then the simplest way to populate an association is to send a list of identifiers. This produces a select box that lets you select multiple values. In this case if you submit the form Grails will automatically use the identifiers from the select box to populate the books association.
Instead you use the subscript operator:. However, with Set 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 not a problem if you use List based associations, since a List has a defined order and an index you can refer to. This is also true of Map based associations. Note also that if the association you are binding to has a size of two and you refer to an element that is outside the size of association:.
You can bind existing instances of the associated type to a List using the same. Will render a select box that will remove the association at books if the empty option is chosen. Binding to a Map property works the same way except that the list index in the parameter name is replaced by the map key:. This would bind the selected image into the Map property images under a key of "cover".
When binding to Maps, Arrays and Collections the data binder will automatically grow the size of the collections as necessary. It is possible to bind data to multiple domain objects from the params object. Grails' params object is like a multi-dimensional hash and you can index into it to isolate only a subset of the parameters to bind.
Notice how we use the prefix before the first dot of the book. We could do the same with an Author domain class:. Controller action arguments are subject to request parameter data binding. There are 2 categories of controller action arguments. The first category is command objects. Complex types are treated as command objects. See the Command Objects section of the user guide for details. The other category is basic object types.
Supported types are the 8 primitives, their corresponding type wrappers and java. The default behavior is to map request parameters to action arguments by name:. For primitive arguments and arguments which are instances of any of the primitive type wrapper classes a type conversion has to be carried out before the request parameter value can be bound to the action argument. The type conversion happens automatically.
In a case like the example shown above, the params. If type conversion fails for any reason, the argument will have its default value per normal Java behavior null for type wrapper references, false for booleans and zero for numbers and a corresponding error will be added to the errors property of the defining controller. If the argument name does not match the name of the request parameter then the grails. RequestParameter annotation may be applied to an argument to express the name of the request parameter which should be bound to that argument:.
Sometimes when performing data binding it is not possible to convert a particular String into a particular target type. This results in a type conversion error. Grails will retain type conversion errors inside the errors property of a Grails domain class. Here we have a domain class Book that uses the java. Given an incoming request such as:. You can check for these like this:. You can use a generic error message handler such as:.
The BindUsing annotation may be used to define a custom binding mechanism for a particular field in a class. Any time data binding is being applied to the field the closure value of the annotation will be invoked with 2 arguments. The first argument is the object that data binding is being applied to and the second argument is DataBindingSource which is the data source for the data binding.
The value returned from the closure will be bound to the property. The following example would result in the upper case version of the name value in the source being applied to the name field during data binding. The BindUsing annotation may be used to define a custom binding mechanism for all of the fields on a particular class.
When the annotation is applied to a class, the value assigned to the annotation should be a class which implements the BindingHelper interface. An instance of that class will be used any time a value is bound to a property in the class that this annotation has been applied to. The BindInitializer annotation may be used to initialize an associated field in a class if it is undefined. Unlike the BindUsing annotation, databinding will continue binding all nested properties on this association. The binder will do a lot of type conversion automatically.
Some applications may want to define their own mechanism for converting values and a simple way to do this is to write a class which implements ValueConverter and register an instance of that class as a bean in the Spring application context. An instance of that class needs to be registered as a bean in the Spring application context. The bean name is not important. All beans that implemented ValueConverter will be automatically plugged in to the data binding process. A custom date format may be specified to be used when binding a String to a Date value by applying the BindingFormat annotation to a Date field.
A global setting may be configured in application.
The formats specified in grails. If a property is marked with BindingFormat , the BindingFormat will take precedence over the values specified in grails. You may supply your own handler for the BindingFormat annotation by writing a class which implements the FormattedValueConverter interface and registering an instance of that class as a bean in the Spring application context. Below is an example of a trivial custom String formatter that might convert the case of a String based on the value assigned to the BindingFormat annotation.
All beans that implemented FormattedValueConverter will be automatically plugged in to the data binding process. With that in place the BindingFormat annotation may be applied to String fields to inform the data binder to take advantage of the custom converter. The BindingFormat annotation supports localized format strings by using the optional code attribute. If a value is assigned to the code attribute that value will be used as the message code to retrieve the binding format string from the messageSource bean in the Spring application context and that lookup will be localized.
A structured data binding editor is a helper class which can bind structured request parameters to a property. The structured editor would retrieve all of those individual pieces of information and use them to construct a Date. The framework provides a structured editor for binding to Date objects.
An application may register its own structured editors for whatever types are appropriate. Consider the following classes:. A Gadget has 2 Shape fields. A Shape has an area property. It may be that the application wants to accept request parameters like width and height and use those to calculate the area of a Shape at binding time.
A structured binding editor is well suited for that. The way to register a structured editor with the data binding process is to add an instance of the grails. TypedStructuredBindingEditor interface to the Spring application context. The easiest way to implement the TypedStructuredBindingEditor interface is to extend the org. AbstractStructuredBindingEditor abstract class and override the getPropertyValue method as shown below:. When the data binder binds to an instance of the Gadget class it will check to see if there are request parameters with names compressedShape and expandedShape which have a value of "struct" and if they do exist, that will trigger the use of the StructuredShapeEditor.
Typically the request parameters with "struct" as their value would be represented by hidden form fields. The DataBindingListener interface provides a mechanism for listeners to be notified of data binding events. The interface looks like this:. Any bean in the Spring application context which implements that interface will automatically be registered with the data binder. The DataBindingListenerAdapter class implements the DataBindingListener interface and provides default implementations for all of the methods in the interface so this class is well suited for subclassing so your listener class only needs to provide implementations for the methods your listener is interested in.
There are situations where an application may want to use the data binder directly. For example, to do binding in a Service on some arbitrary object which is not a domain class. The following will not work because the properties property is read only. An instance of the data binder is in the Spring application context with a bean name of grailsWebDataBinder.
That bean implements the DataBinder interface. The following code demonstrates using the data binder directly. See the DataBinder documentation for more information about overloaded versions of the bind method. When batch updating properties from request parameters you need to be careful not to allow clients to bind malicious data to domain classes and be persisted in the database.
You can limit what properties are bound to a given domain class using the subscript operator:. Another way to do this is is to use Command Objects as the target of data binding instead of domain classes. Alternatively there is also the flexible bindData method. The bindData method allows the same data binding capability, but to arbitrary objects:.
The bindable constraint can be used to globally prevent data binding for certain properties. The respond method provides content negotiation strategies to intelligently produce an appropriate response for the given client. The respond method will then look for an appriopriate Renderer for the object and the calculated media type from the RendererRegistry.
Grails includes a number of pre-configured Renderer implementations that will produce default representations of JSON responses for the argument passed to respond. By default if you define a controller there is no priority in terms of which format is sent back to the client and Grails assumes you wish to serve HTML as a response type.
However if your application is primarily an API, then you can specify the priorty using the responseFormats property:.