WEB项目漫谈(二)--web.xml

下面的内容主要来自以下几个链接,和其他网络内容,只是略作总结,因为每个都很长,不可能看完,看完也不可能都记住,记下来,什么后都可以翻翻看看:

http://www.jb51.net/article/19141.htm

http://mianhuaman.iteye.com/blog/1105522

http://www.cnblogs.com/konbluesky/articles/1925295.html

http://blog.csdn.net/liaoxiaohua1981/article/details/6761053

web.xml是web项目的基础配置文件,struts,spring什么的都要先配在这里,然后起作用。里面的标签主要包括

1. context-param

2. filter

3. listener

4. servlet

其他还有 session-config,distributable,welcome-file-list,error-page等

web.xml的加载顺序是context-param->listener->filter->servlet

在web项目启动时,容器首先会创建一个ServletContext,这个ServletContext初始化被整个项目所共享。context-param中的内容会转变成键值对,然后传递给ServletContext。context-param大多是用来配置一些参数,如

    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/log4j.properties</param-value>
    </context-param>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

这些内容会在稍后初始化的listener中被调用。

listener,监听类,监听web应用中的事件。最常用的接口有两个:

javax.servlet.ServletContextListener
javax.servlet.http.HttpSessionListener 

从名字就可以看出来一个用来监听servlet,一个监听session。最常被举例的应用是统计网站的在线人数,只要实现了HttpSessionListener这个接口,就必须实现sessionCreate()和sessionDestoryed()这两个方法,那么在session被创建或销毁时就会调用这两个方法,以此来实现统计。另一个比较常见的是spring的ContextLoaderListener,这个类继承了ServletContextListener接口,在应用启动时,它可以读取前面context-param中配置的contextConfigLocation,然后读取xml文件中的内容。listener的配置相对简单,如下:   

<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

filter,过滤器,对于web项目中的资源,如js,jsp等,都可以设计filter,当试图访问这些资源时会先调用相应的filter。定义一个filter类要实现javax.servlet.Filter接口,接口中有三个方法,inti(),destory(),doFilter(),在filter被创建时会调用inti(),当访问相应资源时,doFilter()方法会被调用,方法里有一个FilterChain类型的参数,顾名思义,这个参数用来实现多个filter的顺序调用。一个filter的配置分为两部分,首先定义这个filter,包括filter的name,对应的类,和类里面会用到的参数。然后定义这个filter对应的拦截资源。不难理解,filter的定义要写在filter-mapping的前面,对同一个资源,mapping的先后顺序决定filter的调用顺序:

    <filter>
        <filter-name>cachefilter</filter-name>
        <filter-class>
            com.opensymphony.oscache.web.filter.CacheFilter
        </filter-class>
        <init-param>
            <param-name>time</param-name>
            <param-value>60</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>CacheFilter</filter-name>
        <url-pattern>*.jsp</url-pattern>
    </filter-mapping>

servlet,在早前传统的WEB开发中,servlet应该是可以在web.xml中唱主角的,页端的get、post请求会到达定义好的servlet中,然后进行处理,再返回给页端。在这个WEB开发必用框架的年代,servlet应该是很少用了,也只能主体功能之外需要一些额外处理的时候会专门定义servlet。servlet的配置和filter大致相同,servlet有一个filter没有的标签是load-on-startup,它可以指定servlet的加载顺序,已经是否在项目启动时就加载。

除了上述几个主要的配置项外,还有一些小的配置项,比如<welcome-file-list>定义默认首页,<error-page>等,在开头的链接中都有很详尽的讲述。

猜你喜欢

转载自xuhuazhi.iteye.com/blog/2146556
今日推荐