web.xml详解

  我们都知web项目的运行,通常会首先加载web.xml文件,但却对web.xml文件知之甚少,今天就来揭开它的面纱,一睹它的真容!

一.web.xml是什么?

web.xml是web项目的配置文件,一般的web工程都会用到web.xml来配置,主要用来配置Listener,Filter,Servlet等。

但需要注意的是:web.xml并不是必须的,一个web工程可以没有web.xml文件

 

二.web项目加载web.xml过程

Tomcat启动web项目时,web容器就会的加载首先加载web.xml文件,

加载过程如下:

1.web项目加载web.xml,读取context-param和listener这两个结点,

2.创建一个ServletContext(Servlet上下文),整个项目会共享这个ServletContext

3.容器将<context-param>转换为键值对,并交给ServletContext

4.容器创建<listener>中的类实例,创建监听器

 

三.web.xml元素详解

首先是表明xml的使用版本。

 

<?xml version="1.0" encoding="UTF-8"?>

 

web-app是web.xml的根元素,包含着web.xml所有子元素。
xmlns以及xmlns:xsi后面引进的连接是表明web.xml引进的模式文件,便能拥有该模式的相关功能。
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

</web-app>
指明项目名称
<display-name>web-SSMTest</display-name>

web项目加载web.xml首先读取这两个结点,加载spring容器及创建spring监听器;

ApplicationContext.xml 是spring 全局配置文件,用来控制spring 特性的

ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
这个过滤器就是针对于每次浏览器请求进行过滤的
  <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>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
配置DispatcherServlet 前端控制器,加载springMVC容器
  <servlet>
    <servlet-name>SpringMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 配置springMVC需要加载的配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/springMVC.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>
  </servlet>
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
展示首页页面
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
session配置 
  <session-config>
    <session-timeout>15</session-timeout>
  </session-config>



 

posted @ 2020-03-11 17:41  长木木弓  阅读(2790)  评论(0编辑  收藏  举报