解读WEB工程下的web.xml配置文件

来源:互联网 发布:淘宝现在有多少卖家 编辑:程序博客网 时间:2024/05/21 01:47

1.作用: 该文件是用来配置,欢迎页、servlet、filter等的。

2.地位: web.xml文件不是创建一个工程所必须的文件,当你的工程没有用到“作用”中的功能时,可以不创建它。(在开发工具中,一般默认都会创建这个文件,网站功能复杂后,web.xm文件有非常大的用处)

3.从定义到使用这些标签: web.xml文件中出现的各种标签元素,都是由web.xml模式文件(schema)预先定义的(每个标签元素都有其特定的功能)。该模式文件是由sun公司定义的,每个web.xml文件的根元素<web-app>中,都必须标明这个web.xml使用的是哪一个模式文件。如:
<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"   version="2.5">  </web-app></span>  


4.一些常用的标签元素:

a.指定欢迎页:

 <welcome-file-list>    <welcome-file>login.jsp</welcome-file>    <welcome-file>login.jsp</welcome-file></welcome-file-list>

如果第一个存在,就显示第一个欢迎页,后面的不起作用。如果第一个不存在,就找第二个,以此类推。

(欢迎页,访问网站时,默认看到的第一个页面就是欢迎页。对于tomcat来说,当你指定一个web的根名,没有指定具体页面,去访问一个web时,若在web.xml中配置了欢迎页,那么就返回指定的页面作为欢迎页面,若没有配置欢迎页情况下,它默认先找index.html,如果找到,就把该文件作为欢迎页,若找不到,就去找index.jsp文件。找到则以此为欢迎页,若找不到,tomcat就不知道该返回什么页面,就会显示报错页面the requested resource is not available )


b.命名与定制URL(命名必须在定制URL前)。如:

先为servlet命名:

<servlet>    <servlet-name>springmvc</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class></servlet>

再定制URL:

<servlet-mapping>    <servlet-name>springmvc</servlet-name>    <url-pattern>*.do</url-pattern></servlet-mapping>


c.定制初始化参数(可以定制servlet、jsp、context的初始化参数,然后可在servlet、jsp、context中获取这些参数)

<servlet>    <servlet-name>springmvc</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <init-param>      <param-name>contextConfigLocation</param-name>      <param-value>classpath:spring-mvc.xml</param-value>    </init-param></servlet>

经过这样的配置,在servlet中能够调用getServletConfig().getInitParameter("paramName")获得参数名对应的值。


d.指定错误处理页面(可以通过异常类型或错误码来指定错误处理页面)

<error-page>    <error-code>404</error-code>    <location>/NotFound.jsp</location></error-page>-------------------------------------------<error-page>    <exception-type>java.lang.Exception<exception-type>    <location>/exception.jsp<location></error-page>


e.设置过滤器

<filter>    <filter-name>filtername</filter-name>    <filter-class>net.test.Classname</filter-class></filter><filter-mapping>    <filter-name>filtername</filter-name>    <url-pattern>/*</url-pattern></filter-mapping> 


f.设置监听器

<listener>  <listener-class>net.test.lisenetname</listener-class></listener>


g.设置会话过期时间(“秒”为单位)

<session-config>  <session-timeout>60</session-timeout></session-config>
60秒超时
除了这些常用的标签元素外,还有很多其他标签,需要可以去模式文件中查找。