Java & XML, 2nd (Best web design) Edition // Create new
Friday, August 31st, 2007Java & XML, 2nd Edition // Create new DOM tree DOMImplementation domImpl = new DOMImplementationImpl( ); Document doc = domImpl.createDocument(null, “item”, null); Element root = doc.getDocumentElement( ); // ID of item (as attribute) root.setAttribute(”id”, id); // Name of item Element nameElement = doc.createElement(”name”); Text nameText = doc.createTextNode(name); nameElement.appendChild(nameText); root.appendChild(nameElement); // Description of item Element descriptionElement = doc.createElement(”description”); Text descriptionText = doc.createTextNode(description); descriptionElement.appendChild(descriptionText); root.appendChild(descriptionElement); // Serialize DOM tree DOMSerializer serializer = new DOMSerializer( ); serializer.serialize(doc, new File(ITEMS_DIRECTORY + “item-” + name + “.xml”)); // Print confirmation PrintWriter out = res.getWriter( ); res.setContentType(”text/html”); out.println(”
Thank you for your submission. ” + “Your item has been processed.“); out.close( ); } } Go ahead and compile this class. I’ll walk you through it in just a moment, but ensure that you have your environment set up to include the needed classes. Make sure the DOMSerializer class from the last chapter is in your classpath when compiling the UpdateItemServlet class. You’ll also want to add this to the classes in your servlet engine’s context. In my setup, using Tomcat, my context is called javaxml2, in a directory named javaxml2 under the webapps directory. In my WEB-INF/classes directory, there is a javaxml2 directory (for the package), and then the DOMSerializer.class and UpdateItemServlet.class files are within that directory. You should also ensure that a copy of your parser’s jar file (xerces.jar in my case) is in the classpath of your engine. In Tomcat, you can simply drop a copy in Tomcat’s lib directory. Finally, you’ll need to ensure that Xerces, and the DOM Level 2 implementation within it, is loaded before the DOM Level 1 implementation in Tomcat’s parser.jar archive. Do this by renaming parser.jar to z_parser.jar. I’ll explain more about this in Chapter 10, but for now just trust me and make the change. Then restart Tomcat and everything should work.We would like to recommend you tested and proved virtual web hosting services, which you will surely find to be of great quality.