天天看點

一個web項目中web.xml中context-param的作用

web.xml的配置中配置作用

  1. 啟動一個WEB項目的時候,容器(如:Tomcat)會去讀它的配置檔案web.xml.讀兩個節點: 和

    2.緊接着,容器建立一個ServletContext(上下文),這個WEB項目所有部分都将共享這個上下文.

    3.容器将轉化為鍵值對,并交給ServletContext.

    4.容器建立中的類執行個體,即建立監聽.

    5.在監聽中會有contextInitialized(ServletContextEvent args)初始化方法,在這個方法中獲得ServletContext = ServletContextEvent.getServletContext();

    context-param的值 = ServletContext.getInitParameter(“context-param的鍵”);

    6.得到這個context-param的值之後,你就可以做一些操作了.注意,這個時候你的WEB項目還沒有完全啟動完成.這個動作會比所有的Servlet都要早.

    換句話說,這個時候,你對中的鍵值做的操作,将在你的WEB項目完全啟動之前被執行.

    7.舉例.你可能想在項目啟動之前就打開資料庫.

    那麼這裡就可以在中設定資料庫的連接配接方式,在監聽類中初始化資料庫的連接配接.

    8.這個監聽是自己寫的一個類,除了初始化方法,它還有銷毀方法.用于關閉應用前釋放資源.比如說資料庫連接配接的關閉.

    如:

contextConfigLocation /WEB-INF/applicationContext.xml,/WEB-INF/action-servlet.xml,/WEB- INF/jason-servlet.xml org.springframework.web.context.ContextLoaderListener 又如: --->自定義context-param,且自定義listener來擷取這些資訊 urlrewrite false cluster false servletmapping *.bbscs poststoragemode 1 com.laoer.bbscs.web.servlet.SysListener public class SysListener extends HttpServlet implements ServletContextListener { private static final Log logger = LogFactory.getLog(SysListener.class); public void contextDestroyed(ServletContextEvent sce) { //用于在容器關閉時,操作 } //用于在容器開啟時,操作 public void contextInitialized(ServletContextEvent sce) { String rootpath = sce.getServletContext().getRealPath("/"); System.out.println("-------------rootPath:"+rootpath); if (rootpath != null) { rootpath = rootpath.replaceAll("\\\\", "/"); } else { rootpath = "/"; } if (!rootpath.endsWith("/")) { rootpath = rootpath + "/"; } Constant.ROOTPATH = rootpath; logger.info("Application Run Path:" + rootpath); String urlrewrtie = sce.getServletContext().getInitParameter("urlrewrite"); boolean burlrewrtie = false; if (urlrewrtie != null) { burlrewrtie = Boolean.parseBoolean(urlrewrtie); } Constant.USE_URL_REWRITE = burlrewrtie; logger.info("Use Urlrewrite:" + burlrewrtie); 其它略之.... } } context-param和init-param差別 web.xml裡面可以定義兩種參數: (1)application範圍内的參數,存放在servletcontext中,在web.xml中配置如下: context/param avalible during application (2)servlet範圍内的參數,隻能在servlet的init()方法中取得,在web.xml中配置如下: MainServlet com.wes.controller.MainServlet param1 avalible in servlet init() 0 在servlet中可以通過代碼分别取用: package com.wes.controller; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; public class MainServlet extends HttpServlet ...{ public MainServlet() ...{ super(); } public void init() throws ServletException ...{ System.out.println("下面的兩個參數param1是在servlet中存放的"); System.out.println(this.getInitParameter("param1")); System.out.println("下面的參數是存放在servletcontext中的"); System.out.println(getServletContext().getInitParameter("context/param")); } } 第一種參數在servlet裡面可以通過getServletContext().getInitParameter("context/param")得到 第二種參數隻能在servlet的init()方法中通過this.getInitParameter("param1")取得.