init-param和context-param的区别

 web工程大多都需要配置web.xml文件,web.xml文件主要用来配置Listener、Filter、Servlet等。web.xml文件包括xml文件头,DOCTYPE声明,web-app元素。


web.xml的加载过程(引用)

  在web-app元素内,元素的配置顺序与工程的加载顺序无关,web.xml的加载过程为:

1. 启动一个web项目,web容器(如tomcat)读取web.xml文件,读取其中的配置信息

2. 容器创建一个servlet上下文(servletContext),这个web项目所有部分共享这个上下文

3. 容器将转换为键值对,交给servletContext

4. 容器创建中的监听器实例

5. 触发contextInitialized方法,listener被调用(当Servlet 容器启动或终止Web 应用时,会触发ServletContextEvent 事件,该事件由ServletContextListener 来处理。在ServletContextListener 接口中定义了处理ServletContextEvent 事件的两个方法contextInitialized;contextDestroyed,web.xml有contextLoaderListener监听器,spring等框架实现了本监听器的接口方法)

6. 调用完contextInitialized方法后,容器再对filter初始化

7. 容器对web.xml中的指定load-on-startup的值为正数Servlet初始化(优先级1,2,3...->递减),负数或不指定则在该Servlet调用时初始化(springMVC的初始化为此阶段

结论:web.xml 的加载顺序:

ServletContext -> context-param(无顺序)-> listener(无顺序)-> filter(书写顺序) -> servlet(load-on-startup优先级)

web.xml文件中配置的区别

都是上下文参数,但它们的范围和使用方式不同。

是application范围内的初始化参数,用于向servlet-context提供键值对,即应用程序的上下文信息,listener、filter等初始化时会用到这些信息

是servlet范围内的参数,只能在servlet类的init()方法中取得

具体使用方法如下: 

   

          context/param   

           avalibleduring application   

  
   

   MainServlet   

   com.wes.controller.MainServlet   

       

      param1   

      avalible in servlet init()   

       

   0   

 
public class MainServlet extends HttpServlet {   

    public MainServlet() {   

        super();   

      }   

    public void init() throwsServletException {   

         System.out.println(this.getInitParameter("param1"));   

         System.out.println(getServletContext().getInitParameter("context/param"));   

       }   

}

你可能感兴趣的:(JavaWeb)