FileDocCategorySizeDatePackage
UpdateItemServlet.javaAPI DocExample8433Thu Aug 16 16:59:34 BST 2001javaxml2

UpdateItemServlet

public class UpdateItemServlet extends HttpServlet
UpdateItemServlet demonstrates how the DOM Level 2 Range module can be used for handling range within a document.

Fields Summary
private static final String
ITEMS_DIRECTORY
The directory to load XML from
Constructors Summary
Methods Summary
public voiddoGet(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res)

Allow a user to input a new item for the auction.


                    
         
           

        // Get output
        PrintWriter out = res.getWriter();
        res.setContentType("text/html");

        // Output HTML        
        out.println("<html>");
        out.println(" <head><title>Input/Update Item Listing</title></head>");
        out.println(" <body>");
        out.println("  <h1 align='center'>Input/Update Item Listing</h1>");
        out.println("  <p align='center'>");
        out.println("   <form method='POST' " +
            "action='/javaxml2/servlet/javaxml2.UpdateItemServlet'>");
        out.println("    Item ID (Unique Identifier): <br />");
        out.println("    <input name='id' type='text' maxLength='10' />" +
            "<br /><br />");
        out.println("    Item Name: <br />");
        out.println("    <input name='name' type='text' maxLength='50' />" +
            "<br /><br />");
        out.println("    Item Description: <br />");
        out.println("    <textarea name='description' rows='10' cols='30' " +
            "wrap='wrap' ></textarea><br /><br />");
        out.println("    <input type='reset' value='Reset Form' />  ");
        out.println("    <input type='submit' value='Add/Update Item' />");
        out.println("   </form>");
        out.println("  </p>");
        out.println(" </body>");
        out.println("</html>");
 
        out.close();
    
public voiddoPost(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res)

Search for the item specified, and either create a new file or update the existing one. DOM Level 2 Range is used for quicker replacement of a range of data.


        // Get parameter values
        String id = req.getParameterValues("id")[0];
        String name = req.getParameterValues("name")[0];
        String description = req.getParameterValues("description")[0];

        // See if this file exists
        Document doc = null;
        File xmlFile = new File(ITEMS_DIRECTORY + "item-" + id + ".xml");
        String docNS = "http://www.oreilly.com/javaxml2";

        if (!xmlFile.exists()) {
            // Create new DOM tree
            DOMImplementation domImpl = new DOMImplementationImpl();
            doc = domImpl.createDocument(docNS, "item", null);
            Element root = doc.getDocumentElement();
            root.setAttribute("xmlns", docNS);

            // ID of item (as attribute)
            root.setAttribute("id", id);

            // Name of item
            Element nameElement = doc.createElementNS(docNS, "name");
            Text nameText = doc.createTextNode(name);
            nameElement.appendChild(nameText);
            root.appendChild(nameElement);

            // Description of item
            Element descriptionElement = doc.createElementNS(docNS, "description");
            Text descriptionText = doc.createTextNode(description);
            descriptionElement.appendChild(descriptionText);
            root.appendChild(descriptionElement);
        } else {
            // Load document
            try {
                DOMParser parser = new DOMParser();
                parser.parse(xmlFile.toURL().toString());
                doc = parser.getDocument();

                Element root = doc.getDocumentElement();
   
                // Name of item
                NodeList nameElements = root.getElementsByTagNameNS(docNS, "name");
                Element nameElement = (Element)nameElements.item(0);
                Text nameText = (Text)nameElement.getFirstChild();
                nameText.setData(name);
            
                // Description of item
                NodeList descriptionElements = 
                    root.getElementsByTagNameNS(docNS, "description");
                Element descriptionElement = (Element)descriptionElements.item(0);

                // Remove and recreate description
                Range range = ((DocumentRange)doc).createRange();
                range.setStartBefore(descriptionElement.getFirstChild());
                range.setEndAfter(descriptionElement.getLastChild());
                range.deleteContents();
                Text descriptionText = doc.createTextNode(description);
                descriptionElement.appendChild(descriptionText);
            } catch (SAXException e) {
                // Print error
                PrintWriter out = res.getWriter();
                res.setContentType("text/html");
                out.println("<HTML><BODY>Error in reading XML: " +
                    e.getMessage() + ".</BODY></HTML>");
                out.close(); 
                return;
            }
        }

        // Serialize DOM tree
        DOMSerializer serializer = new DOMSerializer();
        serializer.serialize(doc, xmlFile);

        // Print confirmation
        PrintWriter out = res.getWriter();
        res.setContentType("text/html");
        out.println("<HTML><BODY>Thank you for your submission. " +
            "Your item has been processed.</BODY></HTML>");
        out.close();