web.xml

来源:互联网 发布:淘宝回收十字绣靠谱吗 编辑:程序博客网 时间:2024/05/22 12:21

1)web.xml的主要作用

Web应用中的一些初始信息进行了配置。Struts2框架要先依赖于过滤器FilterDispatcher来截取Web程序的HTTP请求,再做进一步的处理。这就必须在web.xml文件中来配置FilterDispatcher过滤器。

Web,xml出来配置过滤器外,还可以用来配置<session-config>会话时间,<welcome-file-list>欢迎页,<error-page>错误页,<listener>监听器,控制器等等。

web.xml文件中含有一系列标签元素,这些标签元素是由其对应的Schema文件来定义的,因此,必须在每个web.xml文件的根元素web-app中指定其Schema文件的版本。

 

2)web.xml关键元素分析

1.welcome-file-list welcome-file元素

通常欢迎页面都在web.xml中指定,如果在访问Web应用时,只指定一个根名,而没有指定具体的页面或Action,那么Tomcat就会查看web.xml中是否指定了欢迎页面,如果指定了,则访问此访问欢迎页面;否则Tomcat默认去查找index.htmlindex.jsp页面;如果这两个页面也不存在,就会报错。

   <welcome-file-list>

     <welcome-file>standard.html</welcome-file>

   </welcome-file-list>

 

2.filter和filter-mapping元素

 

<!-- struts2过滤器 -->

 <filter>

<!-- 过滤器名称 -->

     <filter-name>struts2</filter-name>

     <!-- 过滤器类 --> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepa reAndExecuteFilter</filter-class>

 </filter>

<!-- struts2过滤器映射 -->

 <filter-mapping>

<!-- 过滤器名称 -->

     <filter-name>struts2</filter-name>

<!-- 过滤器映射 -->

     <url-pattern>*.action</url-pattern>

 </filter-mapping>

 

3.error-page元素

如果Struts框架不能处理的某种错误,就会把它抛给Web容器来处理。

<error-page>

     <error-code>404</error-code>

     <location>/error.html</location>

</error-page>

 

4.listener元素

该元素用来注册监听器类,并使用子元素listener-class指定监听程序的完整限定类名。

下面的代码设置了监听器,用于初始化Spring框架

<!-- 配置Spring监听-->

 <listener>

     <listener-class>

org.springframework.web.context.ContextLoaderListener

</listener-class>

 </listener>

 

5.session-config元素

该元素用来指定会话过期时间,下面代码表示会话超过30分钟,session对象里面存放的值会自动失效

  <!-- 配置Session -->

 <session-config>

     <session-timeout>30</session-timeout>

 </session-config>

 

6.init-param元素

该元素用来定义参数,在web.xml中可以有多个init-param元素。下面的代码使用init-param元素设置了常量:

<!-- 配置编码过滤器 -->

<filter>

     <filter-name>encodingFilter</filter-name>

    <filter-class>

org.springframework.web.filter.CharacterEncodingFilter

</filter-class>

    <init-param>

       <param-name>encoding</param-name>

       <param-value>UTF-8</param-value>

    </init-param>

 

    <init-param>

       <param-name>forceEncoding</param-name>

       <param-value>true</param-value>

    </init-param>

</filter>

 

<filter-mapping>

     <filter-name>encodingFilter</filter-name>

     <url-pattern>/*</url-pattern>

 </filter-mapping>