Sunday, March 16, 2008

More Struts 2

Some additional things I picked up as I work with Struts 2, as well as new approaches and explanations to some behavior in my previous post.

  • Matt Payne is spot on with his comment on validator annotations not limiting themselves to the Action methods they are declared to.  You will need to create a new Action if you need a validate another Action method in a different way.  Or maybe go with ActionClass-urlAlias-validation.xml which works pretty well.
  • Struts 2 includes a conversion error interceptor that displays a customizable error message if a type conversion fails, and a conversion validator that checks if a conversion was successful or not.  I used the validator to check if the value of a required date field was in the correct format.  Problem was that if conversion failed two errors were displayed: one for the conversion and one for the required field.  Ended up disabling the interceptor and writing a validator that combined the two validators together.
  • To disable the interceptor above I initially copied defaultStack from struts-default.xml to my struts.xml and removed the interceptor.  This didn't work.  Finally found this ticket that explained that zero config ignored the custom interceptor stacks in struts.xml.  This explains why modifying excludeMethods in my previous post didn't work.  Adding @ParentPackage to my Action fixed my stack problem.
  • Custom type converters are pretty easy to write.  We make use of a certain date format for our date fields which is different from my current locale.  I wrote a custom type converter that checks for the required date format.  Added this to xwork-conversion.properties (still not struts-conversion.properties I see) to replace the global date type converter.
  • Found out about message store interceptor.  This pretty much covered the custom code I wrote to persist messages across redirects, and more.  A problem though is that it doesn't have an annotation equivalent as far I know, and the request parameter approach of adding operationMode is awkward.  Ended up removing zero config just for this.  Hopefully there will be a way to use this with annotations in the future. 

Admittedly, the last point was a bit of a downer.  But we need to be practical, and the XML required in struts.xml isn't that bad.  Certainly much better than that of Struts 1 even with XDoclet, which probably makes it worse.  Still, here's a screen shot of the commit log when I removed zero-config for XML:

From annotations to XML

0 comments: