在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>
参考: