Why web.xml does not work when I do not use a glob

2019-07-20 04:56发布

问题:

I have this very simple web.xml file:

<?xml version="1.0" encoding="UTF-8" ?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <welcome-file-list>
        <welcome-file>testx.jsp</welcome-file>
    </welcome-file-list>
</web-app>

When I deploy the application and visit the context root, I will be taken to testx.jsp which is fine. But in my web.xml file I do not want to use a global namespace so I change the web.xml as follows:

<?xml version="1.0" encoding="UTF-8" ?>
<ee:web-app xmlns:ee="http://xmlns.jcp.org/xml/ns/javaee"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
            version="3.1">
    <ee:welcome-file-list>
        <ee:welcome-file>testx.jsp</ee:welcome-file>
    </ee:welcome-file-list>    
</ee:web-app>

Now when I again start tomcat and visit the page, I will find myself in /index instead of /testx.jsp. But why?

I am deploying the application to Tomcat Server. I tried Glassfish and I did not encounter this problem. I guess this is a Tomcat problem?

回答1:

Your XML is correct and valid, but the xmlNamespaceAware property of your Tomcat web application Context is probably set to false (default).

I was able to reproduce the behavior you describe with a web.xml that uses namespace-prefixes for the elements, like your example. After modifying the %CATALINA_HOME%/conf/context.xml to add the xmlNamespaceAware attribute set to true <Context xmlNamespaceAware="true">, the welcome-file-list behaved as expected.

https://tomcat.apache.org/tomcat-7.0-doc/config/context.html

xmlNamespaceAware

If the value of this flag is true, the parsing of web.xml and web-fragment.xml files for this web application will be namespace-aware. Note that *.tld, *.jspx and *.tagx files are always parsed using a namespace-aware parser and that the tagPlugins.xml file (if any) is never parsed using a namespace-aware parser. Note also that if you turn this flag on, you should probably also turn xmlValidation on. If the org.apache.catalina.STRICT_SERVLET_COMPLIANCE system property is set to true, the default value of this attribute will be true, else the default value will be false. Setting this attribute to true will incur a performance penalty.