05. 屬性和監聽者

初始化參數(局部)

DD(寫在servlet裏面)

<servlet>

  <servlet-name>test2</servlet-name>

  <servlet-class>com.ou.head.InitParam</servlet-class>

  <init-param>

      <param-name>name</param-name>

      <param-value>My testinit</param-value>

  </init-param>

  </servlet>

  <servlet-mapping>

  <servlet-name>test2</servlet-name>

  <url-pattern>/test2.do</url-pattern>

  </servlet-mapping>

 

String t = getServletConfig().getInitParameter("name");

 

初始化參數(全局)

DD (寫在servlet外面)

<context-param>

    <param-name>name</param-name>

    <param-value>My testinit</param-value>

</context-param

String t =getServletContext().getInitParameter("name");

 

每個servlet有一個ServletConfig
每個Web應用有一個ServletContext


整個Web應用只有一個ServletContext,而且Web應用中的所有部分都
能訪問它。不過,應用中的各個servlet有自己的ServletConfig.部署
Web應用時,容器會建立一個ServletContext,這個上下文對Web應用
中的每個Servlet和JSP (也會成爲一個servlet) 都可用。

 

利用監聽者將初始化參數轉換爲一個對象

監聽者

 

public class MyServletLister implements ServletContextListener{

 

    public void contextInitialized(ServletContextEvent event) {

       ServletContext sc = event.getServletContext();

       String name = sc.getInitParameter("dogName");

      

       Dog dog = new Dog();

       dog.setName(name);

       sc.setAttribute("dog",dog);

    }

   

}

 

<listener>

    <listener-class>com.ou.lister.MyServletLister</listener-class>

</listener>

 

 

Servlet API中有一個ServletContextListener接口,它能夠監聽ServletContext對象的生命週期,實際上就是監聽Web應用的生命週期。

Servlet容器啓動或終止Web應用時,會觸發ServletContextEvent事件,該事件由 ServletContextListener來處理。在 ServletContextListener接口中定義了處理ServletContextEvent事件的兩個方法。

contextInitialized(ServletContextEvent sce)
:當Servlet容器啓動Web應用時調用該方法。在調用完該方法之後,容器再對Filter初始化,並且對那些在Web應用啓動時就需要被初始化的Servlet進行初始化。


contextDestroyed(ServletContextEventsce):當Servlet容器終止Web應用時調用該方法。在調用該方法之前,容器會先銷燬所有的ServletFilter過濾器。

 

 

上下文屬性不是線程安全的應該對上下文進行同步

    synchronized(getServletContext()){

           getServletContext().setAttribute(arg0, arg1);

           getServletContext().setAttribute(arg0, arg1);

          

           getServletContext().getAttribute(arg0);

           getServletContext().getAttribute(arg0);

       }

 

 

會話屬性也不是線程安全的(如果用戶打開了兩個瀏覽器的話)

synchronized(session){

           session.setAttribute(arg0, arg1);

           session.setAttribute(arg0, arg1);

          

           session.getAttribute(arg0);

           session.getAttribute(arg0);

       }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章