在java工程中,web.xml用來初始化工程配置信息,好比說welcome頁面,filter,listener,servlet,servlet-mapping,啓動加載級別等等。每個xml文件都有定義格式規範的schema文件,web.xml所對應的xml Schema文件中定義了多少種標籤元素,web.xml中就能夠出現它所定義的標籤元素,也就具有哪些特定的功能。web.xml的模式文件是由Sun 公司定義的,每一個web.xml文件的根元素爲<web-app>
中,必須標明這個web.xml
使用的是哪一個模式文件。java
web.xml的根元素定義以下所示:web
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> </web-app>
下面就來介紹一下web.xml中經常使用的標籤及其功能:apache
包含兩個子元素small-icon和large-icon,指定web站臺中小圖標和大圖標的路徑服務器
<display-name>Develop Example</display-name> <description>JSP 2.0 Tech Book's Examples</description> <icon> <small-icon>/images/small.gif</small-icon> <large-icon>/images/large.gir</large-icon> </icon>
元素含有一對參數名和參數值,用做應用的servlet上下文初始化參數。參數名在整個Web應用中必須是唯一的。包含兩個子元素param-name和param-valueapp
<context-param> <param-name>param_name</param-name> <param-value>param_value</param-value> </context-param>
此所設定的參數,在JSP網頁中可使用下列方法來取得:${initParam.param_name}
jsp
若在Servlet可使用下列方法來得到:String param_name=getServletContext().getInitParamter("param_name");
url
指定Web容器中的過濾器,請求和響應對象被servlet處理以前或以後,可使用過濾器對這兩個對象進行操做。包含子元素:spa
和filter一塊兒使用,指定過濾器被映射到一個servlet或一個URL模式。和filter必須具備相同的名稱。過濾是按照部署描述符的filter-mapping元素出現的順序執行的。包含子元素:.net
<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
用於處理及響應客戶端的需求,動態生成web內容。code
用來定義servlet所對應URL,和servlet必須具備相同的名稱。
<servlet> <servlet-name>ServletName</servlet-name> <servlet-class>xxxpackage.xxxServlet</servlet-class> <!--Servlet的類--> <init-param> <!--初始化一個變量,可當作全局變量,可省略--> <param-name>參數名稱</param-name> <!--變量名稱--> <param-value>參數值</param-value> <!--變量值--> </init-param> </servlet> <servlet-mapping> <servlet-name>ServletName</servlet-name> <url-pattern>/aaa/xxx</url-pattern> <!--映射的url路徑 --> </servlet-mapping>
能夠收到事件何時發生以及用什麼做爲響應的通知
<listener> <listener-class>com.foo.hello</listener-class> </listener>
包含一個子元素welcome-file,用來定義首頁,服務器會依照設定的順序來找首頁
<welcome-file-list> <welcome-file>index.jsp</welcome-file> <welcome-file>index.htm</welcome-file> </welcome-file-list>
將錯誤代碼(Error Code)或異常(Exception)的種類對應到web應用資源路徑
<error-page> <error-code>404</error-code> <!-- http錯誤碼 --> <location>/error404.jsp</location> <!-- 在web應用內的相關資源路徑 --> </error-page> <error-page> <exception-type>java.lang.Exception</exception-type> <!-- 一個完整名稱的Java異常類型 --> <location>/except.jsp</location> </error-page>
參考: