Spring web.xml詳解

  web.xml文件是Java Web項目中的一個配置文件,主要用於配置歡迎頁、Filter、Listener、Servlet等,但並非必須的,一個Java Web項目沒有web.xml文件也是照樣能跑起來的。html

1. web.xml各版本區別

  首先來看一下Tomcat官網的Servlet和JSP規範規範與的Apache Tomcat版本之間的對應關係,如圖:java

  從中能夠清晰的看到不一樣版本的web.xml文件要使用相應版本的Tomcat服務器。web

  下面是各版本的web.xml配置的頭部聲明:sql

servlet 2.3

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>  
</web-app>

servlet 2.4

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
         version="2.4">
</web-app>

servlet 2.5

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
       version="2.5">
</web-app>

servlet 3.0

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
</web-app>

servlet 3.1

<?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">
</web-app>

servlet 4.0

<?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_4_0.xsd"
         version="4.0">
</web-app>

  Tomcat在激活、加載、部署web應用時,會解析加載${CATALINA_HOME}/conf目錄下全部web應用通用的web.xml,而後解析加載web應用目錄中的WEB-INF/web.xml。若是沒有WEB-INF/web.xml文件,tomcat會輸出找不到的消息,但仍然會部署並使用web應用程序,所以,這個web.xml並非必要的,不過一般最好仍是讓每個上線的web應用程序都有一個本身的WEB-INF/web.xml。數據庫

  ${CATALINA_HOME}/conf/web.xml文件中的設定會應用於全部的web應用程序,而web應用程序的WEB-INF/web.xml中的設定只應用於該應用程序自己。apache

2. web.xml配置詳解

2.1 java web項目啓動加載順序

  (1)啓動WEB項目的時候,容器(如:Tomcat)會去讀它的配置文件web.xml的兩個節點:tomcat

      <listener></listener> 和 <context-param></context-param>;安全

  (2)容器建立一個ServletContext(上下文);服務器

  (3)容器將<context-param></context-param>轉化爲鍵值對,並交給ServletContext;session

  (4)容器建立<listener></listener>中的類實例,即建立監聽;

  (5)容器初始化<filter></filter>,web.xml中能夠定義多個 filter,初始化每一個 filter 時,是按照 filter 配置節出現的順序來初始化的,當請求資源匹配多個 filter-mapping 時,filter 攔截資源是按照 filter-mapping 配置節出現的順序來依次調用 doFilter() 方法的;

  (6)容器初始化<servlet></servlet>, servlet 同 filter 相似。

  那麼,web項目啓動時,能夠知道web.xml文件各個節點的加載順序:context-param -> listener -> filter -> servlet。

2.2 web.xml中定義的元素

<web-app> 
    <display-name></display-name>定義了WEB應用的名字 
    <description></description> 聲明WEB應用的描述信息 
    
    <context-param></context-param> context-param元素聲明應用範圍內的初始化參數。 

    <filter></filter> 過濾器元素將一個名字與一個實現javax.servlet.Filter接口的類相關聯。 
    <filter-mapping></filter-mapping> 一旦命名了一個過濾器,就要利用filter-mapping元素把它與一個或多個servlet或JSP頁面相關聯。 
    
    <listener></listener>servlet API的版本2.3增長了對事件監聽程序的支持,事件監聽程序在創建、修改和刪除會話或servlet環境時獲得通知。Listener元素指出事件監聽程序類。 
    
    <servlet></servlet> 在向servlet或JSP頁面制定初始化參數或定製URL時,必須首先命名servlet或JSP頁面。Servlet元素就是用來完成此項任務的。
    <servlet-mapping></servlet-mapping> 服務器通常爲servlet提供一個缺省的URL:http://host/webAppPrefix/servlet/ServletName.
                        可是,經常會更改這個URL,以便servlet能夠訪問初始化參數或更容易地處理相對URL。在更改缺省URL時,使用servlet-mapping元素。
<session-config></session-config> 若是某個會話在必定時間內未被訪問,服務器能夠拋棄它以節省內存。 可經過使用HttpSession的setMaxInactiveInterval方法
                       明確設置單個會話對象的超時值,或者可利用session-config元素制定缺省超時值。
<mime-mapping></mime-mapping>若是Web應用具備想到特殊的文件,但願能保證給他們分配特定的MIME類型,則mime-mapping元素提供這種保證。 <welcome-file-list></welcome-file-list> 指示服務器在收到引用一個目錄名而不是文件名的URL時,使用哪一個文件。 <error-page></error-page> 在返回特定HTTP狀態代碼時,或者特定類型的異常被拋出時,可以制定將要顯示的頁面。 <taglib></taglib> 對標記庫描述符文件(Tag Libraryu Descriptor file)指定別名。此功能使你可以更改TLD文件的位置,而不用編輯使用這些文件的JSP頁面。 <resource-env-ref></resource-env-ref>聲明與資源相關的一個管理對象。 <resource-ref></resource-ref> 聲明一個資源工廠使用的外部資源。 <security-constraint></security-constraint> 制定應該保護的URL。它與login-config元素聯合使用 <login-config></login-config> 指定服務器應該怎樣給試圖訪問受保護頁面的用戶受權。它與sercurity-constraint元素聯合使用。 <security-role></security-role>給出安全角色的一個列表,這些角色將出如今servlet元素內的security-role-ref元素的role-name子元素中。
                    分別地聲明角色可以使高級IDE處理安全信息更爲容易。
<env-entry></env-entry>聲明Web應用的環境項。 <ejb-ref></ejb-ref>聲明一個EJB的主目錄的引用。 <ejb-local-ref></ejb-local-ref>聲明一個EJB的本地主目錄的應用。 </web-app>

相應元素配置:

(1)Web應用圖標

<icon> 
    <small-icon>/images/app_small.gif</small-icon> 
    <large-icon>/images/app_large.gif</large-icon> 
</icon> 

(2)Web 應用名稱

<display-name>App Name</display-name>

(3)Web 應用描述

<disciption>This is a app disciption.</disciption>

(4)上下文初始化參數

<context-param> 
    <param-name>ContextParameter</para-name> 
    <param-value>test</param-value> 
    <description>It is a test parameter.</description> 
</context-param> 

  在servlet裏面能夠經過getServletContext().getInitParameter("context/param")獲得。

(5)過濾器配置

<filter> 
    <filter-name>setCharacterEncoding</filter-name> 
    <filter-class>com.myTest.setCharacterEncodingFilter</filter-class> 
    <init-param> 
        <param-name>encoding</param-name> 
        <param-value>utf-8</param-value> 
    </init-param> 
</filter> 
<filter-mapping> 
    <filter-name>setCharacterEncoding</filter-name> 
    <url-pattern>/*</url-pattern> 
</filter-mapping>

(6)監聽器配置

<listener> 
    <listerner-class>listener.SessionListener</listener-class> 
</listener>

(7)Servlet配置

  基本配置:

<servlet> 
    <servlet-name>test</servlet-name> 
    <servlet-class>TestServlet</servlet-class> 
</servlet> 
<servlet-mapping> 
    <servlet-name>test</servlet-name> 
    <url-pattern>/test</url-pattern> 
</servlet-mapping> 

  高級配置:<servlet>

<servlet-name>test</servlet-name> 
       <servlet-class>TestServlet</servlet-class> 
       <init-param> 
           <param-name>foo</param-name> 
           <param-value>bar</param-value> 
       </init-param> 
       <run-as> 
           <description>Security role for anonymous access</description> 
           <role-name>tomcat</role-name> 
       </run-as> 
           <!-- 
                 當Web應用啓動時,裝載Servlet的次序
                 當值爲正數或零時:Servlet容器先加載數值小的servlet,再依次加載其餘數值大的servlet. 
                 當值爲負或未定義:Servlet容器將在Web客戶首次訪問這個servlet時加載它 
            -->
    <load-on-startup>1</load-on-startup>
   </servlet> 
   <servlet-mapping> 
       <servlet-name>test</servlet-name> 
       <url-pattern>/test</url-pattern> 
   </servlet-mapping>   

(8)會話超時配置(單位爲分鐘)

<session-config> 
    <session-timeout>120</session-timeout> 
</session-config> 

(9)MIME類型配置

<mime-mapping> 
    <extension>html</extension> 
    <mime-type>text/html</mime-type> 
</mime-mapping> 

(10)歡迎頁配置

<welcome-file-list> 
    <welcome-file>index.jsp</welcome-file> 
    <welcome-file>index.html</welcome-file> 
    <welcome-file>index.htm</welcome-file> 
</welcome-file-list> 

(11)配置錯誤頁面

  方法1:經過錯誤碼來配置error-page

<error-page> 
    <error-code>404</error-code> 
    <location>/404.jsp</location> 
</error-page> 

  上面的配置當系統發生404錯誤時,頁面將跳轉到錯誤處理頁面404.jsp

  方法2:經過異常類型配置error-page

<error-page> 
    <exception-type>java.lang.NullException</exception-type> 
    <location>/error.jsp</location> 
</error-page> 

  上面的配置當系統發生java.lang.NullException異常時,頁面將跳轉到錯誤處理頁面error.jsp

(12)TLD配置

<taglib> 
    <taglib-uri>http://jakarta.apache.org/tomcat/debug-taglib</taglib-uri> 
    <taglib-location>/WEB-INF/jsp/debug-taglib.tld</taglib-location> 
</taglib>
  若是MyEclipse一直在報錯,應該把<taglib>放到<jsp-config>中
<jsp-config> 
    <taglib> 
        <taglib-uri>http://jakarta.apache.org/tomcat/debug-taglib</taglib-uri> 
        <taglib-location>/WEB-INF/pager-taglib.tld</taglib-location> 
    </taglib> 
</jsp-config> 

(13)資源管理對象配置

<resource-env-ref> 
    <resource-env-ref-name>jms/StockQueue</resource-env-ref-name> 
</resource-env-ref> 

(14)資源工廠配置

<resource-ref> 
    <res-ref-name>mail/Session</res-ref-name> 
    <res-type>javax.mail.Session</res-type> 
    <res-auth>Container</res-auth> 
</resource-ref> 

    配置數據庫鏈接池就可在此配置:

<resource-ref> 
    <description>JNDI JDBC DataSource of shop</description> 
    <res-ref-name>jdbc/sample_db</res-ref-name> 
    <res-type>javax.sql.DataSource</res-type> 
    <res-auth>Container</res-auth> 
</resource-ref> 

(15)安全限制配置

<security-constraint> 
  <display-name>Example Security Constraint</display-name> 
  <web-resource-collection> 
      <web-resource-name>Protected Area</web-resource-name> 
      <url-pattern>/jsp/security/protected/*</url-pattern> 
      <http-method>DELETE</http-method> 
      <http-method>GET</http-method> 
      <http-method>POST</http-method> 
      <http-method>PUT</http-method> 
  </web-resource-collection> 
  <auth-constraint> 
      <role-name>tomcat</role-name> 
      <role-name>role1</role-name> 
  </auth-constraint> 
</security-constraint> 

(16)登錄驗證配置

<login-config> 
    <auth-method>FORM</auth-method> 
    <realm-name>Example-Based Authentiation Area</realm-name> 
    <form-login-config> 
        <form-login-page>/jsp/security/protected/login.jsp</form-login-page> 
        <form-error-page>/jsp/security/protected/error.jsp</form-error-page> 
    </form-login-config> 
</login-config> 

(17)安全角色:security-role元素給出安全角色的一個列表,這些角色將出如今servlet元素內的security-role-ref元素的role-name子元素中。分別地聲明角色可以使高級IDE處理安全信息更爲容易。

<security-role> 
    <role-name>tomcat</role-name> 
</security-role> 

(18)Web環境參數:env-entry元素聲明Web應用的環境項

<env-entry> 
    <env-entry-name>minExemptions</env-entry-name> 
    <env-entry-value>1</env-entry-value> 
    <env-entry-type>java.lang.Integer</env-entry-type> 
</env-entry>

(19)EJB 聲明

<ejb-ref> 
    <description>Example EJB reference</decription> 
    <ejb-ref-name>ejb/Account</ejb-ref-name> 
    <ejb-ref-type>Entity</ejb-ref-type> 
    <home>com.mycompany.mypackage.AccountHome</home> 
    <remote>com.mycompany.mypackage.Account</remote> 
</ejb-ref> 

(20)本地EJB聲明

<ejb-local-ref> 
    <description>Example Loacal EJB reference</decription> 
    <ejb-ref-name>ejb/ProcessOrder</ejb-ref-name> 
    <ejb-ref-type>Session</ejb-ref-type> 
    <local-home>com.mycompany.mypackage.ProcessOrderHome</local-home> 
    <local>com.mycompany.mypackage.ProcessOrder</local> 
</ejb-local-ref> 

3. web.xml示例

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
    <display-name>Sample Application</display-name>
    <description>This is a sample application</description>

    <!--context-param元素聲明應用範圍內的初始化參數。-->
    <context-param></context-param>

    <filter>
        <!--過濾器名,能夠隨便取,當web應用中有多個過濾器時不容許重名.-->
        <filter-name>SampleFilter</filter-name>
        <!--具體的過濾器的類的完整的包名+類名。注意:不能寫錯了。不然容器不能正確的實例化過濾器-->
        <filter-class>mypack.SampleFilter</filter-class>
        <init-param>
            <!-- 參數名 -->
            <param-name>initParam1</param-name>
            <!-- 參數值 -->
            <param-value>2</param-value>
        </init-param>
    </filter>
    <!-- Define the SampleFilter Mapping -->
    <filter-mapping>
        <!--過濾器名,注意要和上面的<filter-name>裏的名字同樣。-->
        <filter-name>SampleFilter</filter-name>
        <!-- 指定過濾器負責過濾的URL。這裏指定了*.jsp表示在訪問任何一個jsp頁面時都會先使用mypack.SampleFilter過濾器進行過濾。若是寫成login.jsp.則只有在訪問login.jsp時纔會調用該過濾器進行過濾。-->
        <url-pattern>*.jsp</url-pattern>
    </filter-mapping>
    <servlet>
        <!-- Servlet名字,能夠隨便取,有多個Servlet時不容許重名-->
        <servlet-name>SampleServlet</servlet-name>
        <!--指定實現這個Servlet的類。完整的包名+類名-->
        <servlet-class>mypack.SampleServlet</servlet-class>
        <!--定義Servlet的初始化參數(包括參數名和參數值)一個<servlet>元素裏能夠有多個<init-param>元素。在Servlet類中經過ServletConfig類的來訪問這些參數。
        -->
        <init-param>
            <!-- 參數名 -->
            <param-name>initParam1</param-name>
            <!-- 參數值 -->
            <param-value>2</param-value>
        </init-param>
        <!--指定當前Web應用啓動時裝載Servlet的次序。當這個數>=0時,容器會按數值從小到大依次加載。若是數值<0或沒有指定,容器將載Web客戶首次訪問這個Servlet時加載。-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!-- Define the SampleServlet Mapping -->
    <servlet-mapping>
        <!--必須和<servlet>裏的<servlet-name>內容同樣-->
        <servlet-name>SampleServlet</servlet-name>
        <!--指定訪問這個Servlet的URL。這裏給出的是對於整個Web應用的相對URL路徑。-->
        <url-pattern>/sample</url-pattern>
    </servlet-mapping>
    <session-config>
        <!--設 定HttpSession的生命週期。這裏以分鐘計算。下面的設定指明Session在最長不活動時間爲10分鐘。過了這個時間,Servlet容器將它 做爲無效處理。注意這裏和程序裏指定的計數單位不一樣,程序裏是以秒爲單位。<session-config>只有<session- timeout>這個元素-->
        <session-timeout>10</session-timeout>
    </session-config>
    <!— 配置會話偵聽器,class表示一個HttpSessionListener或 HttpSessionActivationListener 或 HttpSessionAttributeListener或
    HttpSessionBindingListener的實現類。該節點容許多個 -->
    <listener>
        <listener-class>com.cn.SessionListenerImpl</listener-class>
    </listener>
    <!-- 在 用戶訪問Web應用時,若是僅給出Web應用的根訪問URL,沒有指定具體的文件名,容器會調用<weblcome-file- list> 元素裏指定的文件清單。<welcome-file-list>裏容許有多個<welcome-file>元 素,每一個元素表明一個文件。容器會先找第一文文件件是否存在,若是存在這把這個文件返回個客戶,再也不進行其餘文件的查找。若是不存在則找第二個文件,依次 類推。若是全部文件都不存在,則跑出404錯誤-->
    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
        <welcome-file>index.htm</welcome-file>
    </welcome-file-list>
    <!-- 設置Web應用引用的自定義標籤庫。下面的代碼定義了一個/mytaglib標籤庫,它對應的TLD文件爲/WEB-INF/mytaglib.tld -->
    <taglib>
        <taglib-uri>/mytaglib</taglib-uri>
        <taglib-location>/WEB-INF/mytaglib.tld</taglib-location>
    </taglib>
    <!-- 若是Web應用訪問了由Servlet容器管理的某個JNDI Resource必須在這裏聲明對JNDI Resource的引用 -->
    <resource-ref>
        <!-- 對應用資源的說明 -->
        <description>DB Connection</description>
        <!-- 指定所引用資源的JNDI名字 -->
        <res-ref-name>jdbc/sampleDb</res-ref-name>
        <!-- 指定所引用資源的類名字 -->
        <res-type>javax.sql.DataSource</res-type>
        <!-- 指定管理所引用資源的Manager, 它有兩個可選值:Container和Application.Container表示由容器來建立和管理Resource,Application表示由Web應用來管理和建立Resource -->
        <res-auth>Container</res-auth>
    </resource-ref>
    <security-constraint>
        <web-resource-collection>
            <!-- 這個名字是必須的,由工具使用,別的地方不使用 -->
            <web-resource-name>my application</web-resource-name>
            <!-- 指定要受約束的資源,至少有一個。能夠有多個. -->
            <uri-pattern>/*</uri-pattern>
            <!-- 描 述了度可與URL模式指定的資源哪些方法是受約束的,若是沒有<http-method>元素,表示任何角色的人都沒法訪問任何http的方 法  。這裏放置了GET方法,表示只有GET方法是受約束的。其餘任何角色的人能夠訪問POST和其餘的方法。但不能訪問GET方法。-->
            <http-method>GET</http-method>
        </web-resource-collection>
        <!-- 若是沒有<auth-constraint>表示全部角色都能訪問GET方法,若是是<auth-constraint/>表示任何角色都不能訪問GET方法 -->
        <auth-constraint>
            <!-- 可選的。表示哪些角色可以在指定的資源上調用受約束的方法。這裏表示只有擁有Admin和Member角色的人可以訪問GET方法
            <security-role>>裏的<role-name>值同樣 -->
            <role-name>Admin</role-name>
            <role-name>Member</role-name>
        </auth-constraint>
    </security-constraint>
    <!-- 將指定的角色映射到web.xml裏 -->
    <security-role>
        <description>The role that is required to log into the my Application
        </description>
        <!-- 如下的角色和tomcat-users.xml裏的<tomcat-users>裏的<role rolename=""/>裏的rolename屬性值對應 -->
        <role-name>Guest</role-name>
        <role-name>Admin</role-name>
        <role-name>Member</role-name>
    </security-role>
    <!-- 若是要想進行認證,必須有<login-config>-->
    <login-config>
        <!-- 認證方式。有4種:BASIC:基本。 DIGEST:摘要。CLIENT-CERT:客戶證書(能提供最高強度的認證)。FORM:表單 -->
        <auth-method>FORM</auth-method>
        <realm-name>
            Tomcat Servet Configuraton Form-Based Authentication Area
        </realm-name>
        <form-login-config>
            <form-login-page>/login.jsp</form-login-page>
            <form-error-page>/error.jsp</form-error-page>
        </form-login-config>
    </login-config>
</web-app>
相關文章
相關標籤/搜索