1. 程式人生 > >ssh練手(二) web.xml

ssh練手(二) web.xml

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