Geeks With Blogs
Zakaria's Blog
Redirects and Chaining
Redirects
Actions can be redirected using the redirect controller method :
 class OverviewController {  
 def login() {}  
 def find() {  
 	if (!session.user)  
 	redirect(action: 'login')  
 	return  
       }  
 …  
  }  
 }  
Internally the redirect method uses the HttpServletResponse object's sendRedirect method.
The redirect method expects one of :
  • Another closure within the same controller class :
 // Call the login action within the same class  
 redirect(action: login)  
  • The name of an action (and controller name if the redirect isn't to an action in the current controller) :
 // Also redirects to the index action in the home controller  
 redirect(controller: 'home', action: 'index')  
  • A URI for a resource relative the application context path :
 // Redirect to an explicit URI  
 redirect(uri: "/login.html")  
  • Or a full URL :
 // Redirect to a URL  
 redirect(url: "http://grails.org")  
Parameters can optionally be passed from one action to the next using the params argument of the method :
 redirect(action: 'myaction', params: [myparam: "myvalue"])  
These parameters are made available through the params dynamic property that accesses request parameters. specified with the same name as a request parameter, the request parameter is overridden and the controller parameter Since the params object is a Map, you can use it to pass the current request parameters from one action to the
 redirect(action: "next", params: params)  
Finally, you can also include a fragment in the target URI :
 redirect(controller: "test", action: "show", fragment: "profile")  
which will (depending on the URL mappings) redirect to something like "/myapp/test/show#profile".
Chaining
Actions can also be chained. Chaining allows the model to be retained from one action to the next. For example calling action in this action :
 class ExampleChainController {  
 def first() {  
 chain(action: second, model: [one: 1])  
 }  
 def second () {  
 chain(action: third, model: [two: 2])  
 }  
 def third() {  
 [three: 3])  
 }  
 }  
results in the model :
 [one: 1, two: 2, three: 3]  
The model can be accessed in subsequent controller actions in the chain using the map. This dynamic chainModel exists in actions following the call to the chain method:
 class ChainController {  
 def nextInChain() {  
 def model = chainModel.myModel  
 …  
 }  
 }  
Like the redirect method you can also pass parameters to the chain method :
 chain(action: "action1", model: [one: 1], params: [myparam: "param1"])  
Controller Interceptors
Often it is useful to intercept processing based on either request, session or application state. This can be achieved interceptors. There are currently two types of interceptors: before and after.
Before Interception
The beforeInterceptor intercepts processing before the action is executed. If it returns false then the intercepted will not be executed. The interceptor can be defined for all actions in a controller as follows :
 def beforeInterceptor = {  
 println "Tracing action ${actionUri}"  
 }  
The above is declared inside the body of the controller definition. It will be executed before all actions and does processing. A common use case is very simplistic authentication :
 def beforeInterceptor = [action: this.&auth, except: 'login']  
 // defined with private scope, so it's not considered an action  
 private auth() {  
 if (!session.user) {  
 redirect(action: 'login')  
 return false  
 }  
 }  
 def login() {  
 // display login page  
 }  
The above code defines a method called auth. A private method is used so that it is not exposed as an action to the The beforeInterceptor then defines an interceptor that is used on all actions except the login action and it executes method. The auth method is referenced using Groovy's method pointer syntax. Within the method it detects whether user in the session, and if not it redirects to the login action and returns false, causing the intercepted processed.
After Interception
Use the afterInterceptor property to define an interceptor that is executed after an action :
 def afterInterceptor = { model ->  
 println "Tracing action ${actionUri}"  
 }  
The after interceptor takes the resulting model as an argument and can hence manipulate the model or response.
An after interceptor may also modify the Spring MVC object prior to rendering. In this case, ModelAndView the becomes :
 def afterInterceptor = { model, modelAndView ->  
 println "Current view is ${modelAndView.viewName}"  
 if (model.someVar) modelAndView.viewName = "/mycontroller/someotherview"  
 println "View is now ${modelAndView.viewName}"  
 }  
This allows the view to be changed based on the model returned by the current action. Note that the modelAndView null if the action being intercepted called redirect or render.
Interception Conditions
Rails users will be familiar with the authentication example and how the 'except' condition was used when executing (interceptors are called 'filters' in Rails; this terminology conflicts with Servlet filter terminology in Java) :
 def beforeInterceptor = [action: this.&auth, except: 'login']  
This executes the interceptor for all actions except the specified action. A list of actions can also be defined as follows
 def beforeInterceptor = [action: this.&auth, except: ['login', 'register']]  
The other supported condition is 'only', this executes the interceptor for only the specified action(s) :
 def beforeInterceptor = [action: this.&auth, only: ['secure']]  
Data Binding
Data binding is the act of "binding" incoming request parameters onto the properties of an object or an entire graph binding should deal with all necessary type conversion since request parameters, which are typically delivered submission, are always strings whilst the properties of a Groovy or Java object may well not be.
Map Based Binding
The data binder is capable of converting and assigning values in a Map to properties of an object. The binder will in the Map to properties of the object using the keys in the Map that have values which correspond to property names The following code demonstrates the basics :
 // grails-app/domain/Person.groovy  
 class Person {  
 String firstName  
 String lastName  
 Integer age  
 }  
 def bindingMap = [firstName: 'Peter', lastName: 'Gabriel', age: 63]  
 def person = new Person(bindingMap)  
 assert person.firstName == 'Peter'  
 assert person.lastName == 'Gabriel'  
 assert person.age == 63  
To update properties of a domain object you may assign a Map to the properties property of the domain class
 def bindingMap = [firstName: 'Peter', lastName: 'Gabriel', age: 63]  
 def person = Person.get(someId)  
 person.properties = bindingMap  
 assert person.firstName == 'Peter'  
 assert person.lastName == 'Gabriel'  
 assert person.age == 63  
The binder can populate a full graph of objects using Maps of Maps.
 class Person {  
 String firstName  
 String lastName  
 Integer age  
 Address homeAddress  
 }  
 class Address {  
 String county  
 String country  
 }  
 def bindingMap = [firstName: 'Peter', lastName: 'Gabriel', age: 63, homeAddress: [county: country: 'England'] ]  
 def person = new Person(bindingMap)  
 assert person.firstName == 'Peter'  
 assert person.lastName == 'Gabriel'  
 assert person.age == 63  
 assert person.homeAddress.county == 'Surrey'  
 assert person.homeAddress.country == 'England'  
Binding To Collections And Maps
The data binder can populate and update Collections and Maps. The following code shows a simple example of populating of objects in a domain class :
 class Band {  
 String name  
 static hasMany = [albums: Album]  
 List albums  
 }  
 class Album {  
 String title  
 Integer numberOfTracks  
 }  
 def bindingMap = [name: 'Genesis',  
 'albums[0]': [title: 'Foxtrot', numberOfTracks: 6],  
 'albums[1]': [title: 'Nursery Cryme', numberOfTracks: 7]]  
 def band = new Band(bindingMap)  
 assert band.name == 'Genesis'  
 assert band.albums.size() == 2  
 assert band.albums[0].title == 'Foxtrot'  
 assert band.albums[0].numberOfTracks == 6  
 assert band.albums[1].title == 'Nursery Cryme'  
 assert band.albums[1].numberOfTracks == 7  
That code would work in the same way if albums were an array instead of a List.
Note that when binding to a Set the structure of the Map being bound to the Set is the same as that of a Map List but since a Set is unordered, the indexes don't necessarily correspond to the order of elements in the example above, if albums were a Set instead of a List, the bindingMap could look exactly the same but 'the first album in the Set or it might be the second. When updating existing elements in a Set the Map being assigned must have id elements in it which represent the element in the Set being updated, as in the following example :
 /*  
 * The value of the indexes 0 and 1 in albums[0] and albums[1] are arbitrary  
 * values that can be anything as long as they are unique within the Map.  
 * They do not correspond to the order of elements in albums because albums  
 * is a Set.  
 */  
 def bindingMap = ['albums[0]': [id: 9, title: 'The Lamb Lies Down On Broadway']  
 'albums[1]': [id: 4, title: 'Selling England By The Pound']]  
 def band = Band.get(someBandId)  
 /*  
 * This will find the Album in albums that has an id of 9 and will set its title  
 * to 'The Lamb Lies Down On Broadway' and will find the Album in albums that has  
 * an id of 4 and set its title to 'Selling England By The Pound'. In both  
 * cases if the Album cannot be found in albums then the album will be retrieved  
 * from the database by id, the Album will be added to albums and will be updated  
 * with the values described above. If a Album with the specified id cannot be  
 * found in the database, then a binding error will be created and associated  
 * with the band object. More on binding errors later.  
 */  
 band.properties = bindingMap  
When binding to a Map the structure of the binding Map is the same as the structore of a Map used for binding to and the index inside of square brackets corresponds to the key in the Map being bound to. See the following code
 class Album {  
 String title  
 static hasMany = [players: Player]  
 Map players  
 }  
 class Player {  
 String name  
 }  
 def bindingMap = [title: 'The Lamb Lies Down On Broadway',  
 'players[guitar]': [name: 'Steve Hackett'],  
 'players[vocals]': [name: 'Peter Gabriel'],  
 'players[keyboards]': [name: 'Tony Banks']]  
 def album = new Album(bindingMap)  
 assert album.title == 'The Lamb Lies Down On Broadway'  
 assert album.players.size() == 3  
 assert album.players.guitar.name == 'Steve Hackett'  
 assert album.players.vocals.name == 'Peter Gabriel'  
 assert album.players.keyboards.name == 'Tony Banks'  
When updating an exisiting , if the key specified in the binding does not exist in the being bound Map Map Map to will be created and added to the Map with the specified key as in the following example :
 def bindingMap = [title: 'The Lamb Lies Down On Broadway',  
 'players[guitar]': [name: 'Steve Hackett'],  
 'players[vocals]': [name: 'Peter Gabriel']  
 'players[keyboards]': [name: 'Tony Banks']]  
 def album = new Album(bindingMap)  
 assert album.title == 'The Lamb Lies Down On Broadway'  
 assert album.players.size() == 3  
 assert album.players.guitar == 'Steve Hackett'  
 assert album.players.vocals == 'Peter Gabriel'  
 assert album.players.keyboards == 'Tony Banks'  
 def updatedBindingMap = ['players[drums]': [name: 'Phil Collins'],  
 'players[keyboards]': [name: 'Anthony George Banks']]  
 album.properties = updatedBindingMap  
 assert album.title == 'The Lamb Lies Down On Broadway'  
 assert album.players.size() == 4  
 assert album.players.guitar == 'Steve Hackett'  
 assert album.players.vocals == 'Peter Gabriel'  
 assert album.players.keyboards == 'Anthony George Banks'  
 assert album.players.drums == 'Phil Collins'  
Binding Request Data to the Model
The params object that is available in a controller has special behavior that helps convert dotted request parameter nested Maps that the data binder can work with. For example, if a request includes request parameters person.homeAddress.country and person.homeAddress.city with values 'USA' and 'St. Louis' params would include entries like these :
 [person: [homeAddress: [country: 'USA', city: 'St. Louis']]]  
There are two ways to bind request parameters onto the properties of a domain class. The first involves using Map constructor :
 def save() {  
 def b = new Book(params)  
 b.save()  
 }  
The data binding happens within the code . By passing the object to the domain new Book(params) params Grails automatically recognizes that you are trying to bind from request parameters. So if we had an incoming
 /book/save?title=The%20Stand&author=Stephen%20King  
Then the title and author request parameters would automatically be set on the domain class. You can use property to perform data binding onto an existing instance :
 def save() {  
 def b = Book.get(params.id)  
 b.properties = params  
 b.save()  
 }  
This has the same effect as using the implicit constructor.
When binding an empty String (a String with no characters in it, not even spaces), the data binder will convert the null. This simplifies the most common case where the intent is to treat an empty form field as having the value null a way to actually submit a null as a request parameter. When this behavior is not desireable the application may directly.
The mass property binding mechanism will by default automatically trim all Strings at binding time. To disable the grails.databinding.trimStrings property to false in grails-app/conf/Config.groovy
 // the default value is true  
 grails.databinding.trimStrings = false  
 // ...  
The mass property binding mechanism will by default automatically convert all empty Strings to null at binding this behavior set the grails.databinding.convertEmptyStringsToNull property grials-app/conf/Config.groovy.
 // the default value is true  
 grails.databinding.convertEmptyStringsToNull = false  
 // ...  
The order of events is that the String trimming happens and then null conversion happens so if trimStrings convertEmptyStringsToNull is true, not only will empty Strings be converted to null but also blank String is any String such that the trim() method returns an empty String.
Data binding and Single-ended Associations
If you have a one-to-one or many-to-one association you can use Grails' data binding capability relationships too. For example if you have an incoming request such as :
 /book/save?author.id=20  
Grails will automatically detect the .id suffix on the request parameter and look up the Author instance for the doing data binding such as :
 def b = new Book(params)  
An association property can be set to null by passing the literal String "null". For example :
 /book/save?author.id=null  
Data Binding and Many-ended Associations
If you have a one-to-many or many-to-many association there are different techniques for data binding depending type.
If you have a based association (the default for a ) then the simplest way to populate an association Set hasMany of identifiers. For example consider the usage of <g:select> below :
 <g:select name="books"  
 from="${Book.list()}"  
 size="5" multiple="yes" optionKey="id"  
 value="${author?.books}" />  
This produces a select box that lets you select multiple values. In this case if you submit the form Grails will automatically identifiers from the select box to populate the books association. However, if you have a scenario where you want to update the properties of the associated objects the this technique Instead you use the subscript operator :
 <g:textField name="books[0].title" value="the Stand" />  
 <g:textField name="books[1].title" value="the Shining" />  
However, with Set based association it is critical that you render the mark-up in the same order that you plan to This is because a Set has no concept of order, so although we're referring to books0 and books1 it is not guaranteed order of the association will be correct on the server side unless you apply some explicit sorting yourself.
This is not a problem if you use List based associations, since a List has a defined order and an index you can 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 association :
 <g:textField name="books[0].title" value="the Stand" />  
 <g:textField name="books[1].title" value="the Shining" />  
 <g:textField name="books[2].title" value="Red Madder" />  
Then Grails will automatically create a new instance for you at the defined position.
You can bind existing instances of the associated type to a using the same syntax as you would use List .id with association. For example :
 <g:select name="books[0].id" from="${bookList}"  
 value="${author?.books[0]?.id}" />  
 <g:select name="books[1].id" from="${bookList}"  
 value="${author?.books[1]?.id}" />  
 <g:select name="books[2].id" from="${bookList}"  
 value="${author?.books[2]?.id}" />  
Would allow individual entries in the books List to be selected separately.
Entries at particular indexes can be removed in the same way too. For example :
 <g:select name="books[0].id"  
 from="${Book.list()}"  
 value="${author?.books[0]?.id}"  
 noSelection="['null': '']"/>  
Will render a select box that will remove the association at books0 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
 <g:select name="images[cover].id"  
 from="${Image.list()}"  
 value="${book?.images[cover]?.id}"  
 noSelection="['null': '']"/>  
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 default limit to how large the binder will grow a collection is 256. If the data binder encounters an entry that requires be grown beyond that limit, the entry is ignored. The limit may be configured by assigning a grails.databinding.autoGrowCollectionLimit property in Config.groovy.
 // grails-app/conf/Config.groovy  
 // the default value is 256  
 grails.databinding.autoGrowCollectionLimit = 128  
 // ...  
Data binding with Multiple domain classes
It is possible to bind data to multiple domain objects from the params object.
For example so you have an incoming request to :
 /book/save?book.title=The%20Stand&author.name=Stephen%20King  
You'll notice the difference with the above request is that each parameter has a prefix such as author. or book. isolate which parameters belong to which type. Grails' params object is like a multi-dimensional hash and you can isolate only a subset of the parameters to bind.
 def b = new Book(params.book)  
Notice how we use the prefix before the first dot of the book.title parameter to isolate only parameters below bind. We could do the same with an Author domain class :
 def a = new Author(params.author)  
Data Binding and Action Arguments
Controller action arguments are subject to request parameter data binding. There are 2 categories of controller action The first category is command objects. Complex types are treated as command objects. See the Command Objects user guide for details. The other category is basic object types. Supported types are the 8 primitives, their corresponding wrappers and java.lang.String. The default behavior is to map request parameters to action arguments by name
 class AccountingController {  
 // accountNumber will be initialized with the value of params.accountNumber  
 // accountType will be initialized with params.accountType  
 def displayInvoice(String accountNumber, int accountType) {  
 // …  
 }  
 }  
For primitive arguments and arguments which are instances of any of the primitive type wrapper classes a type conversion carried out before the request parameter value can be bound to the action argument. The type conversion happens a case like the example shown above, the params.accountType request parameter has to be converted to conversion fails for any reason, the argument will have its default value per normal Java behavior (null for type wrapper false for booleans and zero for numbers) and a corresponding error will be added to the errors property controller.
 /accounting/displayInvoice?accountNumber=B59786&accountType=bogusValue  
Since "bogusValue" cannot be converted to type int, the value of accountType will be zero, the errors.hasErrors() will be true, the controller's errors.errorCount will be equal to 1 and errors.getFieldError('accountType') will contain the corresponding error.
If the argument name does not match the name of the request parameter then the @grails.web.RequestParameter
annotation may be applied to an argument to express the name of the request parameter which should be bound
 import grails.web.RequestParameter  
 class AccountingController {  
 // mainAccountNumber will be initialized with the value of params.accountNumber  
 // accountType will be initialized with params.accountType  
 def displayInvoice(@RequestParameter('accountNumber') String mainAccountNumber, int {  
 // …  
 }  
 }  
Data binding and type conversion errors
Sometimes when performing data binding it is not possible to convert a particular String into a particular target type. a type conversion error. Grails will retain type conversion errors inside the errors property of a Grails domain
 class Book {  
 …  
 URL publisherURL  
 }  
Here we have a domain class Book that uses the java.net.URL class to represent URLs. Given an incoming
 /book/save?publisherURL=a-bad-url  
it is not possible to bind the string a-bad-url to the publisherURL property as a type mismatch error occurs. for these like this :
 def b = new Book(params)  
 if (b.hasErrors()) {  
 println "The value ${b.errors.getFieldError('publisherURL').rejectedValue}" +  
 " is not a valid URL!"  
 }  
Although we have not yet covered error codes (for more information see the section on Validation), for type conversion would want a message from the grails-app/i18n/messages.properties file to use for the error. You error message handler such as :
 typeMismatch.java.net.URL=The field {0} is not a valid URL  
Or a more specific one :
 typeMismatch.Book.publisherURL=The publisher URL you specified is not a valid URL  
The BindUsing Annotation
The annotation may be used to define a custom binding mechanism for a particular field in a class. BindUsing binding is being applied to the field the closure value of the annotation will be invoked with 2 arguments. The first object that data binding is being applied to and the second argument is DataBindingSource which is the data source binding. The value returned from the closure will be bound to the property. The following example would result version of the name value in the source being applied to the name field during data binding.
 import org.grails.databinding.BindUsing  
 class SomeClass {  
 @BindUsing({obj, source ->  
 //source is DataSourceBinding which is similar to a Map  
 //and defines getAt operation but source.name cannot be used here.  
 //In order to get name from source use getAt instead as shown below.  
 source['name']?.toUpperCase()  
 })  
 String name  
 }  
The BindUsing annotation may be used to define a custom binding mechanism for all of the fields on a particular annotation is applied to a class, the value assigned to the annotation should be a class which implements the interface. An instance of that class will be used any time a value is bound to a property in the class that this annotation applied to.
 @BindUsing(SomeClassWhichImplementsBindingHelper)  
 class SomeClass {  
 String someProperty  
 Integer someOtherProperty  
 }  
Custom Data Converters
The binder will do a lot of type conversion automatically. Some applications may want to define their own converting values and a simple way to do this is to write a class which implements and register ValueConverter an class as a bean in the Spring application context.
 package com.myapp.converters  
 import org.grails.databinding.converters.ValueConverter  
 /**  
 * A custom converter which will convert String of the  
 * form 'city:state' into an Address object.  
 */  
 class AddressValueConverter implements ValueConverter {  
 boolean canConvert(value) {  
 value instanceof String  
 }  
 def convert(value) {  
 def pieces = value.split(':')  
 new com.myapp.Address(city: pieces[0], state: pieces[1])  
 }  
 Class<?> getTargetType() {  
 com.myapp.Address  
 }  
 }  
An instance of that class needs to be registered as a bean in the Spring application context. The bean name is not beans that implemented ValueConverter will be automatically plugged in to the data binding process.
 // grails-app/conf/spring/resources.groovy  
 beans = {  
 addressConverter com.myapp.converters.AddressValueConverter  
 // ...  
 }  
 class Person {  
 String firstName  
 Address homeAddress  
 }  
 class Address {  
 String city  
 String state  
 }  
 def person = new Person()  
 person.properties = [firstName: 'Jeff', homeAddress: "O'Fallon:Missouri"]  
 assert person.firstName == 'Jeff'  
 assert person.homeAddress.city = "O'Fallon"  
 assert person.homeAddress.state = 'Missouri'  
Date Formats For Data Binding
A custom date format may be specified to be used when binding a String to a Date value by applying the BindingFormat to a Date field.
 import org.grails.databinding.BindingFormat  
 class Person {  
 @BindingFormat('MMddyyyy')  
 Date birthDate  
 }  
A global setting may be configured in Config.groovy to define date formats which will be used application wide to Date.
 // grails-app/conf/Config.groovy  
 grails.databinding.dateFormats = ['MMddyyyy', 'yyyy-MM-dd HH:mm:ss.S', "yyyy-MM-dd'T'hh  
The formats specified in grails.databinding.dateFormats will be attempted in the order in which they the List. If a property is marked with @BindingFormat, the @BindingFormat will take precedence over the values grails.databinding.dateFormats.
The default formats that are used are "yyyy-MM-dd HH:mm:ss.S" and "yyyy-MM-dd'T'hh:mm:ss'Z'".
Custom Formatted Converters
You may supply your own handler for the annotation by writing a class which BindingFormat implements FormattedValueConverter interface and regiserting an instance of that class as a bean in the Spring application context. example of a trivial custom String formatter that might convert the case of a String based on the value BindingFormat annotation.
 package com.myapp.converters  
 import org.grails.databinding.converters.FormattedValueConverter  
 class FormattedStringValueConverter implements FormattedValueConverter {  
 def convert(value, String format) {  
 if('UPPERCASE' == format) {  
 value = value.toUpperCase()  
 } else if('LOWERCASE' == format) {  
 value = value.toLowerCase()  
 }  
 value  
 }  
 Class getTargetType() {  
 // specifies the type to which this converter may be applied  
 String  
 }  
 }  
An instance of that class needs to be registered as a bean in the Spring application context. The bean name is not beans that implemented FormattedValueConverter will be automatically plugged in to the data binding process
 // grails-app/conf/spring/resources.groovy  
 beans = {  
 formattedStringConverter com.myapp.converters.FormattedStringValueConverter  
 // ...  
 }  
With that in place the BindingFormat annotation may be applied to String fields to inform the data binder to the custom converter.
 import org.grails.databinding.BindingFormat  
 class Person {  
 @BindingFormat('UPPERCASE')  
 String someUpperCaseString  
 @BindingFormat('LOWERCASE')  
 String someLowerCaseString  
 String someOtherString  
 }  
Localized Binding Formats
The BindingFormat annotation supports localized format strings by using the optional code attribute. If a value 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.
 import org.grails.databinding.BindingFormat  
 class Person {  
 @BindingFormat(code='date.formats.birthdays')  
 Date birthDate  
 }  
 # grails-app/conf/i18n/messages.properties  
 date.formats.birthdays=MMddyyyy  
 # grails-app/conf/i18n/messages_es.properties  
 date.formats.birthdays=ddMMyyyy  
Structured Data Binding Editors
A structured data binding editor is a helper class which can bind structured request parameters to a property. The for structured binding is binding to a object which might be constructed from several smaller pieces of information Date in several request parameters with names like birthday_month, birthday_date and birthday_year. 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 whatever types are appropriate. Consider the following classes :
 // src/groovy/databinding/Gadget.groovy  
 package databinding  
 class Gadget {  
 Shape expandedShape  
 Shape compressedShape  
 }  
 // src/groovy/databinding/Shape.groovy  
 package databinding  
 class Shape {  
 int area  
 }  
A Gadget has 2 Shape fields. A Shape has an area property. It may be that the application wants to accept request like width and height and use those to calculate the area of a Shape at binding time. A structured binding suited for that.
The way to register a structured editor with the data binding process is to add an instance org.grails.databinding.TypedStructuredBindingEditor interface to the Spring application context. The easiest way TypedStructuredBindingEditor inter face i s to extend org.grails.databinding.converters.AbstractStructuredBindingEditor abstract class and override the getPropertyValue as shown below :
 // src/groovy/databinding/converters/StructuredShapeEditor.groovy  
 package databinding.converters  
 import databinding.Shape  
 import org.grails.databinding.converters.AbstractStructuredBindingEditor  
 class StructuredShapeEditor extends AbstractStructuredBindingEditor<Shape> {  
 public Shape getPropertyValue(Map values) {  
 // retrieve the individual values from the Map  
 def width = values.width as int  
 def height = values.height as int  
 // use the values to calculate the area of the Shape  
 def area = width * height  
 // create and return a Shape with the appropriate area  
 new Shape(area: area)  
 }  
 }  
An instance of that class needs to be registered with the Spring application context :
 // grails-app/conf/spring/resources.groovy  
 beans = {  
 shapeEditor databinding.converters.StructuredShapeEditor  
 // …  
 }  
When the data binder binds to an instance of the Gadget class it will check to see if there are request parameters compressedShape and expandedShape which have a value of "struct" and if they do exist, that will trigger StructuredShapeEditor. The individual components of the structure need to have parameter names propertyName_structuredElementName. In the case of the Gadget class above that would mean that the compressedShape
request parameter should have a value of "struct" and the compressedShape_width and compressedShape_parameters should have values which represent the width and the height of the compressed Shape. expandedShape request parameter should have a value of "struct" and the expandedShape_expandedShape_height parameters should have values which represent the width and the hight of the expanded
 // grails-app/controllers/demo/DemoController.groovy  
 class DemoController {  
 def createGadget(Gadget gadget) {  
 /*  
 /demo/createGadget?expandedShape=struct&expandedShape_width=80&expandedShape_height=30  
 &compressedShape=struct&compressedShape_width=10&compressedShape_*/  
 // with the request parameters shown above gadget.expandedShape.area would be 2400  
 // and gadget.compressedShape.area would be 30  
 // ...  
 }}  
Typically the request parameters with "struct" as their value would be represented by hidden form fields.
Data Binding Event Listeners
The interface provides a mechanism for listeners to be notified of data binding events. The interface DataBindingListener this :
 package org.grails.databinding.events;  
 import org.grails.databinding.errors.BindingError;  
 public interface DataBindingListener {  
 /**  
 * @return true if the listener is interested in events for the specified type.  
 */  
 boolean supports(Class<?> clazz);  
 /**  
 * Called when data binding is about to start.  
 *  
 * @param target The object data binding is being imposed upon  
 * @param errors the Spring Errors instance (a org.springframework.validation.BindingResult)  
 * @return true if data binding should continue  
 */  
 Boolean beforeBinding(Object target, Object errors);  
 /**  
 * Called when data binding is about to imposed on a property  
 *  
 * @param target The object data binding is being imposed upon  
 * @param propertyName The name of the property being bound to  
 * @param value The value of the property being bound  
 * @param errors the Spring Errors instance (a org.springframework.validation.BindingResult)  
 * @return true if data binding should continue, otherwise return false  
 */  
 Boolean beforeBinding(Object target, String propertyName, Object value, Object errors);  
 /**  
 * Called after data binding has been imposed on a property  
 *  
 * @param target The object data binding is being imposed upon  
 * @param propertyName The name of the property that was bound to  
 * @param errors the Spring Errors instance (a org.springframework.validation.BindingResult)  
 */  
 void afterBinding(Object target, String propertyName, Object errors);  
 /**  
 * Called after data binding has finished.  
 *  
 * @param target The object data binding is being imposed upon  
 * @param errors the Spring Errors instance (a org.springframework.validation.BindingResult)  
 */  
 void afterBinding(Object target, Object errors);  
 /**  
 * Called when an error occurs binding to a property  
 * @param error encapsulates information about the binding error  
 * @param errors the Spring Errors instance (a org.springframework.validation.BindingResult)  
 * @see BindingError  
 */  
 void bindingError(BindingError error, Object errors);  
 }  
Any bean in the Spring application context which implements that interface will automatically be registered with The DataBindingListenerAdapter class implements the DataBindingListener interface and provides default for all of the methods in the interface so this class is well suited for subclassing so your listener class only implementations for the methods your listener is interested in.
The Grails data binder has limited support for the older BindEventListener style listeners. BindEventListener
 package org.codehaus.groovy.grails.web.binding;  
 import org.springframework.beans.MutablePropertyValues;  
 import org.springframework.beans.TypeConverter;  
 public interface BindEventListener {  
 /**  
 * @param target The target to bind to  
 * @param source The source of the binding, typically a Map  
 * @param typeConverter The type converter to be used  
 */  
 void doBind(Object target, MutablePropertyValues source, TypeConverter typeConverter);  
 }  
Support for BindEventListener is disabled by default. To enable support assign a value of grails.databinding.enableSpringEventAdapter property in grails-app/conf/Config
 // grails-app/conf/Config.groovy  
 grails.databinding.enableSpringEventAdapter=true  
 ...  
With enableSpringEventAdapter set to true instances of BindEventListener which are in the Spring context will automatically be registered with the data binder. Notice that the MutablePropertyValues TypeConverter arguments to the doBind method in BindEventListener are Spring specific classes and to the current data binder. The event adapter will pass null values for those arguments. The only real value doBind method will be the object being bound to. This limited support is provided for backward compatibility and for a subset of scenarios. Developers are encouraged to migrate their BindEventListener beans DataBindingListener model.
Using The Data Binder Directly
There are situations where an application may want to use the data binder directly. For example, to do binding in a arbitrary object which is not a domain class. The following will not work because the properties property is read
 // src/groovy/bindingdemo/Widget.groovy  
 package bindingdemo  
 class Widget {  
 String name  
 Integer size  
 }  
 // grails-app/services/bindingdemo/WidgetService.groovy  
 package bindingdemo  
 class WidgetService {  
 def updateWidget(Widget widget, Map data) {  
 // this will throw an exception because  
 // properties is read-only  
 widget.properties = data  
 }  
 }  
An instance of the data binder is in the Spring application context with a bean name of grailsWebDataBinder. implements the DataBinder interface. The following code demonstrates using the data binder directly.
 // grails-app/services/bindingdmeo/WidgetService  
 package bindingdemo  
 import org.grails.databinding.SimpleMapDataBindingSource  
 class WidgetService {  
 // this bean will be autowired into the service  
 def grailsWebDataBinder  
 def updateWidget(Widget widget, Map data) {  
 grailsWebDataBinder.bind widget, data as SimpleMapDataBindingSource  
 }  
 }  
See the DataBinder documentation for more information about overloaded versions of the bind method.
Data Binding and Security Concerns
When batch updating properties from request parameters you need to be careful not to allow clients to bind domain classes and be persisted in the database. You can limit what properties are bound to a given domain subscript operator :
 def p = Person.get(1)  
 p.properties['firstName','lastName'] = params  
In this case only the firstName and lastName properties will be bound.
Another way to do this is is to use as the target of data binding instead of domain classes. Alternatively Command Objects also the flexible bindData method.
The bindData method allows the same data binding capability, but to arbitrary objects :
 def p = new Person()  
 bindData(p, params)  
The bindData method also lets you exclude certain parameters that you don't want updated :
 def p = new Person()  
 bindData(p, params, [exclude: 'dateOfBirth'])  
Or include only certain properties :
 def p = new Person()  
 bindData(p, params, [include: ['firstName', 'lastName']])  
Posted on Sunday, July 6, 2014 11:54 AM Grails | Back to top


Comments on this post: Grails Basic-Controllers(Part 2)

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © A.K.M. Zakaria | Powered by: GeeksWithBlogs.net