Posted by survivant
on December 19, 2008 at 7:26 AM PST
I needed to parse a web.xml for a sample for Grizzly and I wanted to find a way to have something that I can reuse later. You don't have to do it by hand. There are tools out there to do it for you.
One of them is XMLBeans from Apache group and more popular is JAXB. For JDK 1.4 ,I used XMLBeans and if you have JDK6 JAXB will reduce the dependencies and will be more smaller. I'll show you how to use theses two API.
What I like about this tool is that I can generate Java classes from a xsd within seconds using Ant.
I want to show you how to obtain a Class that will contains a web.xml loaded with only one line of code :)
Let's start by downloading XMLBeans. I'll skip to the folder structure I'll use for this demo.
lib/ : Where you put the XMLBeans libraries
schemas/ : Where you put the xsd
Download build.xml from here .
I use the schemas from Glassfish sources : glassfish/appserv-commons/schemas
You don't have to copy all the files. Copy just the main schemas and Ant will download the missing schemas.
For my demo I used theses files :
you just have to launch the ant task with this command :
that will generate a jar file and the java source for theses schemas.
Now.. How do we load a web.xml within our Java application ?
#1 - Include the jar file : j2ee_schemas-xmlbeans.jar into your project
#2 - Create the root class of your schema and load the web.xml
WebAppDocument webAppDocument = WebAppDocument.Factory.parse(webxmlFile);
After that .. It's up to you, webAppDocument contains all the config from web.xml.
You will need the librairies for the compilation, but after that if you use JDK6, you can remove them, because JAXB is include in JDK6.
#1 - To generate the schemas, you use ant.
#2 - Include the jar file : j2ee_schemas-jaxb.jar into your project
#3 - Create the root class of your schema and load the web.xml
JAXBContext jc = JAXBContext.newInstance("ca.sebastiendionne.jaxb.xsd");
// create an Unmarshaller
Unmarshaller u = jc.createUnmarshaller();
JAXBElement root = (JAXBElement)u.unmarshal( new FileInputStream("./web.xml") );
WebAppType webAppType = (WebAppType)root.getValue();
It's take a little more line of code, but it's not complicated.
I put the source project (xmlbeans + jabx) here .