FileDocCategorySizeDatePackage
AddItemServlet.javaAPI DocExample5150Wed Sep 19 09:49:04 BST 2001javaxml2

AddItemServlet

public class AddItemServlet extends HttpServlet

AddItemServlet is a servlet that takes in new items and adds them to it's file-based video catalog.

Fields Summary
private static final String
CATALOG_FILE
The XML catalog file to use
Constructors Summary
Methods Summary
public voiddoGet(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res)

Accept GET requests and process through the {@link #doPost} method.


        doPost(req, res);
    
public voiddoPost(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res)

This accepts information about a new item and adds it to the internal file-based catalog, using JAXB.


                                
         
           

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

        // Get input parameters
        String id = req.getParameterValues("id")[0];
        String levelString = req.getParameterValues("level")[0];
        String title = req.getParameterValues("title")[0];
        String teacher = req.getParameterValues("teacher")[0];
        String[] guests = req.getParameterValues("guest");
        String description = req.getParameterValues("description")[0];

        // Create new item
        Item item = new Item();
        item.setId(id);
        item.setLevel(LevelType.valueOf(levelString));
        item.setTitle(title);
        item.setTeacher(teacher);
        if (guests != null) {
            for (int i=0; i<guests.length; i++) {
                if (!guests[i].trim().equals("")) {
                    item.addGuest(guests[i]);
                }
            }
        }
        item.setDescription(description);

        try {
            // Load current catalog
            File catalogFile = new File(CATALOG_FILE);
            FileReader reader = new FileReader(catalogFile);
            Catalog catalog = 
                (Catalog)Unmarshaller.unmarshal(Catalog.class, reader);

            // Add item
            catalog.addItem(item);

            // Write back out modified catalog
            FileWriter writer = new FileWriter(catalogFile);
            Marshaller.marshal(catalog, writer);

            out.println("Item added.");
        } catch (Exception e) {
            out.println("Error loading/writing catalog: " + e.getMessage());
        } finally {
            out.close();
        }