tomcat源码浅析(四)之web.xml解析

     Tomcat会先读取通用conf/web.xml,再读取应用程序下WEB-INF/web.xml。通用的cong/web.xml中配置了处理静态页面的org.apache.catalina.servlets.DefaultServlet和处理jsp的org.apache.jasper.servlet.JspServlet。

1.Context在start时先调用bindThread()将Loard的classLoader绑定到线程中,这样Digester在去classLoader时就可以取到Loard的classLoader。

Standardcontext.startinternal代码
  1. protected synchronized void startInternal() throws LifecycleException {  
  2.   
  3.         if (log.isDebugEnabled())  
  4.             log.debug("Starting " + getBaseName());  
  5.   
  6.         // Send j2ee.state.starting notification   
  7.         if (this.getObjectName() != null) {  
  8.             Notification notification = new Notification("j2ee.state.starting", this.getObjectName(),  
  9.                     sequenceNumber.getAndIncrement());  
  10.             broadcaster.sendNotification(notification);  
  11.         }  
  12.   
  13.         setConfigured(false);  
  14.         boolean ok = true;  
  15.   
  16.         // Currently this is effectively a NO-OP but needs to be called to  
  17.         // ensure the NamingResources follows the correct lifecycle  
  18.         if (namingResources != null) {  
  19.             namingResources.start();  
  20.         }  
  21.   
  22.         // Add missing components as necessary  
  23.         if (webappResources == null) { // (1) Required by Loader  
  24.             if (log.isDebugEnabled())  
  25.                 log.debug("Configuring default Resources");  
  26.             try {  
  27.                 String docBase = getDocBase();  
  28.                 if (docBase == null) {  
  29.                     setResources(new EmptyDirContext());  
  30.                 } else if (docBase.endsWith(".war") && !(new File(getBasePath())).isDirectory()) {  
  31.                     setResources(new WARDirContext());  
  32.                 } else {  
  33.                     setResources(new FileDirContext());  
  34.                 }  
  35.             } catch (IllegalArgumentException e) {  
  36.                 log.error(sm.getString("standardContext.resourcesInit"), e);  
  37.                 ok = false;  
  38.             }  
  39.         }  
  40.         if (ok) {  
  41.             if (!resourcesStart()) {  
  42.                 throw new LifecycleException("Error in resourceStart()");  
  43.             }  
  44.         }  
  45.   
  46.         if (getLoader() == null) {  
  47.             WebappLoader webappLoader = new WebappLoader(getParentClassLoader());  
  48.             webappLoader.setDelegate(getDelegate());  
  49.             setLoader(webappLoader);  
  50.         }  
  51.   
  52.         // Initialize character set mapper  
  53.         getCharsetMapper();  
  54.   
  55.         // Post work directory  
  56.         postWorkDirectory();  
  57.   
  58.         // Validate required extensions  
  59.         boolean dependencyCheck = true;  
  60.         try {  
  61.             dependencyCheck = ExtensionValidator.validateApplication(getResources(), this);  
  62.         } catch (IOException ioe) {  
  63.             log.error(sm.getString("standardContext.extensionValidationError"), ioe);  
  64.             dependencyCheck = false;  
  65.         }  
  66.   
  67.         if (!dependencyCheck) {  
  68.             // do not make application available if dependency check fails  
  69.             ok = false;  
  70.         }  
  71.   
  72.         // Reading the "catalina.useNaming" environment variable  
  73.         String useNamingProperty = System.getProperty("catalina.useNaming");  
  74.         if ((useNamingProperty != null) && (useNamingProperty.equals("false"))) {  
  75.             useNaming = false;  
  76.         }  
  77.   
  78.         if (ok && isUseNaming()) {  
  79.             if (getNamingContextListener() == null) {  
  80.                 NamingContextListener ncl = new NamingContextListener();  
  81.                 ncl.setName(getNamingContextName());  
  82.                 ncl.setExceptionOnFailedWrite(getJndiExceptionOnFailedWrite());  
  83.                 addLifecycleListener(ncl);  
  84.                 setNamingContextListener(ncl);  
  85.             }  
  86.         }  
  87.   
  88.         // Standard container startup  
  89.         if (log.isDebugEnabled())  
  90.             log.debug("Processing standard container startup");  
  91.   
  92.         // Binding thread  
  93.         ClassLoader oldCCL = bindThread();  
  94.   
  95.         try {  
  96.   
  97.             if (ok) {  
  98.   
  99.                 // Start our subordinate components, if any  
  100.                 if ((loader != null) && (loader instanceof Lifecycle))  
  101.                     ((Lifecycle) loader).start();  
  102.   
  103.                 // since the loader just started, the webapp classloader is now  
  104.                 // created.  
  105.                 // By calling unbindThread and bindThread in a row, we setup the  
  106.                 // current Thread CCL to be the webapp classloader  
  107.                 unbindThread(oldCCL);  
  108.                 oldCCL = bindThread();  
  109.   
  110.                 // Initialize logger again. Other components might have used it  
  111.                 // too early, so it should be reset.  
  112.                 logger = null;  
  113.                 getLogger();  
  114.   
  115.                 if ((cluster != null) && (cluster instanceof Lifecycle))  
  116.                     ((Lifecycle) cluster).start();  
  117.                 Realm realm = getRealmInternal();  
  118.                 if ((realm != null) && (realm instanceof Lifecycle))  
  119.                     ((Lifecycle) realm).start();  
  120.                 if ((resources != null) && (resources instanceof Lifecycle))  
  121.                     ((Lifecycle) resources).start();  
  122.   
  123.                 // Notify our interested LifecycleListeners  
  124.                 fireLifecycleEvent(Lifecycle.CONFIGURE_START_EVENT, null);  
  125.   
  126.                 // Start our child containers, if not already started  
  127.                 for (Container child : findChildren()) {  
  128.                     if (!child.getState().isAvailable()) {  
  129.                         child.start();  
  130.                     }  
  131.                 }  
  132.   
  133.                 // Start the Valves in our pipeline (including the basic),  
  134.                 // if any  
  135.                 if (pipeline instanceof Lifecycle) {  
  136.                     ((Lifecycle) pipeline).start();  
  137.                 }  
  138.   
  139.                 // Acquire clustered manager  
  140.                 Manager contextManager = null;  
  141.                 if (manager == null) {  
  142.                     if (log.isDebugEnabled()) {  
  143.                         log.debug(sm.getString("standardContext.cluster.noManager",  
  144.                                 Boolean.valueOf((getCluster() != null)), Boolean.valueOf(distributable)));  
  145.                     }  
  146.                     if ((getCluster() != null) && distributable) {  
  147.                         try {  
  148.                             contextManager = getCluster().createManager(getName());  
  149.                         } catch (Exception ex) {  
  150.                             log.error("standardContext.clusterFail", ex);  
  151.                             ok = false;  
  152.                         }  
  153.                     } else {  
  154.                         contextManager = new StandardManager();  
  155.                     }  
  156.                 }  
  157.   
  158.                 // Configure default manager if none was specified  
  159.                 if (contextManager != null) {  
  160.                     if (log.isDebugEnabled()) {  
  161.                         log.debug(sm.getString("standardContext.manager", contextManager.getClass().getName()));  
  162.                     }  
  163.                     setManager(contextManager);  
  164.                 }  
  165.   
  166.                 if (manager != null && (getCluster() != null) && distributable) {  
  167.                     //let the cluster know that there is a context that is distributable  
  168.                     //and that it has its own manager  
  169.                     getCluster().registerManager(manager);  
  170.                 }  
  171.             }  
  172.   
  173.         } finally {  
  174.             // Unbinding thread  
  175.             unbindThread(oldCCL);  
  176.         }  
  177.   
  178.         if (!getConfigured()) {  
  179.             log.error(sm.getString("standardContext.configurationFail"));  
  180.             ok = false;  
  181.         }  
  182.   
  183.         // We put the resources into the servlet context  
  184.         if (ok)  
  185.             getServletContext().setAttribute(Globals.RESOURCES_ATTR, getResources());  
  186.   
  187.         // Initialize associated mapper  
  188.         mapper.setContext(getPath(), welcomeFiles, resources);  
  189.   
  190.         // Binding thread  
  191.         oldCCL = bindThread();  
  192.   
  193.         if (ok) {  
  194.             if (getInstanceManager() == null) {  
  195.                 javax.naming.Context context = null;  
  196.                 if (isUseNaming() && getNamingContextListener() != null) {  
  197.                     context = getNamingContextListener().getEnvContext();  
  198.                 }  
  199.                 Map<String, Map<String, String>> injectionMap = buildInjectionMap(getIgnoreAnnotations() ? new NamingResources()  
  200.                         : getNamingResources());  
  201.                 setInstanceManager(new DefaultInstanceManager(context, injectionMap, this, this.getClass()  
  202.                         .getClassLoader()));  
  203.                 getServletContext().setAttribute(InstanceManager.class.getName(), getInstanceManager());  
  204.             }  
  205.         }  
  206.   
  207.         try {  
  208.             // Create context attributes that will be required  
  209.             if (ok) {  
  210.                 getServletContext().setAttribute(JarScanner.class.getName(), getJarScanner());  
  211.             }  
  212.   
  213.             // Set up the context init params  
  214.             mergeParameters();  
  215.   
  216.             // Call ServletContainerInitializers  
  217.             for (Map.Entry<ServletContainerInitializer, Set<Class<?>>> entry : initializers.entrySet()) {  
  218.                 try {  
  219.                     entry.getKey().onStartup(entry.getValue(), getServletContext());  
  220.                 } catch (ServletException e) {  
  221.                     log.error(sm.getString("standardContext.sciFail"), e);  
  222.                     ok = false;  
  223.                     break;  
  224.                 }  
  225.             }  
  226.   
  227.             // Configure and call application event listeners  
  228.             if (ok) {  
  229.                 if (!listenerStart()) {  
  230.                     log.error(sm.getString("standardContext.listenerFail"));  
  231.                     ok = false;  
  232.                 }  
  233.             }  
  234.   
  235.             try {  
  236.                 // Start manager  
  237.                 if ((manager != null) && (manager instanceof Lifecycle)) {  
  238.                     ((Lifecycle) getManager()).start();  
  239.                 }  
  240.             } catch (Exception e) {  
  241.                 log.error(sm.getString("standardContext.managerFail"), e);  
  242.                 ok = false;  
  243.             }  
  244.   
  245.             // Configure and call application filters  
  246.             if (ok) {  
  247.                 if (!filterStart()) {  
  248.                     log.error(sm.getString("standardContext.filterFail"));  
  249.                     ok = false;  
  250.                 }  
  251.             }  
  252.   
  253.             // Load and initialize all "load on startup" servlets  
  254.             if (ok) {  
  255.                 if (!loadOnStartup(findChildren())) {  
  256.                     log.error(sm.getString("standardContext.servletFail"));  
  257.                     ok = false;  
  258.                 }  
  259.             }  
  260.   
  261.             // Start ContainerBackgroundProcessor thread  
  262.             super.threadStart();  
  263.         } finally {  
  264.             // Unbinding thread  
  265.             unbindThread(oldCCL);  
  266.         }  
  267.   
  268.         // Set available status depending upon startup success  
  269.         if (ok) {  
  270.             if (log.isDebugEnabled())  
  271.                 log.debug("Starting completed");  
  272.         } else {  
  273.             log.error(sm.getString("standardContext.startFailed", getName()));  
  274.         }  
  275.   
  276.         startTime = System.currentTimeMillis();  
  277.   
  278.         // Send j2ee.state.running notification   
  279.         if (ok && (this.getObjectName() != null)) {  
  280.             Notification notification = new Notification("j2ee.state.running", this.getObjectName(),  
  281.                     sequenceNumber.getAndIncrement());  
  282.             broadcaster.sendNotification(notification);  
  283.         }  
  284.   
  285.         // Close all JARs right away to avoid always opening a peak number   
  286.         // of files on startup  
  287.         if (getLoader() instanceof WebappLoader) {  
  288.             ((WebappLoader) getLoader()).closeJARs(true);  
  289.         }  
  290.   
  291.         // Reinitializing if something went wrong  
  292.         if (!ok) {  
  293.             setState(LifecycleState.FAILED);  
  294.         } else {  
  295.             setState(LifecycleState.STARTING);  
  296.         }  
  297.     }  

 

Standardcontext.bindthread代码
  1. protected ClassLoader bindThread() {  
  2.   
  3.         ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();  
  4.   
  5.         if (getResources() == null)  
  6.             return oldContextClassLoader;  
  7.   
  8.         if (getLoader() != null && getLoader().getClassLoader() != null) {  
  9.             Thread.currentThread().setContextClassLoader(getLoader().getClassLoader());  
  10.         }  
  11.   
  12.         DirContextURLStreamHandler.bindThread(getResources());  
  13.   
  14.         if (isUseNaming()) {  
  15.             try {  
  16.                 ContextBindings.bindThread(this, this);  
  17.             } catch (NamingException e) {  
  18.                 // Silent catch, as this is a normal case during the early  
  19.                 // startup stages  
  20.             }  
  21.         }  
  22.   
  23.         return oldContextClassLoader;  
  24.   
  25.     }  

 

Digester.getclassloader代码
  1. public ClassLoader getClassLoader() {  
  2.   
  3.       if (this.classLoader != null) {  
  4.           return (this.classLoader);  
  5.       }  
  6.       if (this.useContextClassLoader) {  
  7.           ClassLoader classLoader =  
  8.                   Thread.currentThread().getContextClassLoader();  
  9.           if (classLoader != null) {  
  10.               return (classLoader);  
  11.           }  
  12.       }  
  13.       return (this.getClass().getClassLoader());  
  14.   
  15.   }  

 2.Context在bindThread()后触发CONFIGURE_START_EVENT事件,ContextConfig接收事件后调用configureStart方法。

Contextconfig.configurestart代码
  1. protected synchronized void configureStart() {  
  2.         // Called from StandardContext.start()  
  3.   
  4.         if (log.isDebugEnabled())  
  5.             log.debug(sm.getString("contextConfig.start"));  
  6.   
  7.         if (log.isDebugEnabled()) {  
  8.             log.debug(sm.getString("contextConfig.xmlSettings", context.getName(),  
  9.                     Boolean.valueOf(context.getXmlValidation()), Boolean.valueOf(context.getXmlNamespaceAware())));  
  10.         }  
  11.   
  12.         webConfig();  
  13.   
  14.         if (!context.getIgnoreAnnotations()) {  
  15.             applicationAnnotationsConfig();  
  16.         }  
  17.         if (ok) {  
  18.             validateSecurityRoles();  
  19.         }  
  20.   
  21.         // Configure an authenticator if we need one  
  22.         if (ok)  
  23.             authenticatorConfig();  
  24.   
  25.         // Dump the contents of this pipeline if requested  
  26.         if ((log.isDebugEnabled()) && (context instanceof ContainerBase)) {  
  27.             log.debug("Pipeline Configuration:");  
  28.             Pipeline pipeline = ((ContainerBase) context).getPipeline();  
  29.             Valve valves[] = null;  
  30.             if (pipeline != null)  
  31.                 valves = pipeline.getValves();  
  32.             if (valves != null) {  
  33.                 for (int i = 0; i < valves.length; i++) {  
  34.                     log.debug("  " + valves[i].getInfo());  
  35.                 }  
  36.             }  
  37.             log.debug("======================");  
  38.         }  
  39.   
  40.         // Make our application available if no problems were encountered  
  41.         if (ok)  
  42.             context.setConfigured(true);  
  43.         else {  
  44.             log.error(sm.getString("contextConfig.unavailable"));  
  45.             context.setConfigured(false);  
  46.         }  
  47.   
  48.     }  
Contextconfig.webconfig代码
  1. protected void webConfig() {  
  2.         /*  
  3.          * Anything and everything can override the global and host defaults.  
  4.          * This is implemented in two parts  
  5.          * - Handle as a web fragment that gets added after everything else so  
  6.          *   everything else takes priority  
  7.          * - Mark Servlets as overridable so SCI configuration can replace  
  8.          *   configuration from the defaults  
  9.          */  
  10.   
  11.         /*  
  12.          * The rules for annotation scanning are not as clear-cut as one might  
  13.          * think. Tomcat implements the following process:  
  14.          * - As per SRV.1.6.2, Tomcat will scan for annotations regardless of  
  15.          *   which Servlet spec version is declared in web.xml. The EG has  
  16.          *   confirmed this is the expected behaviour.  
  17.          * - As per http://java.net/jira/browse/SERVLET_SPEC-36, if the main  
  18.          *   web.xml is marked as metadata-complete, JARs are still processed  
  19.          *   for SCIs.  
  20.          * - If metadata-complete=true and an absolute ordering is specified,  
  21.          *   JARs excluded from the ordering are also excluded from the SCI  
  22.          *   processing.  
  23.          * - If an SCI has a @HandlesType annotation then all classes (except  
  24.          *   those in JARs excluded from an absolute ordering) need to be  
  25.          *   scanned to check if they match.  
  26.          */  
  27.         Set<WebXml> defaults = new HashSet<WebXml>();  
  28.         defaults.add(getDefaultWebXmlFragment());  
  29.   
  30.         WebXml webXml = createWebXml();  
  31.   
  32.         // Parse context level web.xml  
  33.         InputSource contextWebXml = getContextWebXmlSource();  
  34.         parseWebXml(contextWebXml, webXml, false);  
  35.   
  36.         ServletContext sContext = context.getServletContext();  
  37.   
  38.         // Ordering is important here  
  39.   
  40.         // Step 1. Identify all the JARs packaged with the application  
  41.         // If the JARs have a web-fragment.xml it will be parsed at this  
  42.         // point.  
  43.         Map<String, WebXml> fragments = processJarsForWebFragments(webXml);  
  44.   
  45.         // Step 2. Order the fragments.  
  46.         Set<WebXml> orderedFragments = null;  
  47.         orderedFragments = WebXml.orderWebFragments(webXml, fragments, sContext);  
  48.   
  49.         // Step 3. Look for ServletContainerInitializer implementations  
  50.         if (ok) {  
  51.             processServletContainerInitializers();  
  52.         }  
  53.   
  54.         if (!webXml.isMetadataComplete() || typeInitializerMap.size() > 0) {  
  55.             // Step 4. Process /WEB-INF/classes for annotations  
  56.             if (ok) {  
  57.                 // Hack required by Eclipse's "serve modules without  
  58.                 // publishing" feature since this backs WEB-INF/classes by  
  59.                 // multiple locations rather than one.  
  60.                 NamingEnumeration<Binding> listBindings = null;  
  61.                 try {  
  62.                     try {  
  63.                         listBindings = context.getResources().listBindings("/WEB-INF/classes");  
  64.                     } catch (NameNotFoundException ignore) {  
  65.                         // Safe to ignore  
  66.                     }  
  67.                     while (listBindings != null && listBindings.hasMoreElements()) {  
  68.                         Binding binding = listBindings.nextElement();  
  69.                         if (binding.getObject() instanceof FileDirContext) {  
  70.                             File webInfClassDir = new File(((FileDirContext) binding.getObject()).getDocBase());  
  71.                             processAnnotationsFile(webInfClassDir, webXml, webXml.isMetadataComplete());  
  72.                         } else if ("META-INF".equals(binding.getName())) {  
  73.                             // Skip the META-INF directory from any JARs that have been  
  74.                             // expanded in to WEB-INF/classes (sometimes IDEs do this).  
  75.                         } else {  
  76.                             String resource = "/WEB-INF/classes/" + binding.getName();  
  77.                             try {  
  78.                                 URL url = sContext.getResource(resource);  
  79.                                 processAnnotationsUrl(url, webXml, webXml.isMetadataComplete());  
  80.                             } catch (MalformedURLException e) {  
  81.                                 log.error(sm.getString("contextConfig.webinfClassesUrl", resource), e);  
  82.                             }  
  83.                         }  
  84.                     }  
  85.                 } catch (NamingException e) {  
  86.                     log.error(sm.getString("contextConfig.webinfClassesUrl""/WEB-INF/classes"), e);  
  87.                 }  
  88.             }  
  89.   
  90.             // Step 5. Process JARs for annotations - only need to process  
  91.             // those fragments we are going to use  
  92.             if (ok) {  
  93.                 processAnnotations(orderedFragments, webXml.isMetadataComplete());  
  94.             }  
  95.   
  96.             // Cache, if used, is no longer required so clear it  
  97.             javaClassCache.clear();  
  98.         }  
  99.   
  100.         if (!webXml.isMetadataComplete()) {  
  101.             // Step 6. Merge web-fragment.xml files into the main web.xml  
  102.             // file.  
  103.             if (ok) {  
  104.                 ok = webXml.merge(orderedFragments);  
  105.             }  
  106.   
  107.             // Step 7. Apply global defaults  
  108.             // Have to merge defaults before JSP conversion since defaults  
  109.             // provide JSP servlet definition.  
  110.             webXml.merge(defaults);  
  111.   
  112.             // Step 8. Convert explicitly mentioned jsps to servlets  
  113.             if (ok) {  
  114.                 convertJsps(webXml);  
  115.             }  
  116.   
  117.             // Step 9. Apply merged web.xml to Context  
  118.             if (ok) {  
  119.                 webXml.configureContext(context);  
  120.             }  
  121.         } else {  
  122.             webXml.merge(defaults);  
  123.             convertJsps(webXml);  
  124.             webXml.configureContext(context);  
  125.         }  
  126.   
  127.         // Step 9a. Make the merged web.xml available to other  
  128.         // components, specifically Jasper, to save those components  
  129.         // from having to re-generate it.  
  130.         // TODO Use a ServletContainerInitializer for Jasper  
  131.         String mergedWebXml = webXml.toXml();  
  132.         sContext.setAttribute(org.apache.tomcat.util.scan.Constants.MERGED_WEB_XML, mergedWebXml);  
  133.         if (context.getLogEffectiveWebXml()) {  
  134.             log.info("web.xml:\n" + mergedWebXml);  
  135.         }  
  136.   
  137.         // Always need to look for static resources  
  138.         // Step 10. Look for static resources packaged in JARs  
  139.         if (ok) {  
  140.             // Spec does not define an order.  
  141.             // Use ordered JARs followed by remaining JARs  
  142.             Set<WebXml> resourceJars = new LinkedHashSet<WebXml>();  
  143.             for (WebXml fragment : orderedFragments) {  
  144.                 resourceJars.add(fragment);  
  145.             }  
  146.             for (WebXml fragment : fragments.values()) {  
  147.                 if (!resourceJars.contains(fragment)) {  
  148.                     resourceJars.add(fragment);  
  149.                 }  
  150.             }  
  151.             processResourceJARs(resourceJars);  
  152.             // See also StandardContext.resourcesStart() for  
  153.             // WEB-INF/classes/META-INF/resources configuration  
  154.         }  
  155.   
  156.         // Step 11. Apply the ServletContainerInitializer config to the  
  157.         // context  
  158.         if (ok) {  
  159.             for (Map.Entry<ServletContainerInitializer, Set<Class<?>>> entry : initializerClassMap.entrySet()) {  
  160.                 if (entry.getValue().isEmpty()) {  
  161.                     context.addServletContainerInitializer(entry.getKey(), null);  
  162.                 } else {  
  163.                     context.addServletContainerInitializer(entry.getKey(), entry.getValue());  
  164.                 }  
  165.             }  
  166.         }  
  167.     }  

 

Contextconfig.parsewebxml代码
  1. protected void parseWebXml(InputSource source, WebXml dest, boolean fragment) {  
  2.   
  3.         if (source == null)  
  4.             return;  
  5.   
  6.         XmlErrorHandler handler = new XmlErrorHandler();  
  7.   
  8.         Digester digester;  
  9.         WebRuleSet ruleSet;  
  10.         if (fragment) {  
  11.             digester = webFragmentDigester;  
  12.             ruleSet = webFragmentRuleSet;  
  13.         } else {  
  14.             digester = webDigester;  
  15.             ruleSet = webRuleSet;  
  16.         }  
  17.   
  18.         digester.push(dest);  
  19.         digester.setErrorHandler(handler);  
  20.   
  21.         if (log.isDebugEnabled()) {  
  22.             log.debug(sm.getString("contextConfig.applicationStart", source.getSystemId()));  
  23.         }  
  24.   
  25.         try {  
  26.             digester.parse(source);  
  27.   
  28.             if (handler.getWarnings().size() > 0 || handler.getErrors().size() > 0) {  
  29.                 ok = false;  
  30.                 handler.logFindings(log, source.getSystemId());  
  31.             }  
  32.         } catch (SAXParseException e) {  
  33.             log.error(sm.getString("contextConfig.applicationParse", source.getSystemId()), e);  
  34.             log.error(sm.getString("contextConfig.applicationPosition""" + e.getLineNumber(),  
  35.                     "" + e.getColumnNumber()));  
  36.             ok = false;  
  37.         } catch (Exception e) {  
  38.             log.error(sm.getString("contextConfig.applicationParse", source.getSystemId()), e);  
  39.             ok = false;  
  40.         } finally {  
  41.             digester.reset();  
  42.             ruleSet.recycle();  
  43.             InputSourceUtil.close(source);  
  44.         }  
  45.     }  

 3.web的解析规则

Contextconfig.createwebxmldigester代码
  1. public void createWebXmlDigester(boolean namespaceAware, boolean validation) {  
  2.   
  3.         boolean blockExternal = context.getXmlBlockExternal();  
  4.   
  5.         webRuleSet = new WebRuleSet(false);  
  6.         webDigester = DigesterFactory.newDigester(validation, namespaceAware, webRuleSet, blockExternal);  
  7.         webDigester.getParser();  
  8.   
  9.         webFragmentRuleSet = new WebRuleSet(true);  
  10.         webFragmentDigester = DigesterFactory  
  11.                 .newDigester(validation, namespaceAware, webFragmentRuleSet, blockExternal);  
  12.         webFragmentDigester.getParser();  
  13.     }  

 

Webruleset.addruleinstances代码
  1. public void addRuleInstances(Digester digester) {  
  2.        digester.addRule(fullPrefix,  
  3.                         new SetPublicIdRule("setPublicId"));  
  4.        digester.addRule(fullPrefix,  
  5.                         new IgnoreAnnotationsRule());  
  6.        digester.addRule(fullPrefix,  
  7.                new VersionRule());  
  8.   
  9.        // Required for both fragments and non-fragments  
  10.        digester.addRule(fullPrefix + "/absolute-ordering", absoluteOrdering);  
  11.        digester.addRule(fullPrefix + "/ordering", relativeOrdering);  
  12.   
  13.        if (fragment) {  
  14.            // web-fragment.xml  
  15.            digester.addRule(fullPrefix + "/name", name);  
  16.            digester.addCallMethod(fullPrefix + "/ordering/after/name",  
  17.                                   "addAfterOrdering"0);  
  18.            digester.addCallMethod(fullPrefix + "/ordering/after/others",  
  19.                                   "addAfterOrderingOthers");  
  20.            digester.addCallMethod(fullPrefix + "/ordering/before/name",  
  21.                                   "addBeforeOrdering"0);  
  22.            digester.addCallMethod(fullPrefix + "/ordering/before/others",  
  23.                                   "addBeforeOrderingOthers");  
  24.        } else {  
  25.            // web.xml  
  26.            digester.addCallMethod(fullPrefix + "/absolute-ordering/name",  
  27.                                   "addAbsoluteOrdering"0);  
  28.            digester.addCallMethod(fullPrefix + "/absolute-ordering/others",  
  29.                                   "addAbsoluteOrderingOthers");  
  30.        }  
  31.   
  32.        digester.addCallMethod(fullPrefix + "/context-param",  
  33.                               "addContextParam"2);  
  34.        digester.addCallParam(fullPrefix + "/context-param/param-name"0);  
  35.        digester.addCallParam(fullPrefix + "/context-param/param-value"1);  
  36.   
  37.        digester.addCallMethod(fullPrefix + "/display-name",  
  38.                               "setDisplayName"0);  
  39.   
  40.        digester.addRule(fullPrefix + "/distributable",  
  41.                         new SetDistributableRule());  
  42.   
  43.        configureNamingRules(digester);  
  44.   
  45.        digester.addObjectCreate(fullPrefix + "/error-page",  
  46.                                 "org.apache.catalina.deploy.ErrorPage");  
  47.        digester.addSetNext(fullPrefix + "/error-page",  
  48.                            "addErrorPage",  
  49.                            "org.apache.catalina.deploy.ErrorPage");  
  50.   
  51.        digester.addCallMethod(fullPrefix + "/error-page/error-code",  
  52.                               "setErrorCode"0);  
  53.        digester.addCallMethod(fullPrefix + "/error-page/exception-type",  
  54.                               "setExceptionType"0);  
  55.        digester.addCallMethod(fullPrefix + "/error-page/location",  
  56.                               "setLocation"0);  
  57.   
  58.        digester.addObjectCreate(fullPrefix + "/filter",  
  59.                                 "org.apache.catalina.deploy.FilterDef");  
  60.        digester.addSetNext(fullPrefix + "/filter",  
  61.                            "addFilter",  
  62.                            "org.apache.catalina.deploy.FilterDef");  
  63.   
  64.        digester.addCallMethod(fullPrefix + "/filter/description",  
  65.                               "setDescription"0);  
  66.        digester.addCallMethod(fullPrefix + "/filter/display-name",  
  67.                               "setDisplayName"0);  
  68.        digester.addCallMethod(fullPrefix + "/filter/filter-class",  
  69.                               "setFilterClass"0);  
  70.        digester.addCallMethod(fullPrefix + "/filter/filter-name",  
  71.                               "setFilterName"0);  
  72.        digester.addCallMethod(fullPrefix + "/filter/icon/large-icon",  
  73.                               "setLargeIcon"0);  
  74.        digester.addCallMethod(fullPrefix + "/filter/icon/small-icon",  
  75.                               "setSmallIcon"0);  
  76.        digester.addCallMethod(fullPrefix + "/filter/async-supported",  
  77.                "setAsyncSupported"0);  
  78.   
  79.        digester.addCallMethod(fullPrefix + "/filter/init-param",  
  80.                               "addInitParameter"2);  
  81.        digester.addCallParam(fullPrefix + "/filter/init-param/param-name",  
  82.                              0);  
  83.        digester.addCallParam(fullPrefix + "/filter/init-param/param-value",  
  84.                              1);  
  85.   
  86.        digester.addObjectCreate(fullPrefix + "/filter-mapping",  
  87.                                 "org.apache.catalina.deploy.FilterMap");  
  88.        digester.addSetNext(fullPrefix + "/filter-mapping",  
  89.                                 "addFilterMapping",  
  90.                                 "org.apache.catalina.deploy.FilterMap");  
  91.   
  92.        digester.addCallMethod(fullPrefix + "/filter-mapping/filter-name",  
  93.                               "setFilterName"0);  
  94.        digester.addCallMethod(fullPrefix + "/filter-mapping/servlet-name",  
  95.                               "addServletName"0);  
  96.        digester.addCallMethod(fullPrefix + "/filter-mapping/url-pattern",  
  97.                               "addURLPattern"0);  
  98.   
  99.        digester.addCallMethod(fullPrefix + "/filter-mapping/dispatcher",  
  100.                               "setDispatcher"0);  
  101.   
  102.         digester.addCallMethod(fullPrefix + "/listener/listener-class",  
  103.                                "addListener"0);  
  104.           
  105.        digester.addRule(fullPrefix + "/jsp-config",  
  106.                         jspConfig);  
  107.   
  108.        digester.addObjectCreate(fullPrefix + "/jsp-config/jsp-property-group",  
  109.                                 "org.apache.catalina.deploy.JspPropertyGroup");  
  110.        digester.addSetNext(fullPrefix + "/jsp-config/jsp-property-group",  
  111.                            "addJspPropertyGroup",  
  112.                            "org.apache.catalina.deploy.JspPropertyGroup");  
  113.        digester.addCallMethod(fullPrefix + "/jsp-config/jsp-property-group/deferred-syntax-allowed-as-literal",  
  114.                               "setDeferredSyntax"0);  
  115.        digester.addCallMethod(fullPrefix + "/jsp-config/jsp-property-group/el-ignored",  
  116.                               "setElIgnored"0);  
  117.        digester.addCallMethod(fullPrefix + "/jsp-config/jsp-property-group/include-coda",  
  118.                               "addIncludeCoda"0);  
  119.        digester.addCallMethod(fullPrefix + "/jsp-config/jsp-property-group/include-prelude",  
  120.                               "addIncludePrelude"0);  
  121.        digester.addCallMethod(fullPrefix + "/jsp-config/jsp-property-group/is-xml",  
  122.                               "setIsXml"0);  
  123.        digester.addCallMethod(fullPrefix + "/jsp-config/jsp-property-group/page-encoding",  
  124.                               "setPageEncoding"0);  
  125.        digester.addCallMethod(fullPrefix + "/jsp-config/jsp-property-group/scripting-invalid",  
  126.                               "setScriptingInvalid"0);  
  127.        digester.addCallMethod(fullPrefix + "/jsp-config/jsp-property-group/trim-directive-whitespaces",  
  128.                               "setTrimWhitespace"0);  
  129.        digester.addCallMethod(fullPrefix + "/jsp-config/jsp-property-group/url-pattern",  
  130.                               "addUrlPattern"0);  
  131.        digester.addCallMethod(fullPrefix + "/jsp-config/jsp-property-group/default-content-type",  
  132.                               "setDefaultContentType"0);  
  133.        digester.addCallMethod(fullPrefix + "/jsp-config/jsp-property-group/buffer",  
  134.                               "setBuffer"0);  
  135.        digester.addCallMethod(fullPrefix + "/jsp-config/jsp-property-group/error-on-undeclared-namespace",  
  136.                               "setErrorOnUndeclaredNamespace"0);  
  137.   
  138.        digester.addRule(fullPrefix + "/login-config",  
  139.                         loginConfig);  
  140.   
  141.        digester.addObjectCreate(fullPrefix + "/login-config",  
  142.                                 "org.apache.catalina.deploy.LoginConfig");  
  143.        digester.addSetNext(fullPrefix + "/login-config",  
  144.                            "setLoginConfig",  
  145.                            "org.apache.catalina.deploy.LoginConfig");  
  146.   
  147.        digester.addCallMethod(fullPrefix + "/login-config/auth-method",  
  148.                               "setAuthMethod"0);  
  149.        digester.addCallMethod(fullPrefix + "/login-config/realm-name",  
  150.                               "setRealmName"0);  
  151.        digester.addCallMethod(fullPrefix + "/login-config/form-login-config/form-error-page",  
  152.                               "setErrorPage"0);  
  153.        digester.addCallMethod(fullPrefix + "/login-config/form-login-config/form-login-page",  
  154.                               "setLoginPage"0);  
  155.   
  156.        digester.addCallMethod(fullPrefix + "/mime-mapping",  
  157.                               "addMimeMapping"2);  
  158.        digester.addCallParam(fullPrefix + "/mime-mapping/extension"0);  
  159.        digester.addCallParam(fullPrefix + "/mime-mapping/mime-type"1);  
  160.   
  161.   
  162.        digester.addObjectCreate(fullPrefix + "/security-constraint",  
  163.                                 "org.apache.catalina.deploy.SecurityConstraint");  
  164.        digester.addSetNext(fullPrefix + "/security-constraint",  
  165.                            "addSecurityConstraint",  
  166.                            "org.apache.catalina.deploy.SecurityConstraint");  
  167.   
  168.        digester.addRule(fullPrefix + "/security-constraint/auth-constraint",  
  169.                         new SetAuthConstraintRule());  
  170.        digester.addCallMethod(fullPrefix + "/security-constraint/auth-constraint/role-name",  
  171.                               "addAuthRole"0);  
  172.        digester.addCallMethod(fullPrefix + "/security-constraint/display-name",  
  173.                               "setDisplayName"0);  
  174.        digester.addCallMethod(fullPrefix + "/security-constraint/user-data-constraint/transport-guarantee",  
  175.                               "setUserConstraint"0);  
  176.   
  177.        digester.addObjectCreate(fullPrefix + "/security-constraint/web-resource-collection",  
  178.                                 "org.apache.catalina.deploy.SecurityCollection");  
  179.        digester.addSetNext(fullPrefix + "/security-constraint/web-resource-collection",  
  180.                            "addCollection",  
  181.                            "org.apache.catalina.deploy.SecurityCollection");  
  182.        digester.addCallMethod(fullPrefix + "/security-constraint/web-resource-collection/http-method",  
  183.                               "addMethod"0);  
  184.        digester.addCallMethod(fullPrefix + "/security-constraint/web-resource-collection/http-method-omission",  
  185.                               "addOmittedMethod"0);  
  186.        digester.addCallMethod(fullPrefix + "/security-constraint/web-resource-collection/url-pattern",  
  187.                               "addPattern"0);  
  188.        digester.addCallMethod(fullPrefix + "/security-constraint/web-resource-collection/web-resource-name",  
  189.                               "setName"0);  
  190.   
  191.        digester.addCallMethod(fullPrefix + "/security-role/role-name",  
  192.                               "addSecurityRole"0);  
  193.   
  194.        digester.addRule(fullPrefix + "/servlet",  
  195.                         new ServletDefCreateRule());  
  196.        digester.addSetNext(fullPrefix + "/servlet",  
  197.                            "addServlet",  
  198.                            "org.apache.catalina.deploy.ServletDef");  
  199.   
  200.        digester.addCallMethod(fullPrefix + "/servlet/init-param",  
  201.                               "addInitParameter"2);  
  202.        digester.addCallParam(fullPrefix + "/servlet/init-param/param-name",  
  203.                              0);  
  204.        digester.addCallParam(fullPrefix + "/servlet/init-param/param-value",  
  205.                              1);  
  206.   
  207.        digester.addCallMethod(fullPrefix + "/servlet/jsp-file",  
  208.                               "setJspFile"0);  
  209.        digester.addCallMethod(fullPrefix + "/servlet/load-on-startup",  
  210.                               "setLoadOnStartup"0);  
  211.        digester.addCallMethod(fullPrefix + "/servlet/run-as/role-name",  
  212.                               "setRunAs"0);  
  213.   
  214.        digester.addObjectCreate(fullPrefix + "/servlet/security-role-ref",  
  215.                                 "org.apache.catalina.deploy.SecurityRoleRef");  
  216.        digester.addSetNext(fullPrefix + "/servlet/security-role-ref",  
  217.                            "addSecurityRoleRef",  
  218.                            "org.apache.catalina.deploy.SecurityRoleRef");  
  219.        digester.addCallMethod(fullPrefix + "/servlet/security-role-ref/role-link",  
  220.                               "setLink"0);  
  221.        digester.addCallMethod(fullPrefix + "/servlet/security-role-ref/role-name",  
  222.                               "setName"0);  
  223.   
  224.        digester.addCallMethod(fullPrefix + "/servlet/servlet-class",  
  225.                              "setServletClass"0);  
  226.        digester.addCallMethod(fullPrefix + "/servlet/servlet-name",  
  227.                              "setServletName"0);  
  228.          
  229.        digester.addObjectCreate(fullPrefix + "/servlet/multipart-config",  
  230.                                 "org.apache.catalina.deploy.MultipartDef");  
  231.        digester.addSetNext(fullPrefix + "/servlet/multipart-config",  
  232.                            "setMultipartDef",  
  233.                            "org.apache.catalina.deploy.MultipartDef");  
  234.        digester.addCallMethod(fullPrefix + "/servlet/multipart-config/location",  
  235.                               "setLocation"0);  
  236.        digester.addCallMethod(fullPrefix + "/servlet/multipart-config/max-file-size",  
  237.                               "setMaxFileSize"0);  
  238.        digester.addCallMethod(fullPrefix + "/servlet/multipart-config/max-request-size",  
  239.                               "setMaxRequestSize"0);  
  240.        digester.addCallMethod(fullPrefix + "/servlet/multipart-config/file-size-threshold",  
  241.                               "setFileSizeThreshold"0);  
  242.   
  243.        digester.addCallMethod(fullPrefix + "/servlet/async-supported",  
  244.                               "setAsyncSupported"0);  
  245.        digester.addCallMethod(fullPrefix + "/servlet/enabled",  
  246.                               "setEnabled"0);  
  247.   
  248.          
  249.        digester.addRule(fullPrefix + "/servlet-mapping",  
  250.                               new CallMethodMultiRule("addServletMapping"20));  
  251.        digester.addCallParam(fullPrefix + "/servlet-mapping/servlet-name"1);  
  252.        digester.addRule(fullPrefix + "/servlet-mapping/url-pattern", new CallParamMultiRule(0));  
  253.   
  254.        digester.addRule(fullPrefix + "/session-config", sessionConfig);  
  255.        digester.addObjectCreate(fullPrefix + "/session-config",  
  256.                                 "org.apache.catalina.deploy.SessionConfig");  
  257.        digester.addSetNext(fullPrefix + "/session-config""setSessionConfig",  
  258.                            "org.apache.catalina.deploy.SessionConfig");  
  259.        digester.addCallMethod(fullPrefix + "/session-config/session-timeout",  
  260.                               "setSessionTimeout"0);  
  261.        digester.addCallMethod(fullPrefix + "/session-config/cookie-config/name",  
  262.                               "setCookieName"0);  
  263.        digester.addCallMethod(fullPrefix + "/session-config/cookie-config/domain",  
  264.                               "setCookieDomain"0);  
  265.        digester.addCallMethod(fullPrefix + "/session-config/cookie-config/path",  
  266.                               "setCookiePath"0);  
  267.        digester.addCallMethod(fullPrefix + "/session-config/cookie-config/comment",  
  268.                               "setCookieComment"0);  
  269.        digester.addCallMethod(fullPrefix + "/session-config/cookie-config/http-only",  
  270.                               "setCookieHttpOnly"0);  
  271.        digester.addCallMethod(fullPrefix + "/session-config/cookie-config/secure",  
  272.                               "setCookieSecure"0);  
  273.        digester.addCallMethod(fullPrefix + "/session-config/cookie-config/max-age",  
  274.                               "setCookieMaxAge"0);  
  275.        digester.addCallMethod(fullPrefix + "/session-config/tracking-mode",  
  276.                               "addSessionTrackingMode"0);  
  277.   
  278.        // Taglibs pre Servlet 2.4  
  279.        digester.addRule(fullPrefix + "/taglib", new TaglibLocationRule(false));  
  280.        digester.addCallMethod(fullPrefix + "/taglib",  
  281.                               "addTaglib"2);  
  282.        digester.addCallParam(fullPrefix + "/taglib/taglib-location"1);  
  283.        digester.addCallParam(fullPrefix + "/taglib/taglib-uri"0);  
  284.   
  285.        // Taglibs Servlet 2.4 onwards  
  286.        digester.addRule(fullPrefix + "/jsp-config/taglib", new TaglibLocationRule(true));  
  287.        digester.addCallMethod(fullPrefix + "/jsp-config/taglib",  
  288.                "addTaglib"2);  
  289.        digester.addCallParam(fullPrefix + "/jsp-config/taglib/taglib-location"1);  
  290.        digester.addCallParam(fullPrefix + "/jsp-config/taglib/taglib-uri"0);  
  291.   
  292.        digester.addCallMethod(fullPrefix + "/welcome-file-list/welcome-file",  
  293.                               "addWelcomeFile"0);  
  294.   
  295.        digester.addCallMethod(fullPrefix + "/locale-encoding-mapping-list/locale-encoding-mapping",  
  296.                              "addLocaleEncodingMapping"2);  
  297.        digester.addCallParam(fullPrefix + "/locale-encoding-mapping-list/locale-encoding-mapping/locale"0);  
  298.        digester.addCallParam(fullPrefix + "/locale-encoding-mapping-list/locale-encoding-mapping/encoding"1);  
  299.   
  300.        digester.addRule(fullPrefix + "/post-construct",  
  301.                new LifecycleCallbackRule("addPostConstructMethods"2, true));  
  302.        digester.addCallParam(fullPrefix + "/post-construct/lifecycle-callback-class"0);  
  303.        digester.addCallParam(fullPrefix + "/post-construct/lifecycle-callback-method"1);  
  304.   
  305.        digester.addRule(fullPrefix + "/pre-destroy",  
  306.                new LifecycleCallbackRule("addPreDestroyMethods"2, false));  
  307.        digester.addCallParam(fullPrefix + "/pre-destroy/lifecycle-callback-class"0);  
  308.        digester.addCallParam(fullPrefix + "/pre-destroy/lifecycle-callback-method"1);  
  309.    }  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值