<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    軟件藝術(shù)思考者  
    混沌,彷徨,立志,蓄勢...
    公告
    日歷
    <2025年5月>
    27282930123
    45678910
    11121314151617
    18192021222324
    25262728293031
    1234567

    導(dǎo)航

    隨筆分類(86)

    隨筆檔案(85)

    搜索

    •  

    最新評論

    閱讀排行榜

    評論排行榜

     
    javax.servlet.ServletContextListener 的應(yīng)用
        ServletContextListener 一個典型的應(yīng)用就是給web程序設(shè)置一些常用的常量(例如全局的path)或者是在程序啟動的時候就去聯(lián)系數(shù)據(jù)庫。下面是一個在程序啟動時連接數(shù)據(jù)庫的例子。

       1):web.xml里。<listener>  <listener-class> com.abchina.hermes.util.StartupListener   </listener-class> </listener>
       2):

    package com.abchina.hermes.util;

    import javax.servlet.ServletContext;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    import org.apache.log4j.Logger;
    import org.springframework.context.ApplicationContext;
    import org.springframework.web.context.support.WebApplicationContextUtils;
    public class StartupListener implements ServletContextListener {
     private static Logger log = Logger.getLogger(StartupListener.class);
     public void contextDestroyed(ServletContextEvent arg0) {
     }
     public void contextInitialized(ServletContextEvent event) {
      if(log.isInfoEnabled()){
       log.info("Initialization Start..............");
      }
      ServletContext servletContext = event.getServletContext();
      // 安裝全局context和加載靜態(tài)數(shù)據(jù)
      setupContext(servletContext);
      if (log.isInfoEnabled()) {
       log.info("Initialization Complete ............. [OK]");
      }
     }
     public static void setupContext(ServletContext context) {
      ApplicationContext applicationContext = WebApplicationContextUtils
        .getRequiredWebApplicationContext(context);
      
      SpringUtil.setCtx(applicationContext);
      // 加載靜態(tài)數(shù)據(jù)
      initData(applicationContext);
     }
     /**
      * 加載靜態(tài)數(shù)據(jù)和基礎(chǔ)數(shù)據(jù)
      */
     private static void initData(ApplicationContext applicationContext) {
      // 通過統(tǒng)一的靜態(tài)參數(shù)定義
      try {
       DataItemsFactory.getMapInstance();
      } catch (Exception ex) {
       if (log.isInfoEnabled()) {
        log.info("加載靜態(tài)數(shù)據(jù)和基礎(chǔ)數(shù)據(jù)失敗......................");
       }
       ex.printStackTrace();
      }
     }

    }

    3)spring的applicationContext設(shè)置

    package com.abchina.hermes.util;

    import org.springframework.context.ApplicationContext;

    public class SpringUtil {
     public static ApplicationContext ctx;

     public static ApplicationContext getCtx() {
      return ctx;
     }

     public static void setCtx(ApplicationContext ctx) {
      SpringUtil.ctx = ctx;
     }
    }

    4)應(yīng)用applicationContext。用它可以得到注冊的service或者dao類。以便訪問數(shù)據(jù)庫

    package com.abchina.hermes.util;

    import java.io.File;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.List;
    import net.sf.json.JSONArray;
    import net.sf.json.JSONObject;
    import org.springframework.context.ApplicationContext;
    import com.abchina.hermes.platform.sysmgr.domain.CommParaClass;
    import com.abchina.hermes.platform.sysmgr.domain.CommParaValu;
    import com.abchina.hermes.platform.sysmgr.service.IDataFactoryService;
    import com.abchina.hermes.platform.sysmgr.web.vo.CommParaValuVo;
    import com.abchina.hermes.util.CommonTools;
    import com.abchina.hermes.util.AjaxUtil;
    public class DataItemsFactory {
     // 初始化Spring 工具
     private static ApplicationContext ctx;
     static {
      ctx = SpringUtil.getCtx();
     }
     private static  IDataFactoryService getdataService(){
      return (IDataFactoryService)ctx.getBean("dataService");
     }
     /**
      * dataClassid-->jsonList
      */
     private static HashMap<String, String>  dataMap=null;
     public static  HashMap<String, String> getMapInstance() {
      File dataConstantFile = new File("C:/DataConstant.java");
      
      if(dataMap==null){
       try {
       dataMap = new HashMap<String, String>(); 
          CommParaClass dataClass=new CommParaClass();
          CommParaValu data = new CommParaValu();
          List classli=getdataService().findAllClasses(dataClass);
         
          //寫文件頭
          String head =" package com.abchina.hermes.common; " +
           " public class DataConstant { ";
          FileUtil.coverToFileByFileWriter(dataConstantFile, head);
     
          for(int i=0;classli!=null&&i<classli.size();i++){
            dataClass=(CommParaClass)classli.get(i);
            CommonTools.info("...............【"+dataClass.getCP_Name()+"】分類信息..................");
    //      寫常量文件
            String comment ="/**"+dataClass.getCP_Name()+" **/";
         String strContent = comment+" public static String "+dataClass.getCP_ClasId()+" = \""+dataClass.getCP_ClasId()+"\";";
         FileUtil.appendToFileByFileWriter(dataConstantFile, strContent); 
            data.setCPV_ClasId(dataClass.getCP_ClasId());
            List datali=getdataService().getAllDataItems(data);
            List li2=new ArrayList();
         String[] key_value=null;
         for(int j=0;j<datali.size();j++){
          CommParaValuVo dataVo = (CommParaValuVo)datali.get(j);
          key_value= new String[]{dataVo.getCPV_Name(),dataVo.getST_Value()};
          String subkey ="/**"+dataClass.getCP_Name()+"-->"+dataVo.getST_Value()+" **/";
          String key = dataClass.getCP_ClasId()+"_"+dataVo.getCPV_Name();
          subkey +="public static String "+key+" = \""+dataVo.getCPV_Name()+"\";";
          FileUtil.appendToFileByFileWriter(dataConstantFile,subkey);
          li2.add(key_value);
         }
         String jsonString=AjaxUtil.getJsonString(li2);
         dataMap.put(dataClass.getCP_ClasId(), jsonString);
         
         
         
           }
          //寫文件尾部
          FileUtil.appendToFileByFileWriter(dataConstantFile, "}"+"http://更新時間:"+new Date().toLocaleString());
          } catch (RuntimeException e) {
        dataMap=null;
        e.printStackTrace();
       }
      }
      //System.out.println(dataMap.size());
         return dataMap;
     }
     /**
      *
      * 功能:刷新內(nèi)存
      * 作者:zlj
      * 日期:2009-5-19
      * 版本:0.1
      */
      public static void flashCacheMap() {
          dataMap.clear();
          dataMap = null;
          DataItemsFactory.getMapInstance();
     }
    /**
     * 得到一個數(shù)據(jù)項String。每個元素是一個json格式的數(shù)據(jù)項
     * @param classId
     * @return list
     */
     public static  String getJsonListByClassId(String classId){
      String json= getMapInstance().get(classId);
      return json;
     }
     /**
      * get a value by classid & key .||根據(jù)種類id和值 得到字符串<br/>
      * a json item example:[{'key':'01','value':'系統(tǒng)管理崗'},{'key':'02','value':'產(chǎn)品管理崗'},{'key':'03','value':'產(chǎn)品分析崗'}]
      */
     
        public static String getValueByClassIdKey(String classId,String Key){
         String jsonStr = getMapInstance().get(classId);
         String value="";
         if(jsonStr==null||Key==null)return "";
         int index =jsonStr.indexOf(Key);
         if(index>0){
          JSONArray jsons = JSONArray.fromString(jsonStr);
          for(int i =0;i<jsons.length();i++){
           JSONObject json = jsons.getJSONObject(i);
           if(json.get("key").toString().equals(Key)){
            value = json.getString("value");
           }
          }
         }
         return value;
        }
       
        /**
      * get a key by classid & value .||根據(jù)種類id和字符串 得到數(shù)據(jù)值<br/>
      * a json item example:[{'key':'01','value':'系統(tǒng)管理崗'},{'key':'02','value':'產(chǎn)品管理崗'},{'key':'03','value':'產(chǎn)品分析崗'}] 
      */
     
        public static String getKeyByClassidValue(String classId,String Value){
         String jsonStr = getMapInstance().get(classId);
         String key="";
         int index =jsonStr.indexOf(Value);
         if(index>0){
          JSONArray jsons = JSONArray.fromString(jsonStr);
          for(int i =0;i<jsons.length();i++){
           JSONObject json = jsons.getJSONObject(i);
           if(json.get("value").toString().equals(Value)){
            key = json.getString("key");
           }
          }
         }
         return key;
        }
       
        /**
         * 測試方法  test method. run it by self
         * @param args
         */
        public static void main(String[] args){
         String jsonStr="[{'key':'01','value':'系統(tǒng)管理崗'},{'key':'02','value':'產(chǎn)品管理崗'},{'key':'03','value':'產(chǎn)品分析崗'}]";
         String key="02";
         int index =jsonStr.indexOf(key);
         if(index>-1){
          String value = "";
          JSONArray jsons = JSONArray.fromString(jsonStr);
          for(int i =0;i<jsons.length();i++){
           JSONObject json = jsons.getJSONObject(i);
           if(json.get("key").toString().equals(key)){
            value = json.getString("value");
           }
          }
                System.out.println("value:"+value);
         }
         
          key="";String value="產(chǎn)品管理崗";
         int index1 =jsonStr.indexOf(value);
         if(index>0){
          JSONArray jsons = JSONArray.fromString(jsonStr);
          for(int i =0;i<jsons.length();i++){
           JSONObject json = jsons.getJSONObject(i);
           if(json.get("value").toString().equals(value)){
            key = json.getString("key");
           }
          }
          System.out.print("key:"+key);
         }
      
        }
      
    }

    下面是接活的一段網(wǎng)文
    ------------------------------------------------------------------------------------------------------------------------------------------
    JSP/Servlet 中的事件處理寫過AWT或Swing程序的人一定對桌面程序的事件處理機(jī)制印象深刻:通過實現(xiàn)Listener接口的類可以在特定事件(Event)發(fā)生時,呼叫特定的方法來對事件進(jìn)行響應(yīng)。

    其實我們在編寫JSP/Servle程序時,也有類似的事件處理機(jī)制,所不同的是在JSP/Servlet中是在web.xml中注冊Listener,由Container在特定事件發(fā)生時呼叫特定的實現(xiàn)Listener的類。


    1. Servlet中的Listener和Event:

    在JSP 2.0/Servlet 2.4中,共有八個Listener接口,六個Event類別。
    ServletContextListener接口
    [接口方法] contextInitialized()與 contextDestroyed()
    [接收事件] ServletContextEvent
    [觸發(fā)場景] 在Container加載Web應(yīng)用程序時(例如啟動 Container之后),會呼叫contextInitialized(),而當(dāng)容器移除Web應(yīng)用程序時,會呼叫contextDestroyed ()方法。

    ServletContextAttributeListener
    [接口方法] attributeAdded()、 attributeReplaced()、attributeRemoved()
    [接收事件] ServletContextAttributeEvent
    [觸發(fā)場景] 若有對象加入為application(ServletContext)對象的屬性,則會呼叫attributeAdded(),同理在置換屬性與移除屬性時,會分別呼叫attributeReplaced()、attributeRemoved()。

    HttpSessionListener
    [接口方法] sessionCreated()與sessionDestroyed ()
    [接收事件] HttpSessionEvent
    [觸發(fā)場景] 在session (HttpSession)對象建立或被消滅時,會分別呼叫這兩個方法。

    HttpSessionAttributeListener
    [接口方法] attributeAdded()、 attributeReplaced()、attributeRemoved()
    [接收事件] HttpSessionBindingEvent
    [觸發(fā)場景] 若有對象加入為session(HttpSession)對象的屬性,則會呼叫attributeAdded(),同理在置換屬性與移除屬性時,會分別呼叫attributeReplaced()、 attributeRemoved()。

    HttpSessionActivationListener
    [接口方法] sessionDidActivate()與 sessionWillPassivate()
    [接收事件] HttpSessionEvent
    [觸發(fā)場景] Activate與Passivate是用于置換對象的動作,當(dāng)session對象為了資源利用或負(fù)載平衡等原因而必須暫時儲存至硬盤或其它儲存器時(透過對象序列化),所作的動作稱之為Passivate,而硬盤或儲存器上的session對象重新加載JVM時所采的動作稱之為Activate,所以容易理解的,sessionDidActivate()與 sessionWillPassivate()分別于Activeate后與將Passivate前呼叫。

    ServletRequestListener
    [接口方法] requestInitialized()與 requestDestroyed()
    [接收事件] RequestEvent
    [觸發(fā)場景] 在request(HttpServletRequest)對象建立或被消滅時,會分別呼叫這兩個方法。

    ServletRequestAttributeListener
    [接口方法] attributeAdded()、 attributeReplaced()、attributeRemoved()
    [接收事件] HttpSessionBindingEvent
    [觸發(fā)場景] 若有對象加入為request(HttpServletRequest)對象的屬性,則會呼叫attributeAdded(),同理在置換屬性與移除屬性時,會分別呼叫attributeReplaced()、 attributeRemoved()。

    HttpSessionBindingListener
    [接口方法] valueBound()與valueUnbound()
    [接收事件] HttpSessionBindingEvent
    [觸發(fā)場景] 實現(xiàn)HttpSessionBindingListener接口的類別,其實例如果被加入至session(HttpSession)對象的屬性中,則會呼叫 valueBound(),如果被從session(HttpSession)對象的屬性中移除,則會呼叫valueUnbound(),實現(xiàn)HttpSessionBindingListener接口的類別不需在web.xml中設(shè)定。

    2. 如何注冊Servlet中的事件
    實現(xiàn)上面這幾個接口的類別,除了HttpSessionBindingListener外,必須在web.xml中向容器注冊,容器才會在對應(yīng)的事件發(fā)生時呼叫對應(yīng)的類別,如:
     < listener > 
     < listener-class > demo.servlet.listener.CustomServletContextListener </ listener-class > 
     </ listener >

    3. Servlet事件的應(yīng)用實例

    看到這里,你也許會有疑問: 了解這些 listener和event 有什么用呢?我平時開發(fā)沒有用到這些,一樣也能完成任務(wù)啊.

    不錯,在日常的開發(fā)中很少用到這些事件處理的方面,但是在某些情況下使用事件處理機(jī)制卻可以達(dá)到事半功倍的效果,例如下面兩個例子:

    4.Java類實例
    ==========
    //偵聽啟動和關(guān)閉
    import javax.servlet.ServletContextListener;
    import javax.servlet.*;

    public class TigerListen implements ServletContextListener {
     public void contextInitialized(ServletContextEvent sce)
     {
      System.out.print("Init") ;
     }
     public void contextDestroyed(ServletContextEvent sce)
     {
      System.out.print("Destroved") ;
     }
    }

    對應(yīng)的web.xml是
    ============
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.4"
     xmlns="  xmlns:xsi="  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
       <listener>
      <listener-class>TigerListen</listener-class>
     </listener>
    </web-app>

    posted on 2006-12-11 14:13 智者無疆 閱讀(1778) 評論(1)  編輯  收藏 所屬分類: about java
    評論:
    • # re: javax.servlet.ServletContextListener 的應(yīng)用   self Posted @ 2006-12-12 10:16
      2.省時省力的 Map.Entry 類
      BUILDER.COM 翻譯:Java研究組織
      13/2/2003
      URL: http://www.zdnet.com.cn/developer/code/story/0,3800066897,39107146,00.htm

      你是否已經(jīng)對每次從Map中取得關(guān)鍵字然后再取得相應(yīng)的值感覺厭倦?使用Map.Entry類,你可以得到在同一時間得到所有的信息。標(biāo)準(zhǔn)的Map訪問方法如下:

      Setkeys = map.keySet( );
      if(keys != null) {
      Iterator iterator = keys.iterator( );
      while(iterator.hasNext( )) {
      Object key = iterator.next( );
      Object value = map.get(key);
      ;....
      ;}
      }

      然后,這個方法有一個問題。從Map中取得關(guān)鍵字之后,我們必須每次重復(fù)返回到Map中取得相對的值,這是很繁瑣和費時的。

      幸運的是,這里有一個更加簡單的途徑。Map類提供了一個稱為entrySet()的方法,這個方法返回一個Map.Entry實例化后的對象集。接著,Map.Entry類提供了一個getKey()方法和一個getValue()方法,因此,上面的代碼可以被組織得更符合邏輯。舉例如下:




      Setentries = map.entrySet( );
      if(entries != null) {
      Iterator iterator = entries.iterator( );
      while(iterator.hasNext( )) {
      Map.Entry entry =iterator.next( );
      Object key = entry.getKey( );
      Object value = entry.getValue(
      );
      ;....
      }
      }

      盡管增加了一行代碼,我們卻省略了許多對Map不必要的“get”調(diào)用。同時,提供給開發(fā)人員一個同時保持了關(guān)鍵字和其對應(yīng)的值的類。Map.Entry同時也提供了一個setValue()方法,程序員可以使用它修改map里面的值。
        回復(fù)  更多評論   

     
    Copyright © 智者無疆 Powered by: 博客園 模板提供:滬江博客


       觀音菩薩贊

    主站蜘蛛池模板: 大地资源在线观看免费高清| 亚洲欧洲av综合色无码| 四虎免费永久在线播放| 伊人久久大香线蕉亚洲| 无码日韩精品一区二区免费| 特级做A爰片毛片免费看无码| 亚洲日韩在线中文字幕综合 | 亚洲国产综合AV在线观看| 亚洲日本中文字幕| 亚洲午夜未满十八勿入网站2| 免费看片A级毛片免费看| 日韩a毛片免费观看| 亚洲熟伦熟女专区hd高清| 亚洲伊人成无码综合网 | 久久精品国产精品亚洲色婷婷| 亚洲A丁香五香天堂网| 国产成人AV片无码免费| 国产VA免费精品高清在线| 99亚洲精品卡2卡三卡4卡2卡| 国产.亚洲.欧洲在线| 国产亚洲AV夜间福利香蕉149| 又爽又高潮的BB视频免费看| 看全色黄大色大片免费久久| 日本成年免费网站| 91在线老王精品免费播放| 免费视频成人手机在线观看网址| 精品久久久久久国产免费了| 一级毛片在线完整免费观看| 日韩a毛片免费观看| 一级黄色片免费观看| 有码人妻在线免费看片| 深夜福利在线免费观看| 色吊丝性永久免费看码| 一个人看的www免费在线视频| 久久国产福利免费| 久久99热精品免费观看牛牛| 久久国产精品萌白酱免费| 三年片在线观看免费大全电影 | 国产大片线上免费看| 波多野结衣久久高清免费| 手机看片久久国产免费|