多少人忽略的细节--web.xml解析

来源:互联网 发布:js exec 编辑:程序博客网 时间:2024/04/28 09:25

  • webxml解析
  • 命名空间
  • webxml 关键元素

web.xml解析

  • web应的初始信息的配置,大部分的mvc框架的都组要配置:过滤器、会话时间、欢迎页、错误页、控制器等。
  • 文件中也包含一系列的元素,每一个标签元素代表不同的功能;

命名空间

web xml 的命名空间遵循的是sun公司定义的Schema

  <?xml  version="1.0" encoding="UTF-8" ?>  <web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instsnce"  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee    http://java/sun/com/xml/ns/j2ee/web-app_2_4.xsd">  ...  </web-app>

上面,xml说明了XM的版本和编码方式。接着在<web-app>中指明了命名规范的Schema的来源
如果要添加其他标签的时候,需要添加到<web-app>内。

web.xml 关键元素

  1. wlcome-file-list 和welcomw-file 文件

    欢迎页通常都是在此处定义的,但是在一个项目中web.xml并不是一定存在的.java web 工程回去寻找默认的的欢迎页面,可以在<welcome-file-list><welcome-file> 中去指定,一个<welcome-file-list></welcome-file-list>可以有多个欢迎页设置。

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

上面的代码中,java工程首先会找index.jsp,如果找不到index.jsp,就会继续寻找login.jsp.
2. filter和filter-map文件

filter用来声明一个拦截器,使用该元素来拦截多个请求。

 <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>

上面 的</*>代表过滤了所有的http请求.
3. error-page 文件

虽然很多框架都提供了很好的错误处理机制,但是并不能保证对所有的错误都能进行处理。如果框架不女王处理掉错误,就会把它抛给Web容器,默认情况下,WEB容器会将原有点错误信息,返回给用户浏览器。如果不希望用用户看到错误信息,就可以在web.xml中进行设置是,可用通过error-page进行捕获Java 异常,需要在exception-type的子节点进行想指定异常。

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

两种类型的错误捕获方式.
4. listener 元素

该元素是用来注册监听类,使用子元素来指定监听程序的完整限定名
5. session-config 元素

指定会话的过期时间,下面代码的会话时间超过30分钟,session对象会自动失效。

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

将用户的关键信息放在session中,如果用户的登录时间超过session的有效时间,该信息就会丢失,这样用户就需要重新登录。
6. init-param元素
在web.xml可以定义多个init-param元素,用来定义参数。

<init-param><param-name>struts.i18n.ecoding</init-param><param-value>UTF-8<param-value></init-param>
0 0
原创粉丝点击