一、web.xml是什么
web.xml学名叫部署描述符文件,是在Servlet规范中定义的,是Web应用的配置文件,是Web应用的基础。
二、web.xml加载流程
总的来说:ServletContext——Listener——Filter——Servlet
1、首先Web容器创建一个ServletContext对象(对应JSP中的application内置对象),这个Web项目所有部分都将共享这个上下文(类似于这个项目的全局变量集合)。
2、然后Web容器以<contex-param></contex-param>中的name为键,value作为值,将其转化为键值对,存入ServletContext对象中。
3、Web容器创建<listener></listener>中的类实例,根据配置的class类路径<listener-class>来创建监听器,在监听类中会有contextInitialized(ServletContextEvent args)初始化方法,启动Web应用时,系统调用Listener的该方法,在这个方法中获得:
ServletContext application =ServletContextEvent.getServletContext();
context-param的值= application.getInitParameter("context-param的键");
得到这个context-param的值之后,你就可以做一些操作了。
举例:你可能想在项目启动之前就打开数据库,那么这里就可以在<context-param>中设置数据库的连接方式(驱动、url、user、password),在监听器中初始化数据库的连接。这个监听器是自己写的一个类,除了初始化方法,它还有销毁方法,用于关闭应用前释放资源。比如:说数据库连接的关闭,此时,调用contextDestroyed(ServletContextEvent args)销毁方法,关闭Web应用时,系统调用Listener的该方法。
4、接着,容器会读取<filter></filter>,根据指定的类路径来实例化过滤器。
5、以上都是在Web项目还没有启动完毕之前完成的工作,而Servlet时在第一次客户端向服务器发起请求时被实例化的。
本用例的配置比较简单:
<?xml version="1.0" encoding="GBK"?>
<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">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<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>
</web-app>