Migrating from Struts to Spring MVC – using Groovy!

To migrate from Struts 1 to Spring MVC, the easiest route is:
  1. Add the Spring ContextLoaderPlugin to your struts-config file. This plugin will load your bean definitions file.
  2. Update struts-config so that rather than using the default Struts request processor it uses Spring’s delegating request processor.
  3. Write a bean definition file to declare all of your Struts actions as Spring beans.
The third of these tasks could be a tedious manual task – why not script it with Groovy? It provides a good example of Groovy’s XML and GPath capabilities. GPath is the Groovy syntax for navigating in XML or object trees. It allows you to do the following:
  • Use the dot notation to traverse from one object or XML node to the next.
  • Find objects with specified properties.
For my very first attempt at scripting this, I wrote the following (it doesn’t deal with all of the Struts properties, just demonstrates the concept):
// read the struts file in as XML
GPathResult strutsConfig = new XmlSlurper().parse(inputFile)

// get all of the "action" nodes by traversing from the top level
// struts-config node
def actions = strutsConfig."action-mappings".action

// write the Spring action-beans.xml file
actions.each{ action ->
	outputFile.append('<bean name="' + action.@path + '"n')
	outputFile.append('  class="' + action.@type + '"n')
You can see easy and concise the Groovy code is compared to Java. Reading the file in is a single line, as is getting the set of <action> nodes. For more info on Groovy’s XML capabilities, check out: http://groovy.codehaus.org/Reading+XML+using+Groovy%27s+XmlSlurper http://groovy.codehaus.org/GPath
This entry was posted in Groovy, Spring and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

HTML tags are not allowed.

516,722 Spambots Blocked by Simple Comments