Sunday, September 25, 2011

Porting Spring MVC to Grails

Model
Model comparison
Spring mvc really doesn't tie in a specific model but hibernate with JPA anotations is probably the choice for most.  We had hibernate with xml configs plus DAOs.  GORM is much more elegant - less code - less classes.  No validators for example.  GORM has named queries - think of SUPER Domain classes!  Between service and domain  classes I see no need for a DAO.

Model porting
Switching you model tier to grails will involve the most work.  It would be possible to reuse hibernate DAOs and just create service classes that use them as a first step.  Best to just port it to GORM to gain all capabilities of Grails domain classes.

Best approached as both a bottom and top down.  Rewrite all hibernate domains to GORM then rewrite all spring service classes to Grails service classes and add functionality to domain classes as required by service class.   Finally add validators (constraints) to replace spring validator classes to domains.

Model Results
Elimination of many layers, classes (ie, DAOs, Validators).  Service classes are similar but much less code.  Using groovy and GORM dynamic features brings a lot of power.    Much more readable.

View
View comparison
GSP more flexible, sitemesh layouts are intuitive,  grails tag libs that can be called as methods (avoids nested tag issue), Grails tag library very good.  Smart tags that pass through tag attributes that are not part of tag (ie. class="css-class").  Big plus for grails  is handling of partial pages (templates). Can be done with tiles but has to be configured as an entire page.  Grails makes ajax trivial (whether returning xml, Json, or partial html).

View porting
This was by far the simplest part of porting.  Simply rename your JSP to GSP and switch your JSP tags to Grails tags.  Your javascript should be relatively unaffected as long as you have the grails tags create the same markup.  If you used tiles or other dynamic templating switching to sitemesh shouldn't prove too difficult.  We did employ tiles but nothing too crazy.  Switching to sitemesh was a breeze and I much prefer working with sitemesh - very intuitive - no config files.

View Result
No configuration - ie. tiles.  GSP tags more powerful but all in all GSP is similar to a JSP.

Controller comparison
Spring MVC has a few ways to handle model in the controller. What I dislike the most is the annotation of a method to have it return  part of the model.  So your controller has this mix of methods that have very different purposes.  All in all somewhat similar although handling different output formats (eg. JSon) much easier in grails - same handler method can handle different outpout.

Controller port
Fairly straightforward.
Result 
Grails controller much more concise and intutitive.  Easy to maintain - logic for particular request in one method (closure actually).    

No comments:

Post a Comment