web.xml文件的作用
web.xml文件是用来初始化工程的配置信息:比如Welcome页面、错误页面、servlet、servlet-mapping、过滤器、监听器、启动加载级别等。开发者可以通过此文件看到项目的基础信息。
定义文件头
头声明可以使用的XML版本和文件的字符编码(UTF-8)
DOCYTPE声明必须立即出现在此头之后。这个声明告诉服务器适用的servlet规范的版本(如2.2或2.3)并指定管理此文件其余部分内容的语法的DTD(Document Type Definition,文档类型定义)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
作为文件的开头,第一行大多数IDE都会自动写好。如果项目很简单,第二行DOCTYPE不写依然可以编译,但是IDE可能会报Warning。
根元素web-app
在标签内必须指明schema文件的版本,因为schema文件规定了web.xml的书写规则,即只能使用某一版本schema文件中已存在的标签。
<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" id="WebApp_9">
</web-app>
不同版本的schema文件的声明各不相同,只要搜索 “web.xml文件头声明各版本参考” 就能查到
web.xml文件中描述的所有元素(filter、welcome-file-list等)都要写在<web-app></web-app>之中,并且元素的书写要遵循正确的顺序,比如说filter要放在filter-mapping之前,否则Tomcat可能拒绝这份不规范的xml
这也许是一份较规范的xml文件写法
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE xml>
<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" id="WebApp_9">
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
常用配置元素
web.xml文件中可以进行许多配置设定,全部记忆还是算了,我们现用现查就好,目前找了一个比较全面的
这里仅对自己使用过的元素做些说明
filter过滤器
使用模板如下,使用的是struts2提供的过滤器类
<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>
<filter-name>
为你要使用的过滤器起一个名字,这个是自定义的,当然越规范越好,并且这个名字要求与<filter-mapping>
中的<filter-name>
一致
<filter-class>
指明这个过滤器的实现类
值得注意的是StrutsPrepareAndExecuteFilter是自Struts 2.1.3开始就替代了FilterDispatcher,所以新版本的过滤器写法见模板,是
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
2.1.3之前的版本则使用
org.apache.struts2.dispatcher.FilterDispatcher
<filter-mapping>
为已声明的过滤器指定过滤规则,在<url-pattern>
中定义过滤器负责拦截的url地址,模板中的/*表示拦截所有http请求
欢迎页welcome-file-list
使用模板如下
<welcome-file-list>
<welcome-file>index1.jsp</welcome-file>
<welcome-file>index2.jsp</welcome-file>
</welcome-file-list>
这个元素很好理解,见名知意,在列表中可以写许多网页*.jsp,如果这网页真的存在,项目就拿它作为欢迎页/首页,如果不存在就接着向下找直到找到为止。当然如果列表中一个存在的网页都没有,那就报错
错误页面error-page
使用模板如下
<error-page>
<error-code>404</error-code>
<location>/error1.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error2.jsp</location>
</error-page>
见名知意,这元素描述的是如何处理错误。
有两种方式,一种是根据错误代码(404/500等)转到特意编写的友好的页面。或者是根据抛出的异常转到相应编写的页面。