軟件藝術(shù)思考者  
          混沌,彷徨,立志,蓄勢...
          公告
          日歷
          <2025年7月>
          293012345
          6789101112
          13141516171819
          20212223242526
          272829303112
          3456789

          導(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程序的人一定對桌面程序的事件處理機制印象深刻:通過實現(xiàn)Listener接口的類可以在特定事件(Event)發(fā)生時,呼叫特定的方法來對事件進行響應(yīng)。

          其實我們在編寫JSP/Servle程序時,也有類似的事件處理機制,所不同的是在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對象為了資源利用或負載平衡等原因而必須暫時儲存至硬盤或其它儲存器時(透過對象序列化),所作的動作稱之為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ā)中很少用到這些事件處理的方面,但是在某些情況下使用事件處理機制卻可以達到事半功倍的效果,例如下面兩個例子:

          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 智者無疆 閱讀(1782) 評論(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: 博客園 模板提供:滬江博客


             觀音菩薩贊

          主站蜘蛛池模板: 宜章县| 梁河县| 金沙县| 藁城市| 灵寿县| 邢台县| 防城港市| 九龙城区| 三穗县| 西林县| 即墨市| 宝坻区| 永吉县| 偏关县| 舒兰市| 高要市| 永德县| 遵义县| 伊吾县| 泽州县| 大厂| 聂荣县| 台北市| 安西县| 阿克| 房山区| 璧山县| 洛隆县| 金溪县| 教育| 湾仔区| 大荔县| 海门市| 福州市| 图们市| 黄梅县| 香港| 北流市| 清徐县| 竹山县| 平果县|