In Grails, one can 'bindData' in controller:
Book b = new Book()
bindData(b, params)
What if I have a date field with specific format (e.g. yyyy-MM-dd) from user input? In Spring, we can use registerCustomEditor(). How about Grails?
With Grails 1.1.1, you can implement a PropertyEditorRegistrar and use that to specify a format. See http://grails.1312388.n4.nabble.com/Grails-1-1-1-change-in-binding-date-properties-td1323105.html
Have you already come across the Extended Data Binding Plugin?
From the documentation on the site, it appears to offer both aspects which you are referring to
Allow customization of the DataBinder that will be used to parse user-defined input and populate objects (typically domain objects) with custom PropertyEditors on both application-wide and controller-specific levels.as String.
Extend controllers with dynamic methods to allow data binding and bean wrapping.
Related
#WebInitParam is an annotation that goes at class level.
It defines initialization parameters for the servlet.
I would like to know, what is the difference between doing this and using static variables, and why do it the #WebInitParam way rather than using statics?
What does defining k/v pairs as #WebInitParams allow you to do that you couldn't do if you declared static variables instead?
I have looked and all I can find is a million people saying how to define #WebInitParams. Well yes that's the easy bit. It's what I can do with that that is really what is of interest.
Thanks very much.
From a "raison d'etre" perspective, the annotation exists as a better design and architecture alternative to just peppering a class with static fields. #WebInitParam is a self-documenting approach to the initialization parameters a servlet or filter class needs, available via web.xml as well. It serves this purpose for the end developers as well as the JavaEE platform as a whole.
Think about it this way: in a vanilla project, you have the option of hardcoding a bunch of parameters in the class as static fields, or defining the same parameters in a property file. Which would you pick? Under what circumstances?
From a purely functional angle, apart from the function of using the annotation to override defaults set in web.xml, one other major reason is that you will sometimes need to get a hold of those initialization parameters from another component in your application. Using the annotation essentially increases the visibility of the parameter. In JSF for example, the API allows you to retrieve FacesServlet initialization parameters with:
//get all the parameters
FacesContext.getCurrentInstance().getExternalContext().getInitParameterMap()
//get a specific parameter
FacesContext.getCurrentInstance().getExternalContext().getInitParameter("aParameter");
In JSF-2.3 , it gets even more convenient with the following CDI-enabled injection:
#InitParameterMap Map<String,String> servletParameterMap;
Bear in mind that because it's CDI, it means this facility is available throughout the JavaEE platform, not just in web applications/JSF.
It's going to be a hassle to retrieve init parameters if the only mechanism available is a static field in the servlet class - you'll need to obtain an instance of the filter or servlet to get the static fields in it.
Separately, one could make the argument that maybe one should favour context-params over servlet-params because then, you get even more flexibility that isn't tied to any given servlet. That's a separate matter entirely :)
I'm trying to come up with a reusable pattern for updating MongoDB Documents when using Spring Data in conjunction with Spring MVC.
The use case can generally be summarized by:
A document is created in Mongo using repository.save()
Parts of that document are then presented in a Spring MVC editable form.
A user submits updated parts of that document which are then saved.
If I use the repository.save() method in step 3, I will lose any data in the document that was not bound to the form. Making the form responsible for the entire document is fragile so this is where it seems the findAndModify() method of the MongoTemplate comes in handy.
To use the findAndModify() method, I've created Form objects that support a toMap() method which takes the Form object's properties as a Map and removes some of the fields (e.g. class and id). This gets me a Map that contains only the fields that I care about from the Form object. Passing the object ID and this map to an update() method on my customized repository, I build Query and Update objects that I can pass to the findAndModify() method.
Using this approach, I'm able to add fields to my objects easily and only worry about instances when there are fields I don't want to update from a form posting. Document fields not manipulated by the Form should be retained. It still seems slightly convoluted to be using both the Repository and MongoTemplate so I'm wondering if there are better examples for how to handle this. It seems like this should be a consistent pattern when working with Mongo and Spring MVC (at the least).
I've created a sample project showing how I achieve this model on GitHub. The Spock Tests show how "updating" a Document using save() will blow away fields as expected and my update() method.
https://github.com/watchwithmike/diner-data
What are other people doing when dealing with partial updates to Documents using Spring MVC and Spring Data?
If you are taking whatever the user supplies and just shoving that in the database you are running the risk of doing something dangerous like updating or creating data that they shouldn't be able to. Instead, you should first query Mongo to get the most recent version of the document, change any fields (it looks like you are using Groovy so you could loop through all the properties and set them on the new document), and then save the new, complete document.
If you are making small, consistent updates (like increasing the number of votes, or something like that), you could create a custom MongoDB query using the MongoTemplate to do an update to a few fields. Check out the spring-data-mongodb docs for more. You can also add custom methods to the MongoRepository that use the MongoTemplate.
I would like to customize at runtime the attributes that MVC sees on a view model property. As far as I know, MVC relies internally on type descriptors to enumerate the attributes. Is there a way to hook a type descriptor somewhere to return a custom list of attributes for a property?
Is there a way to hook a type descriptor somewhere to return a custom
list of attributes for a property?
It depends. If you want to override the Data Annotations used by the metadata provider then you could write your own custom ModelMetadataProvider and replace the default one (DataAnnotationsModelMetadataProvider). This allows you to have a custom metadata provider for a given type and return this information at runtime.
If on the other hand you are doing validation, then you are a bit out of luck. For more flexibility I would recommend you using FluentValidation.NET instead of data annotations.
Say I have a form that has fields to gather data about future conferences (not the real domain but will suffice for the purposes of this question). Part of the validation is that a new event can only happen once in that year so for instance if you have a "stackoverflow getmessyandrunk conference" that happens in 2012 - the user shouldn't be allowed to enter a new event with the same name and year...
Now - what I have tried so far is to add a remote validator to each of the fields:
one for the event name field that uses the AdditionalFields property to include the year field and one for the year field which uses the AdditionalFields to include the event name field.
it doesn't work - if I try to add an event with the same name and year it adds an error to just the year field, correcting it fixes it, then trying again it adds an error to the name field and year field, correcting the name field to make the combination unique only removes the error from the name field - it goes on like this...
How are others doing this?
If you prefer using data annotations for validation, I would recommend that you just use the Foolproof validation library that is available on Codeplex: https://foolproof.codeplex.com/
It supports, amongst others, the following "requiredif" validation attributes / decorations:
[RequiredIf]
[RequiredIfNot]
[RequiredIfTrue]
[RequiredIfFalse]
[RequiredIfEmpty]
[RequiredIfNotEmpty]
[RequiredIfRegExMatch]
[RequiredIfNotRegExMatch]
To get started is easy:
Download the package from the provided link
Add a reference to the included .dll file
Import the included javascript files
Ensure that your views references the included javascript files from within its HTML for unobtrusive javascript and jquery validation.
If you don't like mixing your domain and and validation logic by decorating your domain classes with validation attributes, you can always opt for the powerful fluent validation. You can find the library for it here:
https://fluentvalidation.codeplex.com/
It is unfortunately server-side only, but a suitable option if seperation of concerns is of importance to you... and context is not lost due to the validation being tied to a specific field. (See here: http://www.codeproject.com/Articles/326647/FluentValidation-and-Unity)
I am relatively new to Web Parts and Web Forms (I have only worked a lot with the MVC framework).
I am planning to store some data in the control state. All the examples I can find put an object[] array in the control state and the base control state on the 0 index.
I don't really like putting everything in an object[], so I wanted to create an extra class for my web part with typed properties: e.g. MyWebPartControlState. I will store the base control state in a property BaseControlState of type object.
I was wondering if this could cause any problems or if there are any other reasons why this might not be a good idea. I am wondering because it feels logical to me, but I cannot find any examples of control state where they don't put everything in the control state directly or in a object[].
Thanks in advance.
The control state is persisted in the same field as view state and follows the same rules for serialization. All the samples you found use an object array because that's one of the types the optimized state serializer in ASP.NET understands and for which is able to optimize serialization.
If you use a custom object the serializer won't use the optimizations and instead will serialize your object using the BinaryFormatter which will lead to bloated control state. If you want to have a strongly typed view of your state you should implement IStateManager on your custom class so that it encapsulates the transformation of itself from and to simple objects that the serializer understands.
If I recall correctly the serializer can efficiently serialize the following types:
Primitive types (int, long, etc);
DateTime;
string;
Boxed values of supported value types;
Object arrays containing instances of supported types;
Pair and Triplet objects containing instances of supported types.
I wrote a short blogpost illustrating the differences in size resulting from a simple custom class being serialized with BinaryFormatter versus implementing IStateManager and decomposing to simple types that the serializer can optimize. You can find it at:
ASP.NET ViewState Tips and Tricks #2