jump to navigation

Commons Digester October 23, 2007

Posted by Phill in General J2EE, Open Source.
Tags: , , ,
comments closed

Last week, I had to build a validation system for a legacy J2EE system (I’m not sure whether you can actually call any J2EE applications ‘legacy’, but it’s pretty old anyway – from before frameworks were popular).

I thought I’d model it on the Struts validation system: have an XML file containing all the different validators, and another XML file containing the actual validation that is to be performed on each field. Obviously it couldn’t be as comprehensive as the Struts validators (it was actually fairly basic in the end), but did require a moderate level of complexity in the XML configuration.

I don’t know about you, but I hate parsing XML – it’s just not particularly exciting! You feel like you have to spend ages with the nuts-and-bolts. Step up Commons Digester. This is an XML parser with a difference… you don’t actually ever need to deal with any XML (per se). It was originally built for the Struts framework, to parse the struts-config.xml file.

Its purpose is to create Java objects from an XML file. You specify a list of ‘rules’, and the XML document is then parsed and Java objects created as necessary. For example, if you have an element in the XML document: validators/validator, you could set up Digester to create a new object “com.test.Validator” whenever this particular construct was encountered.

There are some good examples on the documentation.

If you’re starting a new project and need to create Java objects based on an XML file, it’s definitely worth a look. It saved me a lot of hassle!

Follow

Get every new post delivered to your Inbox.