Java/Servlets/Web INF XML

Материал из Java эксперт
Перейти к: навигация, поиск

A WebAppConfig object is a wrapper around a DOM tree for a web.xml file

   <source lang="java">

/*

* Copyright (c) 2004 David Flanagan.  All rights reserved.
* This code is from the book Java Examples in a Nutshell, 3nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose,
* including teaching and use in open-source projects.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book, 
* please visit http://www.davidflanagan.ru/javaexamples3.
*/

import java.io.File; import java.io.IOException; import java.io.PrintWriter; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /**

* A WebAppConfig object is a wrapper around a DOM tree for a web.xml file. The
* methods of the class use the DOM API to work with the tree in various ways.
*/

public class WebAppConfig {

 /** The main method creates and demonstrates a WebAppConfig object */
 public static void main(String[] args) throws IOException, SAXException,
     ParserConfigurationException, TransformerConfigurationException, TransformerException {
   // Create a new WebAppConfig object that represents the web.xml
   // file specified by the first command-line argument
   WebAppConfig config = new WebAppConfig(new File(args[0]));
   // Query the tree for the class name associated with the specified
   // servlet name
   System.out.println("Class for servlet " + args[1] + " is " + config.getServletClass(args[1]));
   // Add a new servlet name-to-class mapping to the DOM tree
   config.addServlet("foo", "bar");
   // And write out an XML version of the DOM tree to standard out
   config.output(new PrintWriter(System.out));
 }
 org.w3c.dom.Document document; // This field holds the parsed DOM tree
 /**
  * This constructor method is passed an XML file. It uses the JAXP API to
  * obtain a DOM parser, and to parse the file into a DOM Document object,
  * which is used by the remaining methods of the class.
  */
 public WebAppConfig(File configfile) throws IOException, SAXException,
     ParserConfigurationException {
   // Get a JAXP parser factory object
   javax.xml.parsers.DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
   // Tell the factory what kind of parser we want
   dbf.setValidating(false);
   // Use the factory to get a JAXP parser object
   javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder();
   // Tell the parser how to handle errors. Note that in the JAXP API,
   // DOM parsers rely on the SAX API for error handling
   parser.setErrorHandler(new org.xml.sax.ErrorHandler() {
     public void warning(SAXParseException e) {
       System.err.println("WARNING: " + e.getMessage());
     }
     public void error(SAXParseException e) {
       System.err.println("ERROR: " + e.getMessage());
     }
     public void fatalError(SAXParseException e) throws SAXException {
       System.err.println("FATAL: " + e.getMessage());
       throw e; // re-throw the error
     }
   });
   // Finally, use the JAXP parser to parse the file. This call returns
   // A Document object. Now that we have this object, the rest of this
   // class uses the DOM API to work with it; JAXP is no longer required.
   document = parser.parse(configfile);
 }
 /**
  * This method looks for specific Element nodes in the DOM tree in order to
  * figure out the classname associated with the specified servlet name
  */
 public String getServletClass(String servletName) {
   // Find all <servlet> elements and loop through them.
   NodeList servletnodes = document.getElementsByTagName("servlet");
   int numservlets = servletnodes.getLength();
   for (int i = 0; i < numservlets; i++) {
     Element servletTag = (Element) servletnodes.item(i);
     // Get the first <servlet-name> tag within the <servlet> tag
     Element nameTag = (Element) servletTag.getElementsByTagName("servlet-name").item(0);
     if (nameTag == null)
       continue;
     // The <servlet-name> tag should have a single child of type
     // Text. Get that child, and extract its text. Use trim()
     // to strip whitespace from the beginning and end of it.
     String name = ((Text) nameTag.getFirstChild()).getData().trim();
     // If this <servlet-name> tag has the right name
     if (servletName.equals(name)) {
       // Get the matching <servlet-class> tag
       Element classTag = (Element) servletTag.getElementsByTagName("servlet-class").item(0);
       if (classTag != null) {
         // Extract the tag"s text as above, and return it
         Text classTagContent = (Text) classTag.getFirstChild();
         return classTagContent.getNodeValue().trim();
       }
     }
   }
   // If we get here, no matching servlet name was found
   return null;
 }
 /**
  * This method adds a new name-to-class mapping in in the form of a <servlet>
  * sub-tree to the document.
  */
 public void addServlet(String servletName, String className) {
   // Create the <servlet> tag
   Element newNode = document.createElement("servlet");
   // Create the <servlet-name> and <servlet-class> tags
   Element nameNode = document.createElement("servlet-name");
   Element classNode = document.createElement("servlet-class");
   // Add the name and classname text to those tags
   nameNode.appendChild(document.createTextNode(servletName));
   classNode.appendChild(document.createTextNode(className));
   // And add those tags to the servlet tag
   newNode.appendChild(nameNode);
   newNode.appendChild(classNode);
   // Now that we"ve created the new sub-tree, figure out where to put
   // it. This code looks for another servlet tag and inserts the new
   // one right before it. Note that this code will fail if the document
   // does not already contain at least one <servlet> tag.
   NodeList servletnodes = document.getElementsByTagName("servlet");
   Element firstServlet = (Element) servletnodes.item(0);
   // Insert the new node before the first servlet node
   firstServlet.getParentNode().insertBefore(newNode, firstServlet);
 }
 /**
  * Output the DOM tree to the specified stream as an XML document. See the
  * XMLDocumentWriter example for the details.
  */
 public void output(PrintWriter out) throws TransformerConfigurationException,
     TransformerException {
   TransformerFactory factory = TransformerFactory.newInstance();
   Transformer transformer = factory.newTransformer();
   transformer.transform(new javax.xml.transform.dom.DOMSource(document),
       new javax.xml.transform.stream.StreamResult(out));
 }

}

 </source>
   
  
 
  



Define welcome files for web application

   <source lang="java">


<?xml version="1.0" encoding="UTF-8"?> <web-app

       xmlns="http://java.sun.ru/xml/ns/javaee" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xsi:schemaLocation="http://java.sun.ru/xml/ns/javaee http://java.sun.ru/xml/ns/javaee/web-app_2_5.xsd" 
       version="2.5">
   
   <welcome-file-list>
       <welcome-file>index.html</welcome-file>
       <welcome-file>index.jsp</welcome-file>
       <welcome-file>default.html</welcome-file>
       <welcome-file>default.jsp</welcome-file>
   </welcome-file-list>

</web-app>


 </source>
   
  
 
  



Init Param Servlet

   <source lang="java">

import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.io.IOException; public class InitParamServlet extends HttpServlet {

 public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException 
 {
   res.setContentType("text/plain");
   PrintWriter out = res.getWriter();
   String url = getInitParameter("URL");
   ServletConfig config = getServletConfig();
   ServletContext context = getServletContext();
   String uid = config.getInitParameter("UID");
   String pwd = config.getInitParameter("PWD");
   String port = context.getInitParameter("some-port");
   out.println("Values retrieved for the init parameters are: ");
   out.println("URL: " + url);
   out.println("UID: " + uid);
   out.println("PWD: " + pwd);
   out.println("some-port: " + port);
 }

}


 </source>
   
  
 
  



Parse a web.xml file using the SAX2 API

   <source lang="java">

/*

* Copyright (c) 2004 David Flanagan.  All rights reserved.
* This code is from the book Java Examples in a Nutshell, 3nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose,
* including teaching and use in open-source projects.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book, 
* please visit http://www.davidflanagan.ru/javaexamples3.
*/

import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /**

* Parse a web.xml file using the SAX2 API. This class extends DefaultHandler so
* that instances can serve as SAX2 event handlers, and can be notified by the
* parser of parsing events. We simply override the methods that receive events
* we"re interested in
*/

public class ListServlets extends org.xml.sax.helpers.DefaultHandler {

 /** The main method sets things up for parsing */
 public static void main(String[] args) throws IOException, SAXException,
     ParserConfigurationException {
   // We use a SAXParserFactory to obtain a SAXParser, which
   // encapsulates a SAXReader.
   SAXParserFactory factory = SAXParserFactory.newInstance();
   factory.setValidating(false); // We don"t want validation
   factory.setNamespaceAware(false); // No namespaces please
   // Create a SAXParser object from the factory
   SAXParser parser = factory.newSAXParser();
   // Now parse the file specified on the command line using
   // an instance of this class to handle the parser callbacks
   parser.parse(new File(args[0]), new ListServlets());
 }
 HashMap nameToClass; // Map from servlet name to servlet class name
 HashMap nameToID; // Map from servlet name to id attribute
 HashMap nameToPatterns; // Map from servlet name to url patterns
 StringBuffer accumulator; // Accumulate text
 String servletName, servletClass, servletPattern; // Remember text
 String servletID; // Value of id attribute of <servlet> tag
 // Called at the beginning of parsing. We use it as an init() method
 public void startDocument() {
   accumulator = new StringBuffer();
   nameToClass = new HashMap();
   nameToID = new HashMap();
   nameToPatterns = new HashMap();
 }
 // When the parser encounters plain text (not XML elements), it calls
 // this method, which accumulates them in a string buffer.
 // Note that this method may be called multiple times, even with no
 // intervening elements.
 public void characters(char[] buffer, int start, int length) {
   accumulator.append(buffer, start, length);
 }
 // At the beginning of each new element, erase any accumulated text.
 public void startElement(String namespaceURL, String localName, String qname,
     Attributes attributes) {
   accumulator.setLength(0);
   // If its a servlet tag, look for id attribute
   if (qname.equals("servlet"))
     servletID = attributes.getValue("id");
 }
 // Take special action when we reach the end of selected elements.
 // Although we don"t use a validating parser, this method does assume
 // that the web.xml file we"re parsing is valid.
 public void endElement(String namespaceURL, String localName, String qname) {
   // Since we"ve indicated that we don"t want name-space aware
   // parsing, the element name is in qname. If we were doing
   // namespaces, then qname would include the name, colon and prefix,
   // and localName would be the name without the the prefix or colon.
   if (qname.equals("servlet-name")) { // Store servlet name
     servletName = accumulator.toString().trim();
   } else if (qname.equals("servlet-class")) { // Store servlet class
     servletClass = accumulator.toString().trim();
   } else if (qname.equals("url-pattern")) { // Store servlet pattern
     servletPattern = accumulator.toString().trim();
   } else if (qname.equals("servlet")) { // Map name to class
     nameToClass.put(servletName, servletClass);
     nameToID.put(servletName, servletID);
   } else if (qname.equals("servlet-mapping")) {// Map name to pattern
     List patterns = (List) nameToPatterns.get(servletName);
     if (patterns == null) {
       patterns = new ArrayList();
       nameToPatterns.put(servletName, patterns);
     }
     patterns.add(servletPattern);
   }
 }
 // Called at the end of parsing. Used here to print our results.
 public void endDocument() {
   // Note the powerful uses of the Collections framework. In two lines
   // we get the key objects of a Map as a Set, convert them to a List,
   // and sort that List alphabetically.
   List servletNames = new ArrayList(nameToClass.keySet());
   Collections.sort(servletNames);
   // Loop through servlet names
   for (Iterator iterator = servletNames.iterator(); iterator.hasNext();) {
     String name = (String) iterator.next();
     // For each name get class and URL patterns and print them.
     String classname = (String) nameToClass.get(name);
     String id = (String) nameToID.get(name);
     List patterns = (List) nameToPatterns.get(name);
     System.out.println("Servlet: " + name);
     System.out.println("Class: " + classname);
     if (id != null)
       System.out.println("ID: " + id);
     if (patterns != null) {
       System.out.println("Patterns:");
       for (Iterator i = patterns.iterator(); i.hasNext();) {
         System.out.println("\t" + i.next());
       }
     }
     System.out.println();
   }
 }
 // Issue a warning
 public void warning(SAXParseException exception) {
   System.err
       .println("WARNING: line " + exception.getLineNumber() + ": " + exception.getMessage());
 }
 // Report a parsing error
 public void error(SAXParseException exception) {
   System.err.println("ERROR: line " + exception.getLineNumber() + ": " + exception.getMessage());
 }
 // Report a non-recoverable error and exit
 public void fatalError(SAXParseException exception) throws SAXException {
   System.err.println("FATAL: line " + exception.getLineNumber() + ": " + exception.getMessage());
   throw (exception);
 }

}

 </source>
   
  
 
  



Servlet Mapping In Web XML

Using Initialization Parameters Servlet