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

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

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

    JAVA學習點點滴滴

    用開放的腦子去闖蕩;用開闊的視野去拼搏;用平和的身心去磨練;用美好的理想去追求!

      BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
      18 隨筆 :: 1 文章 :: 2 評論 :: 0 Trackbacks

    2007年1月27日 #

    創(chuàng)建型模式

    1、FACTORY—追MM少不了請吃飯了,麥當勞的雞翅和肯德基的雞翅都是MM愛吃的東西,雖然口味有所不同,但不管你帶MM去麥當勞或肯德基,只管向服務員說“來四個雞翅”就行了。麥當勞和肯德基就是生產(chǎn)雞翅的Factory

    工廠模式:客戶類和工廠類分開。消費者任何時候需要某種產(chǎn)品,只需向工廠請求即可。消費者無須修改就可以接納新產(chǎn)品。缺點是當產(chǎn)品修改時,工廠類也要做相應的修改。如:如何創(chuàng)建及如何向客戶端提供。

    2、BUILDER—MM最愛聽的就是“我愛你”這句話了,見到不同地方的MM,要能夠用她們的方言跟她說這句話哦,我有一個多種語言翻譯機,上面每種語言都有一個按鍵,見到MM我只要按對應的鍵,它就能夠用相應的語言說出“我愛你”這句話了,國外的MM也可以輕松搞掂,這就是我的“我愛你”builder。(這一定比美軍在伊拉克用的翻譯機好賣)

    建造模式:將產(chǎn)品的內(nèi)部表象和產(chǎn)品的生成過程分割開來,從而使一個建造過程生成具有不同的內(nèi)部表象的產(chǎn)品對象。建造模式使得產(chǎn)品內(nèi)部表象可以獨立的變化,客戶不必知道產(chǎn)品內(nèi)部組成的細節(jié)。建造模式可以強制實行一種分步驟進行的建造過程。

    3、FACTORY METHOD—請MM去麥當勞吃漢堡,不同的MM有不同的口味,要每個都記住是一件煩人的事情,我一般采用Factory Method模式,帶著MM到服務員那兒,說“要一個漢堡”,具體要什么樣的漢堡呢,讓MM直接跟服務員說就行了。

    工廠方法模式:核心工廠類不再負責所有產(chǎn)品的創(chuàng)建,而是將具體創(chuàng)建的工作交給子類去做,成為一個抽象工廠角色,僅負責給出具體工廠類必須實現(xiàn)的接口,而不接觸哪一個產(chǎn)品類應當被實例化這種細節(jié)。

    4、PROTOTYPE—跟MM用QQ聊天,一定要說些深情的話語了,我搜集了好多肉麻的情話,需要時只要copy出來放到QQ里面就行了,這就是我的情話prototype了。(100塊錢一份,你要不要)

    原始模型模式:通過給出一個原型對象來指明所要創(chuàng)建的對象的類型,然后用復制這個原型對象的方法創(chuàng)建出更多同類型的對象。原始模型模式允許動態(tài)的增加或減少產(chǎn)品類,產(chǎn)品類不需要非得有任何事先確定的等級結構,原始模型模式適用于任何的等級結構。缺點是每一個類都必須配備一個克隆方法。

    5、SINGLETON—俺有6個漂亮的老婆,她們的老公都是我,我就是我們家里的老公Sigleton,她們只要說道“老公”,都是指的同一個人,那就是我(剛才做了個夢啦,哪有這么好的事)

    單例模式:單例模式確保某一個類只有一個實例,而且自行實例化并向整個系統(tǒng)提供這個實例單例模式。單例模式只應在有真正的“單一實例”的需求時才可使用。

    結構型模式

    6、ADAPTER—在朋友聚會上碰到了一個美女Sarah,從香港來的,可我不會說粵語,她不會說普通話,只好求助于我的朋友kent了,他作為我和Sarah之間的Adapter,讓我和Sarah可以相互交談了(也不知道他會不會耍我)

    適配器(變壓器)模式:把一個類的接口變換成客戶端所期待的另一種接口,從而使原本因接口原因不匹配而無法一起工作的兩個類能夠一起工作。適配類可以根據(jù)參數(shù)返還一個合適的實例給客戶端。

    7、BRIDGE—早上碰到MM,要說早上好,晚上碰到MM,要說晚上好;碰到MM穿了件新衣服,要說你的衣服好漂亮哦,碰到MM新做的發(fā)型,要說你的頭發(fā)好漂亮哦。不要問我“早上碰到MM新做了個發(fā)型怎么說”這種問題,自己用BRIDGE組合一下不就行了

    橋梁模式:將抽象化與實現(xiàn)化脫耦,使得二者可以獨立的變化,也就是說將他們之間的強關聯(lián)變成弱關聯(lián),也就是指在一個軟件系統(tǒng)的抽象化和實現(xiàn)化之間使用組合/聚合關系而不是繼承關系,從而使兩者可以獨立的變化。

    8、COMPOSITE—Mary今天過生日。“我過生日,你要送我一件禮物。”“嗯,好吧,去商店,你自己挑。”“這件T恤挺漂亮,買,這條裙子好看,買,這個包也不錯,買。”“喂,買了三件了呀,我只答應送一件禮物的哦。”“什么呀,T恤加裙子加包包,正好配成一套呀,小姐,麻煩你包起來。”“……”,MM都會用Composite模式了,你會了沒有?

    合成模式:合成模式將對象組織到樹結構中,可以用來描述整體與部分的關系。合成模式就是一個處理對象的樹結構的模式。合成模式把部分與整體的關系用樹結構表示出來。合成模式使得客戶端把一個個單獨的成分對象和由他們復合而成的合成對象同等看待。

    9、DECORATOR—Mary過完輪到Sarly過生日,還是不要叫她自己挑了,不然這個月伙食費肯定玩完,拿出我去年在華山頂上照的照片,在背面寫上“最好的的禮物,就是愛你的Fita”,再到街上禮品店買了個像框(賣禮品的MM也很漂亮哦),再找隔壁搞美術設計的Mike設計了一個漂亮的盒子裝起來……,我們都是Decorator,最終都在修飾我這個人呀,怎么樣,看懂了嗎?

    裝飾模式:裝飾模式以對客戶端透明的方式擴展對象的功能,是繼承關系的一個替代方案,提供比繼承更多的靈活性。動態(tài)給一個對象增加功能,這些功能可以再動態(tài)的撤消。增加由一些基本功能的排列組合而產(chǎn)生的非常大量的功能。

    10、FACADE—我有一個專業(yè)的Nikon相機,我就喜歡自己手動調(diào)光圈、快門,這樣照出來的照片才專業(yè),但MM可不懂這些,教了半天也不會。幸好相機有Facade設計模式,把相機調(diào)整到自動檔,只要對準目標按快門就行了,一切由相機自動調(diào)整,這樣MM也可以用這個相機給我拍張照片了。

    門面模式:外部與一個子系統(tǒng)的通信必須通過一個統(tǒng)一的門面對象進行。門面模式提供一個高層次的接口,使得子系統(tǒng)更易于使用。每一個子系統(tǒng)只有一個門面類,而且此門面類只有一個實例,也就是說它是一個單例模式。但整個系統(tǒng)可以有多個門面類。

    11、FLYWEIGHT—每天跟MM發(fā)短信,手指都累死了,最近買了個新手機,可以把一些常用的句子存在手機里,要用的時候,直接拿出來,在前面加上MM的名字就可以發(fā)送了,再不用一個字一個字敲了。共享的句子就是Flyweight,MM的名字就是提取出來的外部特征,根據(jù)上下文情況使用。

    享元模式:FLYWEIGHT在拳擊比賽中指最輕量級。享元模式以共享的方式高效的支持大量的細粒度對象。享元模式能做到共享的關鍵是區(qū)分內(nèi)蘊狀態(tài)和外蘊狀態(tài)。內(nèi)蘊狀態(tài)存儲在享元內(nèi)部,不會隨環(huán)境的改變而有所不同。外蘊狀態(tài)是隨環(huán)境的改變而改變的。外蘊狀態(tài)不能影響內(nèi)蘊狀態(tài),它們是相互獨立的。將可以共享的狀態(tài)和不可以共享的狀態(tài)從常規(guī)類中區(qū)分開來,將不可以共享的狀態(tài)從類里剔除出去。客戶端不可以直接創(chuàng)建被共享的對象,而應當使用一個工廠對象負責創(chuàng)建被共享的對象。享元模式大幅度的降低內(nèi)存中對象的數(shù)量。

    12、PROXY—跟MM在網(wǎng)上聊天,一開頭總是“hi,你好”,“你從哪兒來呀?”“你多大了?”“身高多少呀?”這些話,真煩人,寫個程序做為我的Proxy吧,凡是接收到這些話都設置好了自動的回答,接收到其他的話時再通知我回答,怎么樣,酷吧。

    代理模式:代理模式給某一個對象提供一個代理對象,并由代理對象控制對源對象的引用。代理就是一個人或一個機構代表另一個人或者一個機構采取行動。某些情況下,客戶不想或者不能夠直接引用一個對象,代理對象可以在客戶和目標對象直接起到中介的作用。客戶端分辨不出代理主題對象與真實主題對象。代理模式可以并不知道真正的被代理對象,而僅僅持有一個被代理對象的接口,這時候代理對象不能夠創(chuàng)建被代理對象,被代理對象必須有系統(tǒng)的其他角色代為創(chuàng)建并傳入。

    行為模式

    13、CHAIN OF RESPONSIBLEITY—晚上去上英語課,為了好開溜坐到了最后一排,哇,前面坐了好幾個漂亮的MM哎,找張紙條,寫上“Hi,可以做我的女朋友嗎?如果不愿意請向前傳”,紙條就一個接一個的傳上去了,糟糕,傳到第一排的MM把紙條傳給老師了,聽說是個老處女呀,快跑!

    責任鏈模式:在責任鏈模式中,很多對象由每一個對象對其下家的引用而接

    起來形成一條鏈。請求在這個鏈上傳遞,直到鏈上的某一個對象決定處理此請求。客戶并不知道鏈上的哪一個對象最終處理這個請求,系統(tǒng)可以在不影響客戶端的情況下動態(tài)的重新組織鏈和分配責任。處理者有兩個選擇:承擔責任或者把責任推給下家。一個請求可以最終不被任何接收端對象所接受。
    14、COMMAND—俺有一個MM家里管得特別嚴,沒法見面,只好借助于她弟弟在我們倆之間傳送信息,她對我有什么指示,就寫一張紙條讓她弟弟帶給我。這不,她弟弟又傳送過來一個COMMAND,為了感謝他,我請他吃了碗雜醬面,哪知道他說:“我同時給我姐姐三個男朋友送COMMAND,就數(shù)你最小氣,才請我吃面。”,:-(

    命令模式:命令模式把一個請求或者操作封裝到一個對象中。命令模式把發(fā)出命令的責任和執(zhí)行命令的責任分割開,委派給不同的對象。命令模式允許請求的一方和發(fā)送的一方獨立開來,使得請求的一方不必知道接收請求的一方的接口,更不必知道請求是怎么被接收,以及操作是否執(zhí)行,何時被執(zhí)行以及是怎么被執(zhí)行的。系統(tǒng)支持命令的撤消。

    15、INTERPRETER—俺有一個《泡MM真經(jīng)》,上面有各種泡MM的攻略,比如說去吃西餐的步驟、去看電影的方法等等,跟MM約會時,只要做一個Interpreter,照著上面的腳本執(zhí)行就可以了。

    解釋器模式:給定一個語言后,解釋器模式可以定義出其文法的一種表示,并同時提供一個解釋器。客戶端可以使用這個解釋器來解釋這個語言中的句子。解釋器模式將描述怎樣在有了一個簡單的文法后,使用模式設計解釋這些語句。在解釋器模式里面提到的語言是指任何解釋器對象能夠解釋的任何組合。在解釋器模式中需要定義一個代表文法的命令類的等級結構,也就是一系列的組合規(guī)則。每一個命令對象都有一個解釋方法,代表對命令對象的解釋。命令對象的等級結構中的對象的任何排列組合都是一個語言。

    ?

    16、ITERATOR—我愛上了Mary,不顧一切的向她求婚。

    Mary:“想要我跟你結婚,得答應我的條件”

    我:“什么條件我都答應,你說吧”

    Mary:“我看上了那個一克拉的鉆石”

    我:“我買,我買,還有嗎?”

    Mary:“我看上了湖邊的那棟別墅”

    我:“我買,我買,還有嗎?”

    Mary:“你的小弟弟必須要有50cm長”

    我腦袋嗡的一聲,坐在椅子上,一咬牙:“我剪,我剪,還有嗎?”

    ……

    迭代子模式:迭代子模式可以順序訪問一個聚集中的元素而不必暴露聚集的內(nèi)部表象。多個對象聚在一起形成的總體稱之為聚集,聚集對象是能夠包容一組對象的容器對象。迭代子模式將迭代邏輯封裝到一個獨立的子對象中,從而與聚集本身隔開。迭代子模式簡化了聚集的界面。每一個聚集對象都可以有一個或一個以上的迭代子對象,每一個迭代子的迭代狀態(tài)可以是彼此獨立的。迭代算法可以獨立于聚集角色變化。

    17、MEDIATOR—四個MM打麻將,相互之間誰應該給誰多少錢算不清楚了,幸虧當時我在旁邊,按照各自的籌碼數(shù)算錢,賺了錢的從我這里拿,賠了錢的也付給我,一切就OK啦,俺得到了四個MM的電話。

    調(diào)停者模式:調(diào)停者模式包裝了一系列對象相互作用的方式,使得這些對象不必相互明顯作用。從而使他們可以松散偶合。當某些對象之間的作用發(fā)生改變時,不會立即影響其他的一些對象之間的作用。保證這些作用可以彼此獨立的變化。調(diào)停者模式將多對多的相互作用轉化為一對多的相互作用。調(diào)停者模式將對象的行為和協(xié)作抽象化,把對象在小尺度的行為上與其他對象的相互作用分開處理。

    18、MEMENTO—同時跟幾個MM聊天時,一定要記清楚剛才跟MM說了些什么話,不然MM發(fā)現(xiàn)了會不高興的哦,幸虧我有個備忘錄,剛才與哪個MM說了什么話我都拷貝一份放到備忘錄里面保存,這樣可以隨時察看以前的記錄啦。

    備忘錄模式:備忘錄對象是一個用來存儲另外一個對象內(nèi)部狀態(tài)的快照的對象。備忘錄模式的用意是在不破壞封裝的條件下,將一個對象的狀態(tài)捉住,并外部化,存儲起來,從而可以在將來合適的時候把這個對象還原到存儲起來的狀態(tài)。

    19、OBSERVER—想知道咱們公司最新MM情報嗎?加入公司的MM情報郵件組就行了,tom負責搜集情報,他發(fā)現(xiàn)的新情報不用一個一個通知我們,直接發(fā)布給郵件組,我們作為訂閱者(觀察者)就可以及時收到情報啦

    觀察者模式:觀察者模式定義了一種一隊多的依賴關系,讓多個觀察者對象同時監(jiān)聽某一個主題對象。這個主題對象在狀態(tài)上發(fā)生變化時,會通知所有觀察者對象,使他們能夠自動更新自己。

    20、STATE—跟MM交往時,一定要注意她的狀態(tài)哦,在不同的狀態(tài)時她的行為會有不同,比如你約她今天晚上去看電影,對你沒興趣的MM就會說“有事情啦”,對你不討厭但還沒喜歡上的MM就會說“好啊,不過可以帶上我同事么?”,已經(jīng)喜歡上你的MM就會說“幾點鐘?看完電影再去泡吧怎么樣?”,當然你看電影過程中表現(xiàn)良好的話,也可以把MM的狀態(tài)從不討厭不喜歡變成喜歡哦。

    狀態(tài)模式:狀態(tài)模式允許一個對象在其內(nèi)部狀態(tài)改變的時候改變行為。這個對象看上去象是改變了它的類一樣。狀態(tài)模式把所研究的對象的行為包裝在不同的狀態(tài)對象里,每一個狀態(tài)對象都屬于一個抽象狀態(tài)類的一個子類。狀態(tài)模式的意圖是讓一個對象在其內(nèi)部狀態(tài)改變的時候,其行為也隨之改變。狀態(tài)模式需要對每一個系統(tǒng)可能取得的狀態(tài)創(chuàng)立一個狀態(tài)類的子類。當系統(tǒng)的狀態(tài)變化時,系統(tǒng)便改變所選的子類。

    ?? 21、STRATEGY—跟不同類型的MM約會,要用不同的策略,有的請電影比較好,有的則去吃小吃效果不錯,有的去海邊浪漫最合適,單目的都是為了得到MM的芳心,我的追MM錦囊中有好多Strategy哦。

    策略模式:策略模式針對一組算法,將每一個算法封裝到具有共同接口的獨立的類中,從而使得它們可以相互替換。策略模式使得算法可以在不影響到客戶端的情況下發(fā)生變化。策略模式把行為和環(huán)境分開。環(huán)境類負責維持和查詢行為類,各種算法在具體的策略類中提供。由于算法和環(huán)境獨立開來,算法的增減,修改都不會影響到環(huán)境和客戶端。

    22、TEMPLATE METHOD——看過《如何說服女生上床》這部經(jīng)典文章嗎?女生從認識到上床的不變的步驟分為巧遇、打破僵局、展開追求、接吻、前戲、動手、愛撫、進去八大步驟(Template method),但每個步驟針對不同的情況,都有不一樣的做法,這就要看你隨機應變啦(具體實現(xiàn));

    模板方法模式:模板方法模式準備一個抽象類,將部分邏輯以具體方法以及具體構造子的形式實現(xiàn),然后聲明一些抽象方法來迫使子類實現(xiàn)剩余的邏輯。不同的子類可以以不同的方式實現(xiàn)這些抽象方法,從而對剩余的邏輯有不同的實現(xiàn)。先制定一個頂級邏輯框架,而將邏輯的細節(jié)留給具體的子類去實現(xiàn)。

    23、VISITOR—情人節(jié)到了,要給每個MM送一束鮮花和一張卡片,可是每個MM送的花都要針對她個人的特點,每張卡片也要根據(jù)個人的特點來挑,我一個人哪搞得清楚,還是找花店老板和禮品店老板做一下Visitor,讓花店老板根據(jù)MM的特點選一束花,讓禮品店老板也根據(jù)每個人特點選一張卡,這樣就輕松多了;

    訪問者模式:訪問者模式的目的是封裝一些施加于某種數(shù)據(jù)結構元素之上的操作。一旦這些操作需要修改的話,接受這個操作的數(shù)據(jù)結構可以保持不變。訪問者模式適用于數(shù)據(jù)結構相對未定的系統(tǒng),它把數(shù)據(jù)結構和作用于結構上的操作之間的耦合解脫開,使得操作集合可以相對自由的演化。訪問者模式使得增加新的操作變的很容易,就是增加一個新的訪問者類。訪問者模式將有關的行為集中到一個訪問者對象中,而不是分散到一個個的節(jié)點類中。當使用訪問者模式時,要將盡可能多的對象瀏覽邏輯放在訪問者類中,而不是放到它的子類中。訪問者模式可以跨過幾個類的等級結構訪問屬于不同的等級結構的成員類。

    http://java.ccidnet.com/art/3749/20060622/586221_3.html

    ?

    posted @ 2007-01-27 23:05 海思 閱讀(261) | 評論 (0)編輯 收藏

    2007年1月21日 #

    Object Hierarchy and Inheritance in JavaScript

    JavaScript is an object-oriented language based on prototypes, rather than, as is common, being class-based. Because of this different basis, it can be less apparent how JavaScript allows you to create hierarchies of objects and to have inheritance of properties and their values. This paper attempts to clarify the situation. If you're interested in precise details of how this all works, you can read the ECMA-262 JavaScript language specification (as a PDF file or a Microsoft Word self-extracting binary).

    This paper assumes that you're already somewhat familiar with JavaScript and that you have used JavaScript functions to create simple objects. For information on this subject, see Chapter 10, "Object Model," in the JavaScript Guide.

    The sections in this paper are:

    Class-based object-oriented languages, such as Java and C++, are founded on the concept of two distinct entities: classes and instances. A class defines all of the properties (considering methods and fields in Java, or members in C++, to be properties) that characterize a certain set of objects. A class is an abstract thing, rather than any particular member of the set of objects it describes. For example, the Employee class could represent the set of all employees. An instance, on the other hand, is the instantiation of a class; that is, one of its members. For example, Victoria could be an instance of the Employee class, representing a particular individual as an employee. An instance has exactly the properties of its parent class (no more, no less).

    A prototype-based language, such as JavaScript, does not make this distinction: it simply has objects. A prototype-based language has the notion of a prototypical object, an object used as a template from which to get the initial properties for a new object. Any object can specify its own properties, either when you create it or even at runtime. In addition, any object can be associated as the prototype for another object, allowing the second object to share the first object's properties.

    In class-based languages, you define a class in a separate class definition. In that definition you can specify special methods, called constructors, to use to create instances of the class. A constructor method can specify initial values for the instance's properties and perform other processing appropriate at creation time. You use the new operator in association with the constructor method to create class instances.

    JavaScript follows a similar model, but does not have a class definition separate from the constructor. Instead, you define a constructor function to create objects with a particular initial set of properties and values. Any JavaScript function can be used as a constructor. You use the new operator with a constructor function to create a new object.

    In a class-based language, you create a hierarchy of classes through the class definitions. In a class definition, you can specify that the new class is a subclass of an already existing class. The subclass inherits all the properties of the superclass and additionally can add new properties or modify the inherited ones. For example, assume the Employee class includes only name and dept properties and Manager is a subclass of Employee that adds the reports property. In this case, an instance of the Manager class would have all three properties: name, dept, and reports.

    JavaScript implements inheritance by allowing you to associate a prototypical object with any constructor function. So, you can create exactly the Employee-Manager example, but you use slightly different terminology. First you define the Employee constructor function, specifying the name and dept properties. Next, you define the Manager constructor function, specifying the reports property. Finally, you assign a new Employee object as the prototype for the Manager constructor function. Then, when you create a new Manager, it inherits the name and dept properties from the Employee object.

    In class-based languages, you typically create a class at compile time and then you instantiate instances of the class either at compile time or at runtime. You cannot change the number or the type of properties of a class after you define the class. In JavaScript, however, at runtime you can add or remove properties from any object. If you add a property to an object that is used as the prototype for a set of objects, the objects for which it is the prototype also get the new property.

    Table?1 gives a short summary of some of these differences. The rest of this paper describes the details of using JavaScript constructors and prototypes to create an object hierarchy and compares this to how you would do it in Java.

    Table 1?Comparison of class-based (Java) and prototype-based (JavaScript) object systems

    Class-based (Java) Prototype-based (JavaScript)
    Class and instance are distinct entities.

    All objects are instances.

    Define a class with a class definition; instantiate a class with constructor methods.

    Define and create a set of objects with constructor functions.

    Create a single object with the new operator.

    Same.

    Construct an object hierarchy by using class definitions to define subclasses of existing classes.

    Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.

    Inherit properties by following the class chain.

    Inherit properties by following the prototype chain.

    Class definition specifies all properties of all instances of a class. No way to add properties dynamically at runtime.

    Constructor function or prototype specifies an initial set of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.

    The Employee Example

    The rest of this paper works with the simple employee hierarchy shown in Figure 1.

    Figure 1??? A simple object hierarchy

  • Employee has the properties name (whose value defaults to the empty string) and dept (whose value defaults to "general").
  • Manager is based on Employee. It adds the reports property (whose value defaults to an empty array, intended to have an array of Employee objects as its value).

  • WorkerBee is also based on Employee. It adds the projects property (whose value defaults to an empty array, intended to have an array of strings as its value).

  • SalesPerson is based on WorkerBee. It adds the quota property (whose value defaults to 100). It also overrides the dept property with the value "sales", indicating that all salespersons are in the same department.

  • Engineer is based on WorkerBee. It adds the machine property (whose value defaults to the empty string) and also overrides the dept property with the value "engineering".

    Creating the Hierarchy

    There are several ways you can define appropriate constructor functions to implement the Employee hierarchy. How you choose to define them depends largely on what you want to be able to do in your application. We'll get into all that later.

    For now, let's use very simple (and comparatively inflexible) definitions just to see how we get the inheritance to work. In these definitions, you can't specify any property values when you create an object. The newly-created object simply gets the default values, which you can change at a later time. Figure 2 illustrates the hierarchy with these simple definitions.

    In a real application, you would probably define constructors that allow you to provide property values at object creation time. Options for doing so are described later in . For now, these simple definitions let us look at how the inheritance occurs.

    Figure 2??? What the definitions look like

    The simple Java and JavaScript Employee definitions below are similar. The only difference is that you need to specify the type for each property in Java but not in JavaScript and you need to create an explicit constructor method for the Java class.

    JavaScript Java
    function Employee () {
    this.name = "";
    this.dept = "general";
    }
    public class Employee {
    ???public String name;
    ???public String dept;
    ???public Employee () {
    ??????this.name = "";
    ??????this.dept = "general";
    ???}
    }

    The Manager and WorkerBee definitions show the difference in how you specify the next object higher in the inheritance chain. In JavaScript, you add a prototypical instance as the value of the prototype property of the constructor function. You can do so at any time after you define the constructor. In Java, you specify the superclass within the class definition. You cannot change the superclass outside the class definition.

    JavaScript Java
    function Manager () {
    this.reports = [];
    }
    Manager.prototype = new Employee;
    function WorkerBee () {
    this.projects = [];
    }
    WorkerBee.prototype = new Employee;
    public class Manager extends Employee {
    ???public Employee[] reports;
    ???public Manager () {
    ??????this.reports = new Employee[0];
    ???}
    }
    public class WorkerBee extends Employee {
    ???public String[] projects;
    ???public WorkerBee () {
    ??????this.projects = new String[0];
    ???}
    }

    The Engineer and SalesPerson definitions create objects that descend from WorkerBee and hence from Employee. An object of these types has properties of all the objects above it in the chain. In addition, these definitions override the inherited value of the dept property with new values specific to these objects.

    JavaScript Java
    function SalesPerson () {
    ???this.dept = "sales";
    ???this.quota = 100;
    }
    SalesPerson.prototype = new WorkerBee;
    function Engineer () {
    ???this.dept = "engineering";
    ???this.machine = "";
    }
    Engineer.prototype = new WorkerBee;
    public class SalesPerson extends WorkerBee {
    ???public double quota;
    ???public SalesPerson () {
    ??????this.dept = "sales";
    ??????this.quota = 100.0;
    ???}
    }
    public class Engineer extends WorkerBee {
    ???public String machine;
    ???public Engineer () {
    ??????this.dept = "engineering";
    ??????this.machine = "";
    ???}
    }

    Using these definitions, you can create instances of these objects that get the default values for their properties. Figure 3 illustrates using these JavaScript definitions to create new objects and shows the property values for the new objects.

    NOTE: As described earlier, the term instance has a specific technical meaning in class-based languages. In these languages, an instance is an individual member of a class and is fundamentally different from a class. In JavaScript, "instance" does not have this technical meaning because JavaScript does not have this difference between classes and instances. However, in talking about JavaScript, "instance" can be used informally to mean an object created using a particular constructor function. So, in this example, you could informally say that jane is an instance of Engineer. Similarly, although the terms parent, child, ancestor, and descendant do not have formal meanings in JavaScript, we can use them informally to refer to objects higher or lower in the prototype chain.
    Figure 3??? Creating objects with the simple definitions

    Object Properties

    This section discusses how objects inherit properties from other objects in the prototype chain and what happens when you add a property at runtime.

    Inheriting Properties

    Assume you create the mark object as a WorkerBee as shown in Figure 3 with this statement:

    mark = new WorkerBee;
    When JavaScript sees the new operator, it creates a new generic object and passes this new object as the value of the this keyword to the WorkerBee constructor function. The constructor function explicitly sets the value of the projects property. It also sets the value of the internal __proto__ property to the value of WorkerBee.prototype. (That property name has 2 underscore characters at the front and 2 at the end.) The __proto__ property determines the prototype chain used to return property values. Once these properties are set, JavaScript returns the new object and the assignment statement sets the variable mark to that object.

    This process doesn't explicitly put values in the mark object (local values) for the properties mark inherits from the prototype chain. When you ask for the value of a property, JavaScript first checks to see if the value exists in that object. If it does, that value is returned. If the value isn't there locally, JavaScript checks the prototype chain (using the __proto__ property). If an object in the prototype chain has a value for the property, that value is returned. If no such property is found, JavaScript says the object doesn't have the property. In this way, the mark object has the following properties and values:

    mark.name = "";
    mark.dept = "general";
    mark.projects = [];
    The mark object inherits values for the name and dept properties from the prototypical object in mark.__proto__. It is assigned a local value for the projects property by the WorkerBee constructor. Simply put, this gives you inheritance of properties and their values in JavaScript. Some subtleties of this process are discussed in .

    Because these constructors don't let you supply instance-specific values, this information is generic. The property values are the default ones shared by all new objects created from WorkerBee. You can, of course, change the values of any of these properties. So, you could give specific information for mark as shown here:

    mark.name = "Doe, Mark";
    mark.dept = "admin";
    mark.projects = ["navigator"];

    Adding Properties

    In JavaScript at runtime you can add properties to any object. You are not constrained to use only the properties provided by the constructor function. To add a property that is specific to a single object, you simply assign a value to the object, as in:

    mark.bonus = 3000;
    Now, the mark object has a bonus property, but no other WorkerBee has this property.

    If you add a new property to an object that is being used as the prototype for a constructor function, you add that property to all objects that inherit properties from the prototype. For example, you can add a specialty property to all employees with the following statement:

    Employee.prototype.specialty = "none";
    As soon as JavaScript executes this statement, the mark object also has the specialty property with the value of "none". Figure 4 shows the effect of adding this property to the Employee prototype and then overriding it for the Engineer prototype.

    Figure 4??? Adding properties

    More Flexible Constructors

    The constructor functions used so far do not let you specify property values when you create an instance. As with Java, you can provide arguments to constructors to initialize property values for instances. Figure 5 shows one way to do this.

    Figure 5??? Specifying properties in a constructor, take 1

    Here are the Java and JavaScript definitions for these objects.

    JavaScript Java
    function Employee (name, dept) {
    this.name = name || "";
    this.dept = dept || "general";
    }
    public class Employee {
    ???public String name;
    ???public String dept;
    ???public Employee () {
    ??????this("", "general");
    ???}
    ???public Employee (name) {
    ??????this(name, "general");
    ???}
    ???public Employee (name, dept) {
    ??????this.name = name;
    ??????this.dept = dept;
    ???}
    }
    function WorkerBee (projs) {
    this.projects = projs || [];
    }
    WorkerBee.prototype = new Employee;
    public class WorkerBee extends Employee {
    ???public String[] projects;
    ???public WorkerBee () {
    ??????this(new String[0]);
    ???}
    ???public WorkerBee (String[] projs) {
    ??????this.projects = projs;
    ???}
    }
    function Engineer (mach) {
    ???this.dept = "engineering";
    ???this.machine = mach || "";
    }
    Engineer.prototype = new WorkerBee;
    public class Engineer extends WorkerBee {
    ???public String machine;
    ???public WorkerBee () {
    ??????this.dept = "engineering";
    ??????this.machine = "";
    ???}
    ???public WorkerBee (mach) {
    ??????this.dept = "engineering";
    ??????this.machine = mach;
    ???}
    }

    These JavaScript definitions use a special idiom for setting default values:

    this.name = name || "";
    The JavaScript logical OR operator (||) evaluates its first argument. If that argument is converts to true, the operator returns it. Otherwise, the operator returns the value of the second argument. Therefore, this line of code tests to see if name has a useful value for the name property. If it does, it sets this.name to that value. Otherwise, it sets this.name to the empty string. This paper uses this idiom for brevity; however, it can be puzzling at first glance.

    With these definitions, when you create an instance of an object, you can specify values for the locally defined properties. As shown in Figure 5, you can use this statement to create a new Engineer:

    jane = new Engineer("belau");
    Jane's properties are now:

    jane.name == "";
    jane.dept == "general";
    jane.projects == [];
    jane.machine == "belau"
    Notice that with these definitions, you cannot specify an initial value for an inherited property such as name. If you want to specify an initial value for inherited properties in JavaScript, you need to add more code to the constructor function.

    So far, the constructor function has created a generic object and then specified local properties and values for the new object. You can have the constructor add more properties by directly calling the constructor function for an object higher in the prototype chain. Figure 6 shows these new definitions.

    Figure 6??? Specifying properties in a constructor, take 2

    Let's look at one of these definitions in detail. Here's the new definition for the Engineer constructor:

    function Engineer (name, projs, mach) {
    this.base = WorkerBee;
    this.base(name, "engineering", projs);
    this.projects = mach || "";
    }
    Assume we create a new Engineer object as follows:

    jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
    JavaScript follows these steps:

    1.???First, the new operator creates a generic object and sets its __proto__ property to Engineer.prototype.
    2.???The new operator then passes the new object to the Engineer constructor as the value of the this keyword.
    3.???Next, the constructor creates a new property called base for that object and assigns the value of the WorkerBee constructor to the base property. This makes the WorkerBee constructor a method of the Engineer object.
    NOTE: The name of the base property is not special. You can use any legal property name; base is simply evocative of its purpose.
    4.???Next, the constructor calls the base method, passing as its arguments two of the arguments passed to the constructor ("Doe, Jane" and ["navigator", "javascript"]) and also the string "engineering". Explicitly using "engineering" in the constructor indicates that all Engineer objects have the same value for the inherited dept property and this value overrides the value inherited from Employee.
    5.???Because base is a method of Engineer, within the call to base, JavaScript binds the this keyword to the object created in step?1. Thus, the WorkerBee function in turn passes the "Doe, Jane" and ["navigator", "javascript"] arguments to the Employee constructor function. Upon return from the Employee constructor function, the WorkerBee function uses the remaining argument to set the projects property.
    6.???Upon return from the base method, the Engineer constructor initializes the object's machine property to "belau".
    7.???Upon return from the constructor, JavaScript assigns the new object to the jane variable.
    You might think that, having called the WorkerBee constructor from inside the Engineer constructor, you've set up inheritance appropriately for Engineer objects. This is not the case. Calling the WorkerBee constructor ensures that an Engineer object starts out with the properties specified in all constructor functions that are called. However, if you later add properties to the Employee or WorkerBee prototypes, those properties are not inherited by the Engineer object. For example, assume you have these statements:

    function Engineer (name, projs, mach) {
    this.base = WorkerBee;
    this.base(name, "engineering", projs);
    this.projects = mach || "";
    }
    jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
    Employee.prototype.specialty = "none";
    The jane object does not inherit the specialty property. You still need to explicitly set up the prototype to ensure dynamic inheritance. Assume instead you have these statements:

    function Engineer (name, projs, mach) {
    this.base = WorkerBee;
    this.base(name, "engineering", projs);
    this.projects = mach || "";
    }
    Engineer.prototype = new WorkerBee;
    jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
    Employee.prototype.specialty = "none";
    Now the value of the jane object's specialty property is "none".

    Property Inheritance Revisited

    The preceding sections have described how constructors and prototypes provide hierarchies and inheritance in JavaScript. As with all languages, there are some subtleties that were not necessarily apparent in these earlier discussions. This section discusses some of those subtleties.

    Local versus Inherited Values

    Let's revisit property inheritance briefly. As discussed earlier, when you access an object property, JavaScript performs these steps:

    1. Check to see if the value exists locally. If it does, return that value.
    2. If there isn't a local value, check the prototype chain (using the __proto__ property).

    3. If an object in the prototype chain has a value for the specified property, return that value.

    4. If no such property is found, the object does not have the property.
    The outcome of this simple set of steps depends on how you've defined things along the way. In our original example, we had these definitions:

    function Employee () {
    this.name = "";
    this.dept = "general";
    }
    function WorkerBee () {
    this.projects = [];
    }
    WorkerBee.prototype = new Employee;
    With these definitions, assume you create amy as an instance of WorkerBee with this statement:

    amy = new WorkerBee;
    The amy object has one local property, projects. The values for the name and dept properties are not local to amy and so are gotten from the amy object's __proto__ property. Thus, amy has these property values:

    amy.name == "";
    amy.dept = "general";
    amy.projects == [];
    Now assume you change the value of the name property in the prototype associated with Employee:

    Employee.prototype.name = "Unknown"
    At first glance, you might expect that new value to propagate down to all the instances of Employee. However, it does not.

    When you create any instance of the Employee object, that instance gets a local value for the name property (the empty string). This means that when you set the WorkerBee prototype by creating a new Employee object, WorkerBee.prototype has a local value for the name property. Therefore, when JavaScript looks up the name property of the amy object (an instance of WorkerBee), JavaScript finds the local value for that property in WorkerBee.prototype. It therefore does not look farther up the chain to Employee.prototype.

    If you want to change the value of an object property at runtime and have the new value be inherited by all descendants of the object, you cannot define the property in the object's constructor function. Instead, you add it to the constructor's associated prototype. For example, assume you change the code above to the following:

    function Employee () {
    ???this.dept = "general";
    }
    Employee.prototype.name = "";
    function WorkerBee () {
    this.projects = [];
    }
    WorkerBee.prototype = new Employee;
    amy = new WorkerBee;
    Employee.prototype.name = "Unknown";
    In this case, the name property of amy becomes "Unknown".

    As these examples show, if you want to have default values for object properties and you want to be able to change the default values at runtime, you should set the properties in the constructor's prototype, not in the constructor function itself.

    Determining Instance Relationships

    You may want to know what objects are in the prototype chain for an object, so that you can tell from what objects this object inherits properties. In a class-based language, you might have an instanceof operator for this purpose. JavaScript does not provide instanceof, but you can write such a function yourself.

    As discussed in , when you use the new operator with a constructor function to create a new object, JavaScript sets the __proto__ property of the new object to the value of the prototype property of the constructor function. You can use this to test the prototype chain.

    For example, assume you have the same set of definitions we've been using, with the prototypes set appropriately. Create an __proto__ object as follows:

    chris = new Engineer("Pigman, Chris", ["jsd"], "fiji");
    With this object, the following statements are all true:

    chris.__proto__ == Engineer.prototype;
    chris.__proto__.__proto__ == WorkerBee.prototype;
    chris.__proto__.__proto__.__proto__ == Employee.prototype;
    chris.__proto__.__proto__.__proto__.__proto__ == Object.prototype;
    chris.__proto__.__proto__.__proto__.__proto__.__proto__ == null;
    Given this, you could write an instanceOf function as follows:

    function instanceOf(object, constructor) { 
    ???while (object != null) {
    ??????if (object == constructor.prototype)
    ?????????return true;
    ??????object = object.__proto__;
    ???}
    ???return false;
    }
    With this definition, the following expressions are all true:

    instanceOf (chris, Engineer)
    instanceOf (chris, WorkerBee)
    instanceOf (chris, Employee)
    instanceOf (chris, Object)
    But this expression is false:

    instanceOf (chris, SalesPerson)

    Global Information in Constructors

    When you create constructors, you need to be careful if you set global information in the constructor. For example, assume that you want a unique ID to be automatically assigned to each new employee. You could use this definition for Employee:

    var idCounter = 1;
    function Employee (name, dept) {
    ???this.name = name || "";
    ???this.dept = dept || "general";
    ???this.id = idCounter++;
    }
    With this definition, when you create a new Employee, the constructor assigns it the next ID in sequence and then increments the global ID counter. So, if your next statement were:

    victoria = new Employee("Pigbert, Victoria", "pubs")
    harry = new Employee("Tschopik, Harry", "sales")
    victoria.id is 1 and harry.id is 2. At first glance that seems fine. However, idCounter gets incremented every time an Employee object is created, for whatever purpose. If you create the entire Employee hierarchy we've been working with, the Employee constructor is called every time we set up a prototype. That is, assume you have this code:

    var idCounter = 1;
    function Employee (name, dept) {
    ???this.name = name || "";
    ???this.dept = dept || "general";
    ???this.id = idCounter++;
    }
    function Manager (name, dept, reports) {...}
    Manager.prototype = new Employee;
    function WorkerBee (name, dept, projs) {...}
    WorkerBee.prototype = new Employee;
    function Engineer (name, projs, mach) {...}
    Engineer.prototype = new WorkerBee;
    function SalesPerson (name, projs, quota) {...}
    SalesPerson.prototype = new WorkerBee;
    mac = new Engineer("Wood, Mac");
    Further assume that the definitions we've omitted here have the base property and call the constructor above them in the prototype chain. In this case, by the time the mac object is created, mac.id is 5.

    Depending on the application, it may or may not matter that the counter has been incremented these extra times. If you care about the exact value of this counter, one possible solution involves instead using this constructor:

    function Employee (name, dept) {
    ???this.name = name || "";
    ???this.dept = dept || "general";
    ???if (name)
    ??????this.id = idCounter++;
    }
    When you create an instance of Employee to use as a prototype, you do not supply arguments to the constructor. Using this definition of the constructor, when you do not supply arguments, the constructor does not assign a value to the id and does not update the counter. Therefore, for an Employee to get an assigned id, you must specify a name for the employee. In our example, mac.id would be 1.

    No Multiple Inheritance

    Some object-oriented languages allow multiple inheritance. That is, an object can inherit the properties and values from unrelated parent objects. JavaScript does not support multiple inheritance.

    As we've already said, inheritance of property values occurs at runtime by JavaScript searching the prototype chain of an object to find a value. Because an object has a single associated prototype, JavaScript cannot dynamically inherit from more than one prototype chain.

    In JavaScript you can have a constructor function call more than one other constructor function within it. This gives the illusion of multiple inheritance. For example, consider the following statements:

    function Hobbyist (hobby) {
    ???this.hobby = hobby || "scuba";
    }
    function Engineer (name, projs, mach, hobby) {
    ???this.base1 = WorkerBee;
    ???this.base1(name, "engineering", projs);
    ???this.base2 = Hobbyist;
    ???this.base2(hobby);
    ???this.projects = mach || "";
    }
    Engineer.prototype = new WorkerBee;
    dennis = new Engineer("Doe, Dennis", ["collabra"], "hugo")
    Further assume that the definition of WorkerBee is as we've previously seen it. In this case, the dennis object has these properties:

    dennis.name == "Doe, Dennis"
    dennis.dept == "engineering"
    dennis.projects == ["collabra"]
    dennis.machine == "hugo"
    dennis.hobby == "scuba"
    So dennis does get the hobby property from the Hobbyist constructor. However, assume you then add a property to the Hobbyist constructor's prototype:

    Hobbyist.prototype.equipment = ["mask", "fins", "regulator", "bcd"]
    The dennis object does not inherit this new property.

    Last Updated: 12/18/97 15:19:54


    Copyright ? 1997 Netscape Communications Corporation

  • posted @ 2007-01-21 16:19 海思 閱讀(473) | 評論 (0)編輯 收藏

    跨越邊界: JavaScript 語言特性

    研究編程語言中的“丑小鴨”

    developerWorks
    文檔選項
    將此頁作為電子郵件發(fā)送

    將此頁作為電子郵件發(fā)送

    未顯示需要 JavaScript 的文檔選項

    樣例代碼


    拓展 Tomcat 應用

    下載 IBM 開源 J2EE 應用服務器 WAS CE 新版本 V1.1


    級別: 初級

    Bruce Tate (bruce.tate@j2life.com), 總裁, RapidRed

    2007 年 1 月 18 日

    JavaScript 常被人們認為是編程語言中無足輕重的一員。這種觀點的形成可以“歸功”于其開發(fā)工具、復雜且不一致的面向 HTML 頁面的文檔對象模型以及不一致的瀏覽器實現(xiàn)。但 JavaScript 絕對不僅僅是一個玩具這么簡單。在本文中,Bruce Tate 向您介紹了 JavaScript 的語言特性。

    幾乎每個 Web 開發(fā)人員都曾有過詛咒 JavaScript 的經(jīng)歷。這個備受爭議的語言受累于其復雜的稱為文檔對象模型 (DOM)的編程模型、糟糕的實現(xiàn)和調(diào)試工具以及不一致的瀏覽器實現(xiàn)。直到最近,很多開發(fā)人員還認為 Javascript 從最好的方面說是無可避免之災禍,從最壞的方面說不過是一種玩具罷了。

    然而 JavaScript 現(xiàn)在開始日益重要起來,而且成為了廣泛應用于 Web 開發(fā)的腳本語言。JavaScript 的復蘇使一些業(yè)界領袖人物也不得不開始重新審視這種編程語言。諸如 Ajax (Asynchronous JavaScript + XML) 這樣的編程技術讓 Web 網(wǎng)頁更加迷人。而完整的 Web 開發(fā)框架,比如 Apache Cocoon,則讓 JavaScript 的應用越來越多,使其不只限于是一種用于制作 Web 頁面的簡單腳本。JavaScript 的一種稱為 ActionScript 的派生物也推動了 Macromedia 的 Flash 客戶端框架的發(fā)展。運行在 JVM 上的實現(xiàn) Rhino 讓 JavaScript 成為了 Java? 開發(fā)人員所首選的一類腳本語言(參見 參考資料)。

    我的好友兼同事 Stuart Halloway 是 Ajax 方面的專家,曾在其教授的 JavaScript 課程中做過這樣的開場白:“到 2011 年,JavaScript 將被公認為是一種擁有開發(fā)現(xiàn)代應用程序所需的一整套新特性的語言” 。他繼而介紹說 JavaScript 程序要比類似的 Java 程序緊密十倍,并繼續(xù)展示了使其之所以如此的一些語言特性。

    關于這個系列

    跨越邊界系列中,作者 Bruce Tate 提出了這樣一個主張:今天的 Java 程序員通過學習其他技術和語言,會得到很好的幫助。編程領域已經(jīng)發(fā)生了變化,Java 技術不再是所有開發(fā)項目理所當然的最佳選擇。其他框架正在影響 Java 框架構建的方式,而從其他語言學到的概念也有助于 Java 編程。對 Python(或 Ruby、Smalltalk 等等)代碼的編寫可能改變 Java 編碼的方式。

    這個系列介紹的編程概念和技術,與 Java 開發(fā)有根本的不同,但可以直接應用于 Java 編程。在某些情況下,需要集成這些技術來利用它們。在其他情況下,可以直接應用這些概念。單獨的工具并不重要,重要的是其他語言和框架可以影響 Java 社區(qū)中的開發(fā)人員、框架,甚至是基本方式。

    在這篇文章中,我將帶您探究 JavaScript 的一些特性,看看這些特性如何讓它如此具有吸引力:

    • 高階函數(shù): 一個高階函數(shù)可以將函數(shù)作為參數(shù),也可以返回一個函數(shù)。此特性讓 JavaScript 程序員可以用 Java 語言所不能提供的方法來操縱函數(shù)。

    • 動態(tài)類型:通過延遲綁定,JavaScript 可以更準確和更靈活。

    • 靈活的對象模型:JavaScript 的對象模型使用一種相對不常見的方式進行繼承 —— 稱為原型 —— 而不是 Java 語言中更常見的基于類的對象模型。

    您可能已經(jīng)熟悉動態(tài)類型模型、高階函數(shù)形式的函數(shù)式編程以及開放對象模型這些概念,因為我在其他的跨越邊界 系列文章中已經(jīng)作過相關的介紹。如果您從未進行過任何正式的 JavaScript 開發(fā),您很可能會認為這些特性屬于非常復雜的語言,例如 Python、Lisp、Smalltalk 和 Haskell,而絕非像 JavaScript 這樣的語言所能提供的。因此,我將用實際的代碼示例來說明這些概念。

    立即開始

    您無需設置 JavaScript。如果您可以在瀏覽器中閱讀此篇文章,就證明您已經(jīng)準備就緒了。本文包含的所有編程示例都可以在大多數(shù)瀏覽器內(nèi)運行。我使用的是 Firefox。

    用在 <script type='text/javascript'></script> 標記之間所包含的 JavaScript 加載簡單的 Web 頁面。清單 1 可以顯示 Hello, World 文本:



    清單 1. Hello, world
    				
    <script type='text/javascript'>
    alert('Hello, World.')
    </script>
    

    要運行此代碼,只需創(chuàng)建一個名為 example1.html 的文件。將清單 1 的代碼復制到該文件內(nèi),并在瀏覽器中加載此文件(參看 下載 部分以獲得本文使用的所有示例 HTML 文件)。注意到每次重載此頁面時,該代碼都會立即執(zhí)行。

    alert 是個函數(shù)調(diào)用,只有一個字符串作為參數(shù)。圖 1 顯示了由清單 1 中的代碼彈出的警告框,顯示文本 “Hello, World”。如果代碼在 HTML body 之內(nèi)(目前并未指定任何 body,但瀏覽器能接受不規(guī)則的 HTML,并且整個頁面都默然作為一個 body 被處理)。頁面一旦加載,JavaScript 就會立即執(zhí)行。



    圖 1. Hello, world
    Hello, World.

    如果要延遲執(zhí)行,可以在 HTML <head> 元素聲明 JavaScript 函數(shù),如清單 2 所示:



    清單 2. 延遲執(zhí)行
    				
    <head>
        
        <script type='text/javascript'>
            function hello() {
                alert('Hello, World.')
            }
        </script>
    </head>
    <body>
        <button onclick="hello();">Say Hello</button>
    </body>
    

    將清單 2 中的代碼輸入到一個 HTML 文件,在瀏覽器內(nèi)加載該文件,單擊 Say Hello 按鈕,結果如圖 2 所示:



    圖 2. 延遲執(zhí)行
    延遲執(zhí)行




    回頁首


    高階函數(shù)

    清單 2,可以大致體會到一些 JavaScript 在操縱函數(shù)方面的能力。將函數(shù)名稱傳遞給 HTML button 標記并利用 HTML 的內(nèi)置事件模型。使用 JavaScript 時,我會經(jīng)常在變量或數(shù)組中存儲函數(shù)(在本文后面的 對象模型 一節(jié),您會看到 JavaScript 對象模型策略大量使用了此技巧)。例如,查看一下清單 3:



    清單 3. 用變量操縱函數(shù)
    				
    <head>
        
        <script type='text/javascript'>
            hot = function hot() {
                alert('Sweat.')
            }
            cold  = function cold() {
                alert('Shiver.')
            }
            
            function swap() {
                temp = hot
                hot = cold
                cold = temp    
                alert('Swapped.')
            }
        </script>
    </head>
    <body>
        <button onclick="hot();">Hot</button>
        <button onclick="cold();">Cold</button>
        <button onclick="swap();">Swap</button>
    </body>
    

    函數(shù)是 JavaScript 中的一類對象,可以自由地操縱它們。首先我聲明兩個函數(shù):hotcold。并分別在不同的變量存儲它們。單擊 Hot 或 Cold 按鈕會調(diào)用對應的函數(shù),生成一個告警。接下來,聲明另一個函數(shù)用來交換 Hot 和 Cold 按鈕的值,將此函數(shù)與第三個按鈕關聯(lián),該按鈕顯示如圖 3 所示的告警:



    圖 3. 操縱函數(shù)

    這個例子說明可以像處理其他變量一樣處理函數(shù)。C 開發(fā)人員很容易將此概念看作是函數(shù)指針 功能,但 JavaScript 的高階函數(shù)的功能更為強大。該特性讓 JavaScript 程序員能夠像處理其他變量類型一樣輕松處理動作或函數(shù)。

    將函數(shù)用作函數(shù)的參數(shù),或將函數(shù)作為值返回,這些概念屬于高階函數(shù)的領域。清單 4 對 清單 3 做了一點點修改,顯示了能返回函數(shù)的高階函數(shù):



    清單 4. 高階函數(shù)
    				
    <head>
    
        <script type='text/javascript'>
    
            function temperature() {
                return current
            }
    
            hot = function hot() {
                alert('Hot.')
            }
    
            cold  = function cold() {
                alert('Cold.')
            }
    
            current = hot
    
            function swap() {
                if(current == hot) {
                  current = cold
                } else {
                  current = hot
                }
            }
        </script>
    </head>
    <body>
        <button onclick="funct = temperature()();">Temperature</button>
        <button onclick="swap();">Swap</button>
    </body>
    

    這個例子解決了一個常見問題:如何將更改中的行為附加到用戶接口事件?通過高階函數(shù),這很容易做到。temperature 高階函數(shù)返回 current 的值,而 current 又可以有 hotcold 函數(shù)。看一下這個有些陳舊的函數(shù)調(diào)用:temperature()()。第一組括號用于調(diào)用 temperature 函數(shù)。第二組括號調(diào)用由 temperature返回 的函數(shù)。圖 4 顯示了輸出:



    圖 4. 高階函數(shù)
    高階函數(shù)

    高階函數(shù)是函數(shù)式編程的基礎,對比面向對象編程,函數(shù)式編程代表了更高級別的抽象。但 JavaScript 的實力并不僅限于高階函數(shù)。JavaScript 的動態(tài)類型就極為適合 UI 開發(fā)。





    回頁首


    動態(tài)類型

    通過靜態(tài)類型,編譯器可以檢查參數(shù)和變量的值或針對一個給定操作所允許的返回值。其優(yōu)勢是編譯器可以做額外的錯誤檢查。而且靜態(tài)類型還可以為諸如 IDE 這樣的工具提供更多信息,帶來其他一些特性,比如更好的代碼完成功能。但靜態(tài)類型也存在著如下一些劣勢:

    • 必須提前聲明意圖,這常常會導致靈活性降低。例如,更改一個 Java 類就會更改類的類型,因而必須重新編譯。對比之下,Ruby 允許開放的類,但更改一個 Java 類還是會更改類的類型。

    • 要實現(xiàn)相同的功能,必須輸入更多的代碼。例如,必須用參數(shù)形式包括進類型信息,必須用函數(shù)形式返回值和所有變量的類型。另外,還必須聲明所有變量并顯式地轉化類型。

    • 靜態(tài)語言的編譯-部署周期要比動態(tài)語言的部署周期長,盡管一些工具可被用來在某種程度上緩解這一問題。

    靜態(tài)類型更適合用于構建中間件或操作系統(tǒng)的語言中。UI 開發(fā)常常需要更高的效率和靈活性,所以更適合采用動態(tài)類型。我深知這種做法存在危險。相信使用過 JavaScript 的 Web 開發(fā)人員都曾經(jīng)為編譯器本應檢測到的錯誤類型的變量而絞盡腦汁。但它所帶來的優(yōu)勢同樣不可否認。下面將舉例加以說明。

    首先,考慮一個對象的情況。在清單 5 中,創(chuàng)建一個新對象,并訪問一個不存在的屬性,名為 color



    清單 5. 引入一個屬性
    				
    <script type='text/javascript'>
        blank_object = new Object();
        blank_object.color = 'blue'
        alert('The color is ' + blank_object.color)
    </script>
    

    當加載并執(zhí)行此應用程序時,會得到如圖 5 所示的結果:



    圖 5. 引入屬性
     引入屬性

    JavaScript 并不會報告 blue 屬性不存在的錯誤。靜態(tài)類型的擁護者大都會被本例所嚇倒,因為本例中的錯誤被很好地隱匿了。雖然這種做法多少會讓您感覺有些不正當,但您也不能否認它巨大的誘惑力。您可以很快引入屬性。如果將本例和本文之前的例子結合起來,還可以引入行為。記住,變量可以保存函數(shù)!所以,基于動態(tài)類型和高階函數(shù),您可以在任何時候向類中引入任意的行為。

    可以輕松地重寫 清單 5,使其如清單 6 所示:



    清單 6. 引入行為
    				
    <script type='text/javascript'>
        blank_object = new Object();
        blank_object.color = function() { return 'blue'}
        alert('The color is ' + blank_object.color())
    </script>
    

    從上例可以看出,在 JavaScript 的不同概念之間可以如此輕松地來回變換,其含義上的變化很大 —— 比如,是引入行為還是引入數(shù)據(jù) —— 但語法上的變化卻很小。該語言很好的延展性是它的一種優(yōu)勢,但同樣也是其缺點所在。實際上,該語言本身的對象模型就是 JavaScript 延展程度的一種體現(xiàn)。





    回頁首


    對象模型

    到目前為止,您應該對 JavaScript 有一個正確的評價了,它絕非只如一個玩具那么簡單。事實上,很多人都使用過其對象模型創(chuàng)建過極為復雜、設計良好的面向對象軟件。但對象模型尤其是用于繼承的對象模型又非您一貫認為的那樣。

    Java 語言是基于類的。當構建應用程序時,也同時構建了可以作為所有對象的模板的新類。然后調(diào)用 new 來實例化該模板,創(chuàng)建一個新對象。而在 JavaScript 中,所創(chuàng)建的是一個原型,此原型是一個實例,可以創(chuàng)建所有未來的對象。

    現(xiàn)在先暫且放下這些抽象的概念,去查看一些實際代碼。比如,清單 7 創(chuàng)建了一個簡單的 Animal,它具有 name 屬性和 speak 動作。其他動物會從這個基礎繼承。



    清單 7. 創(chuàng)建一個構造函數(shù)
    				
    <script type='text/javascript'>        
    Animal = function() {
        this.name = "nobody"
        this.speak = function () {
            return "Who am I?"
        }
    }
    
    myAnimal = new Animal();
    alert('The animal named ' + myAnimal.name + 
          ' says ' + myAnimal.speak());
    
    </script>
    

    清單 7 的結果如圖 6 所示:



    圖 6. 創(chuàng)建一個構造函數(shù)
    構造函數(shù)

    對于 Java 開發(fā)人員而言,清單 7 中的代碼看起來多少有點生疏和奇怪。實際上對于沒有親自構建過對象的許多 JavaScript 開發(fā)人員來說,這些代碼同樣看起來有點生疏和奇怪。也許,下面的解釋可以讓大家能夠更好地理解這段代碼。

    實際上,您只需重點關注其中三段信息。首先,JavaScript 用嵌套函數(shù)表示對象。這意味著清單 7 中的 Animal 的定義是一種有效的語法。第二,JavaScript 基于原型或現(xiàn)有的對象的實例來構造對象,而非基于類模板。funct() 是一種調(diào)用,但 new Animal() 卻基于 Animal 內(nèi)的原型構造一個對象。最后,在 JavaScript 中,對象只是函數(shù)和變量的集合。每個對象并不與類型相關,所以可以自由地修改這種結構。

    回到 清單 7。如您所見,JavaScript 基于在 Animal 中指定的原型定義一個新對象:myAnimal。繼而可以使用原型中的屬性和函數(shù),甚或重定義函數(shù)和屬性。這種靈活性可能會讓 Java 開發(fā)人員受不了,因為他們不習慣這種行為,但它的確是一種十分強大的模型。

    現(xiàn)在我還要更深入一步。您還可以使用名為 prototype 實例變量來指定對象的基礎。方法是設置 prototype 實例變量使其指向繼承鏈的父。如此設置 prototype 之后,您所創(chuàng)建的對象會為未指定的那些對象繼承屬性和函數(shù)。這樣一來,您就可以模仿面向對象的繼承概念。以清單 8 為例:



    清單 8. 通過原型繼承
    				
    <script type='text/javascript'>        
    
    Animal = function() {
        this.name = "nobody"
        this.speak = function () {
            return "Who am I?"
        }
    }
    Dog = function() {
      this.speak = function() {
        return "Woof!"
      }
    }
    Dog.prototype = new Animal();
    
    myAnimal = new Dog();
    alert('The animal named ' + myAnimal.name + 
          ' says ' + myAnimal.speak());
          </script>
    

    在清單 8 中,創(chuàng)建了一個 Dog 原型。此原型基于 AnimalDog 重定義 speak() 方法但卻不會對 name() 方法做任何改動。隨后,將原型 Dog 設置成 Animal。圖 7 顯示了其結果:



    圖 7. 通過原型繼承
    繼承

    這也展示了 JavaScript 是如何解決到屬性或方法的引用問題的:

    • JavaScript 基于原始的原型創(chuàng)建實例,該原型在構造函數(shù)中定義。任何對方法或屬性的引用都會使用所生成的原始副本。

    • 您可以在對象內(nèi)像定義其他任何變量一樣重新定義這些變量。這樣做必然會更改此對象。所以您顯式定義的任何屬性或函數(shù)都將比在原始的原型中定義的那些屬性或函數(shù)優(yōu)先級要高。

    • 如果您顯式設置了名為 prototype 的實例變量,JavaScript 就會在此實例中尋找任何未定義的實例變量或屬性。這種查找是遞歸的:如果 在 prototype 內(nèi)定義的實例不能找到屬性或函數(shù),它就會在 原型中查找,依此類推。

    那么,JavaScript 的繼承模型到底是什么樣的?這取決于您如何對它進行定義。您需要定義繼承行為以便可以覆蓋它。然而,從本質(zhì)上講,JavaScript 更像是一種函數(shù)式語言,而非面向對象的語言,它使用一些智能的語法和語義來仿真高度復雜的行為。其對象模型極為靈活、開放和強大,具有全部的反射性。有些人可能會說它太過靈活。而我的忠告則是,按具體作業(yè)的需要選擇合適的工具。





    回頁首


    結束語

    JavaScript 對象模型構建在該語言的其他功能之上來支持大量的庫,比如 Dojo(參見 參考資料)。這種靈活性讓每個框架能夠以一種精細的方式更改對象模型。在某種程度上,這種靈活性是一種極大的缺點。它可以導致可怕的互操作性問題(盡管該語言的靈活性可以部分緩解這些問題)。

    而另一方面,靈活性又是一種巨大的優(yōu)勢。Java 語言一直苦于無法充分增強其靈活性,原因是它的基本對象模型還未靈活到可以被擴展的程度。一個典型的企業(yè)級開發(fā)人員為能夠成功使用 Java 語言必須要學習很多東西,而新出現(xiàn)的一些優(yōu)秀的開放源碼項目和新技術,比如面向方面編程、Spring 編程框架和字節(jié)碼增強庫,則帶來了大量要學的代碼。

    最后,JavaScript 優(yōu)秀的靈活性的確讓您體會到了一些高階語言的強大功能。當然您無需選擇為每個項目或大多數(shù)項目都做這樣的權衡和折衷。但了解一種語言的優(yōu)勢和劣勢 —— 通過參考大量信息,而不僅僅基于廣告宣傳或公眾意見 —— 會讓您可以更好地控制何時需要使用以及何時不能使用這種語言。當您在修改 JavaScript Web 小部件時,您至少知道該如何讓此語言發(fā)揮它最大的優(yōu)勢。請繼續(xù)跨越邊界吧。


    參考資料

    學習
    posted @ 2007-01-21 15:49 海思 閱讀(240) | 評論 (0)編輯 收藏

    2007年1月7日 #

    1、取出剛剛插入(刪除)的數(shù)據(jù)SELECT 字段名 FROM INSERTED(DELETED)
    2、對于UPDATE實際上是先DELETE然后再INSERT所以如果想得到UPDATE前后的數(shù)據(jù)值,應該先從DELETED取出,然后從INSERTED取出;
    3、IF UPDATE(列名)可以判斷更新或插入哪一個字段的值;
    4、@@ROWCOUNT可以判斷上一行查詢操作得到的列數(shù);
    5、給變量賦值用SET @ZQB = 13;
    6、察看是否有符合條件的記錄IF EXISTS (SELECT name FROM sysobjects WHERE name = 'reminder' AND type = 'TR');
    7、定義游標,如下:
    DECLARE c1 CURSOR FOR
    SELECT emp_mgr.emp
    FROM emp_mgr, inserted
    WHERE emp_mgr.emp = inserted.mgr

    OPEN c1
    FETCH NEXT FROM c1 INTO @e--從游標中取出數(shù)據(jù)
    WHILE @@fetch_status = 0--判斷是否到最后
    BEGIN
    UPDATE emp_mgr
    SET emp_mgr.NoOfReports = emp_mgr.NoOfReports + 1 -- Add 1 for newly
    WHERE emp_mgr.emp = @e -- added employee.

    FETCH NEXT FROM c1 INTO @e
    END
    CLOSE c1
    DEALLOCATE c1--刪除游標引用

    posted @ 2007-01-07 14:34 海思 閱讀(214) | 評論 (0)編輯 收藏

    2006年12月27日 #

    matrixeditor 發(fā)表于 2005-07-28 11:06:41
    作者:Matrixeditor???? 來源:BEA dev2dev
    評論數(shù):4 點擊數(shù):6,815???? 投票總得分:8 投票總人次:3
    關鍵字:

    摘要:

    Acegi安全系統(tǒng),是一個用于Spring Framework的安全框架,能夠和目前流行的Web容器無縫集成。它使用了Spring的方式提供了安全和認證安全服務,包括使用Bean Context,攔截器和面向接口的編程方式。因此,Acegi安全系統(tǒng)能夠輕松地適用于復雜的安全需求。
    ?????????? Acegi安全系統(tǒng),是一個用于Spring Framework的安全框架,能夠和目前流行的Web容器無縫集成。它使用了Spring的方式提供了安全和認證安全服務,包括使用Bean Context,攔截器和面向接口的編程方式。因此,Acegi安全系統(tǒng)能夠輕松地適用于復雜的安全需求。
    ?????? 安全涉及到兩個不同的概念,認證和授權。前者是關于確認用戶是否確實是他們所宣稱的身份。授權則是關于確認用戶是否有允許執(zhí)行一個特定的操作。
    ?????? 在Acegi安全系統(tǒng)中,需要被認證的用戶,系統(tǒng)或代理稱為"Principal"。Acegi安全系統(tǒng)和其他的安全系統(tǒng)不同,它并沒有角色和用戶組的概念。
    Acegi系統(tǒng)設計
    ??關鍵組件
    ??????Acegi安全系統(tǒng)包含以下七個關鍵的功能組件:
    ????????1 Authentication對象,包含了Principal,Credential和Principal的授權信息。同時還可以包含關于發(fā)起認證請求的客戶的其他信息,如IP地址。
    ????????2 ContextHolder對象,使用ThreadLocal儲存Authentication對象的地方。
    ????????3 AuthenticationManager,用于認證ContextHolder中的Authentication對象。
    ????????4 AccessDecissionManager,用于授權一個特定的操作。
    ????????5 RunAsManager,當執(zhí)行特定的操作時,用于選擇性地替換Authentication對象。
    ????????6 Secure Object攔截器,用于協(xié)調(diào)AuthenticationManager,AccessDecissionManager,RunAsManager和特定操作的執(zhí)行。
    ????????7 ObjectDefinitionSource,包含了特定操作的授權定義。
    ??????這七個關鍵的功能組件的關系如下圖所示(圖中灰色部分是關鍵組件):


    安全管理對象
    ?????? Acegi安全系統(tǒng)目前支持兩類安全管理對象。
    ?????? 第一類的安全管理對象管理AOP Alliance的MethodInvocation,開發(fā)人員可以用它來保護Spring容器中的業(yè)務對象。為了使Spring管理的Bean可以作為MethodInvocation來使用,Bean可以通過ProxyFactoryBean和BeanNameAutoProxyCreator來管理,就像在Spring的事務管理一樣使用。
    ?????? 第二類是FilterInvocation。它用過濾器(Filter)來創(chuàng)建,并簡單地包裝了HTTP的ServletRequest,ServletResponse和FilterChain。FilterInvocation可以用來保護HTTP資源。通常,開發(fā)人員并不需要了解它的工作機制,因為他們只需要將Filter加入web.xml,Acegi安全系統(tǒng)就可以工作了。

    安全配置參數(shù)
    ?????? 每個安全管理對象都可以描述數(shù)量不限的各種安全認證請求。例如,MethodInvocation對象可以描述帶有任意參數(shù)的任意方法的調(diào)用,而FilterInvocation可以描述任意的HTTP URL。
    ?????? Acegi安全系統(tǒng)需要記錄應用于每個認證請求的安全配置參數(shù)。例如,對于BankManager.getBalance(int accountNumber)方法和BankManager.approveLoan(int applicationNumber)方法,它們需要的認證請求的安全配置很不相同。
    ?????? 為了保存不同的認證請求的安全配置,需要使用配置參數(shù)。從實現(xiàn)的視角來看,配置參數(shù)使用ConfigAttribute接口來表示。Acegi安全系統(tǒng)提供了ConfigAttribute接口的一個實現(xiàn),SecurityConfig,它把配置參數(shù)保存為一個字符串。
    ?????? ConfigAttributeDefinition類是ConfigAttribute對象的一個簡單的容器,它保存了和特定請求相關的ConfigAttribute的集合。
    ?????? 當安全攔截器收到一個安全認證請求時,需要決定應用哪一個配置參數(shù)。換句話說,它需要找出應用于這個請求的ConfigAttributeDefinition對象。這個查找的過程是由ObjectDefinitionSource接口來處理的。這個接口的主要方法是public ConfigAttributeDefinition getAttributes(Object object),其中Object參數(shù)是一個安全管理對象。因為安全管理對象包含有認證請求的詳細信息,所以ObjectDefinitionSource接口的實現(xiàn)類可以從中獲得所需的詳細信息,以查找相關的ConfigAttributeDefiniton對象。


    Acegi如何工作
    ?????? 為了說明Acegi安全系統(tǒng)如何工作,我們設想一個使用Acegi的例子。通常,一個安全系統(tǒng)需要發(fā)揮作用,它必須完成以下的工作:
    ??????1 首先,系統(tǒng)從客戶端請求中獲得Principal和Credential;
    ??????2 然后系統(tǒng)認證Principal和Credential信息;
    ??????3 如果認證通過,系統(tǒng)取出Principal的授權信息;
    ??????4 接下來,客戶端發(fā)起操作請求;
    ??????5 系統(tǒng)根據(jù)預先配置的參數(shù)檢查Principal對于該操作的授權;
    ??????6 如果授權檢查通過則執(zhí)行操作,否則拒絕。
    ??????那么,Acegi安全系統(tǒng)是如何完成這些工作的呢?首先,我們來看看Acegi安全系統(tǒng)的認證和授權的相關類:
    ??????安全攔截器的抽象基類,它包含有兩個管理類,AuthenticationManager和AccessDecisionManager。AuthenticationManager用于認證ContextHolder中的Authentication對象(包含了Principal,Credential和Principal的授權信息);AccessDecissionManager則用于授權一個特定的操作。

    ??????下面來看一個MethodSecurityInterceptor的例子:
    ??????<bean id="bankManagerSecurity" 
    ???????????????????? class="net.sf.acegisecurity.intercept.method.MethodSecurityInterceptor">
    ???????????? <property name="validateConfigAttributes">
    ????????????????????<value>true</value>
    ????????????</property>
    ????????????<property name="authenticationManager">
    ?????????????????? <ref bean="authenticationManager"/>
    ????????????</property>
    ????????????<property name="accessDecisionManager">
    ??????????????????<ref bean="accessDecisionManager"/>
    ????????????</property>
    ????????????<property name="objectDefinitionSource">
    ??????????????????<value>
    ???????????????????? net.sf.acegisecurity.context.BankManager.delete*=
    ???????????????????????????? ROLE_SUPERVISOR,RUN_AS_SERVER
    ???????????????????? net.sf.acegisecurity.context.BankManager.getBalance=
    ???????????????????????????? ROLE_TELLER,ROLE_SUPERVISOR,BANKSECURITY_CUSTOMER,RUN_
    ??????????????????</value>
    ????????????</property>
    ??????</bean>

    ??????上面的配置文件中,MethodSecurityInterceptor是AbstractSecurityInterceptor的一個實現(xiàn)類。它包含了兩個管理器,authenticationManager和accessDecisionManager。這兩者的配置如下:
    ??????
    <bean id="authenticationDao" class="net.sf.acegisecurity.providers.dao.jdbc.JdbcDaoImpl">
    ?????????????? <property name="dataSource"><ref bean="dataSource"/></property>
    ??????</bean>
    ??????<bean id="daoAuthenticationProvider"
    ???????????????????? class="net.sf.acegisecurity.providers.dao.DaoAuthenticationProvider">
    ?????????????? <property name="authenticationDao"><ref bean="authenticationDao"/></property>
    ??????</bean>
    ??????<bean id="authenticationManager" class="net.sf.acegisecurity.providers.ProviderManager">
    ?????????????? <property name="providers">
    ??????????????????????<list><ref bean="daoAuthenticationProvider"/></list>
    ?????????????? </property>
    ??????</bean>
    ??????<bean id="roleVoter" class="net.sf.acegisecurity.vote.RoleVoter"/>
    ??????<bean id="accessDecisionManager" class="net.sf.acegisecurity.vote.AffirmativeBased">
    ?????????????? <property name="allowIfAllAbstainDecisions"><value>false</value></property>
    ?????????????? <property name="decisionVoters">
    ??????????????????????<list><ref bean="roleVoter"/></list>
    ?????????????? </property>
    ??????</bean>


    ?????? 準備工作做好了,現(xiàn)在我們來看看Acegi安全系統(tǒng)是如何實現(xiàn)認證和授權機制的。以使用HTTP BASIC認證的應用為例子,它包括下面的步驟:
    ?????? 1. 用戶登錄系統(tǒng),Acegi從acegisecurity.ui子系統(tǒng)的安全攔截器(如BasicProcessingFilter)中得到用戶的登錄信息(包括Principal和Credential)并放入Authentication對象,并保存在ContextHolder對象中;
    ?????? 2. 安全攔截器將Authentication對象交給AuthenticationManager進行身份認證,如果認證通過,返回帶有Principal授權信息的Authentication對象。此時ContextHolder對象的Authentication對象已擁有Principal的詳細信息;
    ?????? 3. 用戶登錄成功后,繼續(xù)進行業(yè)務操作;
    ?????? 4. 安全攔截器(bankManagerSecurity)收到客戶端操作請求后,將操作請求的數(shù)據(jù)包裝成安全管理對象(FilterInvocation或MethodInvocation對象);
    ?????? 5. 然后,從配置文件(ObjectDefinitionSource)中讀出相關的安全配置參數(shù)ConfigAttributeDefinition;
    ?????? 6. 接著,安全攔截器取出ContextHolder中的Authentication對象,把它傳遞給AuthenticationManager進行身份認證,并用返回值更新ContextHolder的Authentication對象;
    ?????? 7. 將Authentication對象,ConfigAttributeDefinition對象和安全管理對象(secure Object)交給AccessDecisionManager,檢查Principal的操作授權;
    ?????? 8. 如果授權檢查通過則執(zhí)行客戶端請求的操作,否則拒絕;

    AccessDecisionVoter
    ?????? 注意上節(jié)的accessDecisionManager是一個AffirmativeBased類,它對于用戶授權的投票策略是,只要通過其中的一個授權投票檢查,即可通過;它的allowIfAllAbstainDecisions屬性值是false,意思是如果所有的授權投票是都是棄權,則通不過授權檢查。
    ?????? Acegi安全系統(tǒng)包括了幾個基于投票策略的AccessDecisionManager,上節(jié)的RoleVoter就是其中的一個投票策略實現(xiàn),它是AccessDecisionVoter的一個子類。AccessDecisionVoter的具體實現(xiàn)類通過投票來進行授權決策,AccessDecisionManager則根據(jù)投票結果來決定是通過授權檢查,還是拋出AccessDeniedException例外。
    ?????? AccessDecisionVoter接口共有三個方法:
    public int vote(Authentication authentication, Object object, ConfigAttributeDefinition config);
    public boolean supports(ConfigAttribute attribute);
    public boolean supports(Class clazz);
    ?????? 其中的vote方法返回int返回值,它們是AccessDecisionVoter的三個靜態(tài)成員屬性:ACCESS_ABSTAIN,,ACCESS_DENIED和ACCESS_GRANTED,它們分別是棄權,否決和贊成。
    ?????? Acegi安全系統(tǒng)中,使用投票策略的AccessDecisionManager共有三個具體實現(xiàn)類:AffirmativeBased、ConsensusBased和UnanimousBased。它們的投票策略是,AffirmativeBased類只需有一個投票贊成即可通過;ConsensusBased類需要大多數(shù)投票贊成即可通過;而UnanimousBased類需要所有的投票贊成才能通過。
    ?????? RoleVoter類是一個Acegi安全系統(tǒng)AccessDecisionVoter接口的實現(xiàn)。如果ConfigAttribute以ROLE_開頭,RoleVoter則進行投票。如果GrantedAuthority的getAutority方法的String返回值匹配一個或多個以ROLE_開頭的ConfigAttribute,則投票通過,否則不通過。如果沒有以ROLE_開頭的ConfigAttribute,RoleVoter則棄權。

    安全攔截器
    ??攔截器如何工作
    ??MethodInvocation攔截器
    ??FilterInvocation攔截器
    認證
    ??認證請求
    ??認證管理器
    ??Authentication Provider
    授權
    ??Access Decision Manager
    ??Voting Decision Manager
    ??授權管理推薦
    ContextHolder的用戶接口
    ??用戶接口目標
    ??HTTP會話認證
    ??HTTP Basic認證

    1、Log4j的概念
    ?? Log4j中有三個主要的組件,它們分別是Logger、Appender和Layout,Log4j 允許開發(fā)人員定義多個Logger,每個Logger擁有自己的名字,Logger之間通過名字來表明隸屬關系。有一個Logger稱為Root,它永遠 存在,且不能通過名字檢索或引用,可以通過Logger.getRootLogger()方法獲得,其它Logger通過 Logger.getLogger(String name)方法。
    ?? Appender則是用來指明將所有的log信息存放到什么地方,Log4j中支持多種appender,如 console、files、GUI components、NT Event Loggers等,一個Logger可以擁有多個Appender,也就是你既可以將Log信息輸出到屏幕,同時存儲到一個文件中。
    ?? Layout的作用是控制Log信息的輸出方式,也就是格式化輸出的信息。
    ?? Log4j中將要輸出的Log信息定義了5種級別,依次為DEBUG、INFO、WARN、ERROR和FATAL,當輸出時,只有級別高過配置中規(guī)定的 級別的信息才能真正的輸出,這樣就很方便的來配置不同情況下要輸出的內(nèi)容,而不需要更改代碼,這點實在是方便啊。

    2、Log4j的配置文件
    ??雖然可以不用配置文件,而在程序中實現(xiàn)配置,但這種方法在如今的系統(tǒng)開發(fā)中顯然是不可取的,能采用配置文件的地方一定一定要用配置文件。Log4j支持兩 種格式的配置文件:XML格式和Java的property格式,本人更喜歡后者,首先看一個簡單的例子吧,如下:

     log4j.rootLogger=debug, stdout, R
    ??log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    ??log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

    ??# Pattern to output the caller's file name and line number.
    ??log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

    ??log4j.appender.R=org.apache.log4j.RollingFileAppender
    ??log4j.appender.R.File=example.log
    ??log4j.appender.R.MaxFileSize=100KB

    ??# Keep one backup file
    ??log4j.appender.R.MaxBackupIndex=1

    ??log4j.appender.R.layout=org.apache.log4j.PatternLayout
    ??log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
    ????????

    ??首先,是設置root,格式為 log4j.rootLogger=[level],appenderName, ...,其中l(wèi)evel就是設置需要輸出信息的級別,后面是appender的輸出的目的地,appenderName就是指定日志信息輸出到哪個地方。您可以同時指定多個輸出目的地。配置日志信息輸出目的地Appender,其語法為
    ??log4j.appender.appenderName = fully.qualified.name.of.appender.class
    ??log4j.appender.appenderName.option1 = value1
    ??...
    ??log4j.appender.appenderName.option = valueN
    Log4j提供的appender有以下幾種:
    ??org.apache.log4j.ConsoleAppender(控制臺)
    ??org.apache.log4j.FileAppender(文件)
    ??org.apache.log4j.DailyRollingFileAppender(每天產(chǎn)生一個日志文件)
    ??org.apache.log4j.RollingFileAppender(文件大小到達指定尺寸的時候產(chǎn)生新文件)
    ??org.apache.log4j.WriterAppender(將日志信息以流格式發(fā)送到任意指定的地方)
    配置日志信息的格式(布局),其語法為:
    ??log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class
    ??log4j.appender.appenderName.layout.option1 = value1
    ??....
    ??log4j.appender.appenderName.layout.option = valueN
    Log4j提供的layout有以下幾種:
    ??org.apache.log4j.HTMLLayout(以HTML表格形式布局),
    ??org.apache.log4j.PatternLayout(可以靈活地指定布局模式),
    ??org.apache.log4j.SimpleLayout(包含日志信息的級別和信息字符串),
    ??org.apache.log4j.TTCCLayout(包含日志產(chǎn)生的時間、線程、類別等等信息)

    3、Log4j在程序中的使用
    ??要在自己的類中使用Log4j,首先聲明一個靜態(tài)變量Logger logger=Logger.getLog("classname");在使用之前,用PropertyConfigurator.configure ("配置文件")配置一下,現(xiàn)在就可以使用了,用法如下:logger.debug("debug message")或者logger.info("info message"),看下面一個小例子:

     import com.foo.Bar;
    ??import org.apache.log4j.Logger;
    ??import org.apache.log4j.PropertyConfigurator;
    ??public class MyApp {
    ????static Logger logger = Logger.getLogger(MyApp.class.getName());
    ????public static void main(String[] args) {
    ??????// BasicConfigurator replaced with PropertyConfigurator.
    ??????PropertyConfigurator.configure(args[0]);
    ??????logger.info("Entering application.");
    ??????Bar bar = new Bar();
    ??????bar.doIt();
    ??????logger.info("Exiting application.");
    ????}
    ??}



    [簡介]

    對于一個典型的Web應用,完善的認證和授權機制是必不可少的,在SpringFramework中,Juergen Hoeller提供的范例JPetStore給了一些這方面的介紹,但還遠遠不夠,Acegi是一個專門為SpringFramework提供安全機制的 項目,全稱為Acegi Security System for Spring,當前版本為0.5.1,就其目前提供的功能,應該可以滿足絕大多數(shù)應用的需求。

    本文的主要目的是希望能夠說明如何在基于Spring構架的Web應用中使用Acegi,而不是詳細介紹其中的每個接口、每個類。注意,即使對已經(jīng)存在的Spring應用,通過下面介紹的步驟,也可以馬上享受到Acegi提供的認證和授權。

    [基礎工作]
    在你的Web應用的lib中添加Acegi下載包中的acegi-security.jar

    [web.xml]
    實現(xiàn)認證和授權的最常用的方法是通過filter,Acegi亦是如此,通常Acegi需要在web.xml添加以下5個filter:

    <filter>
    ??<filter-name>Acegi Channel Processing Filter</filter-name>
    ??<filter-class>net.sf.acegisecurity.util.FilterToBeanProxy</filter-class>
    ??<init-param>
    ????<param-name>targetClass</param-name>
    ????<param-value>net.sf.acegisecurity.securechannel.ChannelProcessingFilter</param-value>
    ??</init-param>
    </filter>
    <filter>
    ??<filter-name>Acegi Authentication Processing Filter</filter-name>
    ??<filter-class>net.sf.acegisecurity.util.FilterToBeanProxy</filter-class>
    ??<init-param>
    ????<param-name>targetClass</param-name>
    ????<param-value>net.sf.acegisecurity.ui.webapp.AuthenticationProcessingFilter</param-value>
    ??</init-param>
    </filter>
    <filter>
    ??<filter-name>Acegi HTTP BASIC Authorization Filter</filter-name>
    ??<filter-class>net.sf.acegisecurity.util.FilterToBeanProxy</filter-class>
    ??<init-param>
    ????<param-name>targetClass</param-name>
    ????<param-value>net.sf.acegisecurity.ui.basicauth.BasicProcessingFilter</param-value>
    ??</init-param>
    </filter>
    <filter>
    ??<filter-name>Acegi Security System for Spring Auto Integration Filter</filter-name>
    ??<filter-class>net.sf.acegisecurity.ui.AutoIntegrationFilter</filter-class>
    </filter>
    <filter>
    ??<filter-name>Acegi HTTP Request Security Filter</filter-name>
    ??<filter-class>net.sf.acegisecurity.util.FilterToBeanProxy</filter-class>
    ??<init-param>
    ????<param-name>targetClass</param-name>
    ????<param-value>net.sf.acegisecurity.intercept.web.SecurityEnforcementFilter</param-value>
    ??</init-param>
    </filter>


    最先引起迷惑的是net.sf.acegisecurity.util.FilterToBeanProxy,Acegi自己的文檔上解釋是: “What??FilterToBeanProxy does is delegate the Filter's methods through to a bean which is obtained from the
    Spring application context. This enables the bean to benefit from the Spring application context lifecycle support and configuration flexibility.”,如希望深究的話,去看看源代碼應該不難理解。

    再下來就是添加filter-mapping了:
    <filter-mapping>
    ??<filter-name>Acegi Channel Processing Filter</filter-name>
    ??<url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
    ??<filter-name>Acegi Authentication Processing Filter</filter-name>
    ??<url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
    ??<filter-name>Acegi HTTP BASIC Authorization Filter</filter-name>
    ??<url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
    ??<filter-name>Acegi Security System for Spring Auto Integration Filter</filter-name>
    ??<url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
    ??<filter-name>Acegi HTTP Request Security Filter</filter-name>
    ??<url-pattern>/*</url-pattern>
    </filter-mapping>


    這里,需要注意以下兩點:
    1) 這幾個filter的順序是不能更改的,順序不對將無法正常工作;
    2) 如果你的應用不需要安全傳輸,如https,則將"Acegi Channel Processing Filter"相關內(nèi)容注釋掉即可;
    3) 如果你的應用不需要Spring提供的遠程訪問機制,如Hessian and Burlap,將"Acegi HTTP BASIC Authorization
    Filter"相關內(nèi)容注釋掉即可。

    [applicationContext.xml]
    接下來就是要添加applicationContext.xml中的內(nèi)容了,從剛才FilterToBeanFactory的解釋可以看出,真正的filter都
    在Spring的applicationContext中管理:

    1) 首先,你的數(shù)據(jù)庫中必須具有保存用戶名和密碼的table,Acegi要求table的schema必須如下:

    CREATE TABLE users (
    ????username VARCHAR(50) NOT NULL PRIMARY KEY,
    ????password VARCHAR(50) NOT NULL,
    ????enabled BIT NOT NULL
    );
    CREATE TABLE authorities (
    ????username VARCHAR(50) NOT NULL,
    ????authority VARCHAR(50) NOT NULL
    );
    CREATE UNIQUE INDEX ix_auth_username ON authorities ( username, authority );
    ALTER TABLE authorities ADD CONSTRAINT fk_authorities_users foreign key (username) REFERENCES users
    (username);


    2) 添加訪問你的數(shù)據(jù)庫的datasource和Acegi的jdbcDao,如下:

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    ??<property name="driverClassName"><value>${jdbc.driverClassName}</value></property>
    ??<property name="url"><value>${jdbc.url}</value></property>
    ??<property name="username"><value>${jdbc.username}</value></property>
    ??<property name="password"><value>${jdbc.password}</value></property>
    </bean>
    <bean id="jdbcDaoImpl" class="net.sf.acegisecurity.providers.dao.jdbc.JdbcDaoImpl">
    ??<property name="dataSource"><ref bean="dataSource"/></property>
    </bean>


    3) 添加DaoAuthenticationProvider:

    <bean id="daoAuthenticationProvider" class="net.sf.acegisecurity.providers.dao.DaoAuthenticationProvider">
    ??<property name="authenticationDao"><ref bean="authenticationDao"/></property>
    ??<property name="userCache"><ref bean="userCache"/></property>
    </bean>

    <bean id="userCache" class="net.sf.acegisecurity.providers.dao.cache.EhCacheBasedUserCache">
    ??<property name="minutesToIdle"><value>5</value></property>
    </bean>


    如果你需要對密碼加密,則在daoAuthenticationProvider中加入:<property name="passwordEncoder"><ref
    bean="passwordEncoder"/></property>,Acegi提供了幾種加密方法,詳細情況可看包
    net.sf.acegisecurity.providers.encoding

    4) 添加authenticationManager:

    <bean id="authenticationManager" class="net.sf.acegisecurity.providers.ProviderManager">
    ??<property name="providers">
    ????<list>
    ??????<ref bean="daoAuthenticationProvider"/>
    ????</list>
    ?? </property>
    </bean>


    5) 添加accessDecisionManager:

    <bean id="accessDecisionManager" class="net.sf.acegisecurity.vote.AffirmativeBased">
    ??<property name="allowIfAllAbstainDecisions">
    ????<value>false</value>
    ??</property>
    ??<property name="decisionVoters">
    ????<list><ref bean="roleVoter"/></list>
    ??</property>
    </bean>
    <bean id="roleVoter" class="net.sf.acegisecurity.vote.RoleVoter"/>


    6) 添加authenticationProcessingFilterEntryPoint:

    <bean id="authenticationProcessingFilterEntryPoint" 
    class="net.sf.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint">
    ??<property name="loginFormUrl"><value>/acegilogin.jsp</value></property>
    ??<property name="forceHttps"><value>false</value></property>
    </bean>


    其中acegilogin.jsp是登陸頁面,一個最簡單的登錄頁面如下:

    <%@ taglib prefix='c' uri='http://java.sun.com/jstl/core' %>
    <%@ page import="net.sf.acegisecurity.ui.AbstractProcessingFilter" %>
    <%@ page import="net.sf.acegisecurity.AuthenticationException" %>
    <html>
    ??<head>
    ????<title>Login</title>
    ??</head>

    ??<body>
    ????<h1>Login</h1>
    ????<form action="<c:url value='j_acegi_security_check'/>" method="POST">
    ??????<table>
    ????????<tr><td>User:</td><td><input type='text' name='j_username'></td></tr>
    ????????<tr><td>Password:</td><td><input type='password' name='j_password'></td></tr>
    ????????<tr><td colspan='2'><input name="submit" type="submit"></td></tr>
    ????????<tr><td colspan='2'><input name="reset" type="reset"></td></tr>
    ??????</table>
    ????</form>
    ??</body>
    </html>


    7) 添加filterInvocationInterceptor:

    <bean id="filterInvocationInterceptor" 
    class="net.sf.acegisecurity.intercept.web.FilterSecurityInterceptor">
    ??<property name="authenticationManager">
    ????<ref bean="authenticationManager"/>
    ??</property>
    ??<property name="accessDecisionManager">
    ????<ref bean="accessDecisionManager"/>
    ??</property>
    ??<property name="objectDefinitionSource">
    ????<value>
    ??????CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
    ??????\A/sec/administrator.*\Z=ROLE_SUPERVISOR
    ??????\A/sec/user.*\Z=ROLE_TELLER
    ????</value>
    ??</property>
    </bean>


    這里請注意,要objectDefinitionSource中定義哪些頁面需要權限訪問,需要根據(jù)自己的應用需求進行修改,我上面給出
    的定義的意思是這樣的:
    a. CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON意思是在比較請求路徑時全部轉換為小寫
    b. \A/sec/administrator.*\Z=ROLE_SUPERVISOR意思是只有權限為ROLE_SUPERVISOR才能訪問/sec/administrator*的頁面
    c. \A/sec/user.*\Z=ROLE_TELLER意思是只有權限為ROLE_TELLER的用戶才能訪問/sec/user*的頁面

    8) 添加securityEnforcementFilter:

    <bean id="securityEnforcementFilter" class="net.sf.acegisecurity.intercept.web.SecurityEnforcementFilter">
    ??<property name="filterSecurityInterceptor">
    ????<ref bean="filterInvocationInterceptor"/>
    ??</property>
    ??<property name="authenticationEntryPoint">
    ????<ref bean="authenticationProcessingFilterEntryPoint"/>
    ??</property>
    </bean>


    9) 添加authenticationProcessingFilter:

    <bean id="authenticationProcessingFilter" 
    class="net.sf.acegisecurity.ui.webapp.AuthenticationProcessingFilter">
    ??<property name="authenticationManager">
    ????<ref bean="authenticationManager"/>
    ??</property>
    ??<property name="authenticationFailureUrl">
    ????<value>/loginerror.jsp</value>
    ??</property>
    ??<property name="defaultTargetUrl">
    ????<value>/</value>
    ??</property>
    ??<property name="filterProcessesUrl">
    ????<value>/j_acegi_security_check</value>
    ??</property>
    </bean>

    其中authenticationFailureUrl是認證失敗的頁面。

    10) 如果需要一些頁面通過安全通道的話,添加下面的配置:

    <bean id="channelProcessingFilter" class="net.sf.acegisecurity.securechannel.ChannelProcessingFilter">
    ??<property name="channelDecisionManager">
    ????<ref bean="channelDecisionManager"/>
    ??</property>
    ??<property name="filterInvocationDefinitionSource">
    ????<value>
    ??????CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
    ??????\A/sec/administrator.*\Z=REQUIRES_SECURE_CHANNEL
    ??????\A/acegilogin.jsp.*\Z=REQUIRES_SECURE_CHANNEL
    ??????\A/j_acegi_security_check.*\Z=REQUIRES_SECURE_CHANNEL
    ??????\A.*\Z=REQUIRES_INSECURE_CHANNEL
    ????</value>
    ??</property>
    </bean>

    <bean id="channelDecisionManager" class="net.sf.acegisecurity.securechannel.ChannelDecisionManagerImpl">
    ??<property name="channelProcessors">
    ????<list>
    ??????<ref bean="secureChannelProcessor"/>
    ??????<ref bean="insecureChannelProcessor"/>
    ????</list>
    ??</property>
    </bean>
    <bean id="secureChannelProcessor" class="net.sf.acegisecurity.securechannel.SecureChannelProcessor"/>
    <bean id="insecureChannelProcessor" class="net.sf.acegisecurity.securechannel.InsecureChannelProcessor"/>


    [缺少了什么?]
    Acegi目前提供了兩種"secure object",分別對頁面和方法進行安全認證管理,我這里介紹的只是利用
    FilterSecurityInterceptor對訪問頁面的權限控制,除此之外,Acegi還提供了另外一個Interceptor――
    MethodSecurityInterceptor,它結合runAsManager可實現(xiàn)對對象中的方法的權限控制,使用方法可參看Acegi自帶的文檔
    和contact范例。

    [最后要說的]
    本來以為只是說明如何使用Acegi而已,應該非常簡單,但真正寫起來才發(fā)現(xiàn)想要條理清楚的理順所有需要的bean還是很
    困難的,但愿我沒有遺漏太多東西,如果我的文章有什么遺漏或錯誤的話,還請參看Acegi自帶的quick-start范例,但請
    注意,這個范例是不能直接拿來用的。
    分析和學習Spring中的jpetstore用戶管理
    ??存在用戶的系統(tǒng),必然需要用戶的登錄和認證,今天就通過分析Spring中自帶的jpetstore的例子來學習一下如何實現(xiàn)在Spring構架的系統(tǒng)中用戶登錄。
    1、首先從注冊用戶開始,先看看jpetstore-servlet.xml中關于注冊用戶的bean定義,從定義命名中就可以看出下面這段就是注冊用戶的:
    ??
    <bean name="/shop/newAccount.do" class="org.springframework.samples.jpetstore.web.spring.AccountFormController">
    ????<property name="petStore"><ref bean="petStore"/></property>
    ????<property name="validator"><ref bean="accountValidator"/></property>
    ????<property name="successView"><value>index</value></property>
    ??</bean>

    1). formView呢?從AccountFormController的構造函數(shù)中得到,原來為EditAccountForm;??
    2). EditoAccountForm.jsp中顯得非常亂,其實沒有多少難理解的地方,最主要的是這個form既是添加新用戶的,又是編輯用戶信息的,所以顯得有點亂糟糟的。
    2、添加好了新用戶,接下來看看如何登錄,在jpetstore-servlet中發(fā)現(xiàn)這兩個相關bean定義,如下:
    ??
    <bean name="/shop/signon.do" class="org.springframework.samples.jpetstore.web.spring.SignonController">
    ????<property name="petStore"><ref bean="petStore"/></property>
    ??</bean>
    ??<bean name="/shop/signonForm.do" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
    ????<property name="viewName"><value>SignonForm</value></property>
    ??</bean>

    1). 第二個bean是在運行時用戶輸入用戶名和密碼的form,叫做SignonForm,對于這個 ParameterizableViewController,用文檔里的話說這是最簡單的Controller,其作用就是在運行中指向 Controller而不是直接指向jsp文件,僅此而已。
    2). SignonForm.jsp,里面就是一個簡單的form,其action就是第一個bean,即/shop/signon.do,最需要注意的是 signonForwardAction,其主要作用是forward到需要輸入用戶名和密碼的那個頁面上去,這個變量哪里來的呢?看看下面:
    ??
    <bean id="secureHandlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    ????<property name="interceptors">
    ??????<list>
    ????????<ref bean="signonInterceptor"/>
    ??????</list>
    ????</property>
    ????<property name="urlMap">
    ??????<map>
    ????????<entry key="/shop/editAccount.do"><ref local="secure_editAccount"/></entry>
    ????????<entry key="/shop/listOrders.do"><ref local="secure_listOrders"/></entry>
    ????????<entry key="/shop/newOrder.do"><ref local="secure_newOrder"/></entry>
    ????????<entry key="/shop/viewOrder.do"><ref local="secure_viewOrder"/></entry>
    ??????</map>
    ????</property>
    ??</bean>

    ??原來,上面的signonInterceptor實現(xiàn)了preHandle,因此在請求上面的map頁面時,首先要經(jīng)過這個Interceptor,看看 SignonInterceptor的源碼,原來在其中為signon.jsp賦予一個signonForwardAction對象,呵呵,總算明白了。
    3). 接下來去學習一下SignonController,其主體部分中可以看出,首先取出用戶輸入的username和password,然后到數(shù)據(jù)庫中驗證 有沒有這個用戶,如果沒有這個用戶,返回各錯誤頁面;如果成功,首先生成一個UserSession對象,在request的session加入這個 userSession,注意這部分代碼中給出了PagedListHolder分頁的簡單使用方法,關于分頁顯示,以后再學習吧。
    3、登錄成功后,就可以根據(jù)不同的用戶設施不同的行為了,取得用戶信息,無非就是從session取出userSession即可。
    posted @ 2006-12-27 23:20 海思 閱讀(222) | 評論 (0)編輯 收藏

    2006年12月24日 #

    或許你正需要面試軟件測試工程師,或許你準備去應聘軟件測試工程師,以下是一些可能注意的問題。(選譯)

    有什么原因讓你參與到測試和質(zhì)量管理中來?
    什么是測試生命周期,解釋一下它的各個階段?
    測試和質(zhì)量保證有什么不同?
    什么是Negative測試?
    在之前做測試的過程總遇到過哪些問題?你是如何解決的?
    你是如何給你的測試和質(zhì)量保證團隊力量的?
    你是如何定義質(zhì)量管理的?
    你最喜歡測試和質(zhì)量管理什么地方?
    你最不喜歡什么地方?
    什么是瀑布式開發(fā)方法,你是否認同所有的步驟?
    什么是V-模式開發(fā)方法,你是否認同這個模型?
    什么是CMM?你工作過的公司的級別是怎么樣的?
    什么才算好的測試人員?

    更多問題,可以查看以下內(nèi)容:

    Could you tell me two things you did in your previous assignment (QA/Testing related hopefully) that you are proud of?
    List 5 words that best describe your strengths.
    What are two of your weaknesses?
    What methodologies have you used to develop test cases?
    In an application currently in production, one module of code is being modified. Is it necessary to re- test the whole application or is it enough to just test functionality associated with that module?
    Define each of the following and explain how each relates to the other: Unit, System, and Integration testing.
    Define Verification and Validation. Explain the differences between the two.
    Explain the differences between White-box, Gray-box, and Black-box testing.
    How do you go about going into a new organization? How do you assimilate?
    Define the following and explain their usefulness: Change Management, Configuration Management, Version Control, and Defect Tracking.
    What is ISO 9000? Have you ever been in an ISO shop?
    When are you done testing?
    What is the difference between a test strategy and a test plan?
    What is ISO 9003? Why is it important
    What are ISO standards? Why are they important?
    What is IEEE 829? (This standard is important for Software Test Documentation-Why?)
    What is IEEE? Why is it important?
    Do you support automated testing? Why?
    We have a testing assignment that is time-driven. Do you think automated tests are the best solution?
    What is your experience with change control? Our development team has only 10 members. Do you think managing change is such a big deal for us?
    Are reusable test cases a big plus of automated testing and explain why.
    Can you build a good audit trail using Compuware's QACenter products. Explain why.
    How important is Change Management in today's computing environments?
    Do you think tools are required for managing change. Explain and please list some tools/practices which can help you managing change.
    We believe in ad-hoc software processes for projects. Do you agree with this? Please explain your answer.
    When is a good time for system testing?
    Are regression tests required or do you feel there is a better use for resources?
    Our software designers use UML for modeling applications. Based on their use cases, we would like to plan a test strategy. Do you agree with this approach or would this mean more effort for the testers.
    Tell me about a difficult time you had at work and how you worked through it.
    Give me an example of something you tried at work but did not work out so you had to go at things another way.
    How can one file compare future dated output files from a program which has change, against the baseline run which used current date for input. The client does not want to mask dates on the output files to allow compares. - Answer-Rerun baseline and future date input files same # of days as future dated run of program with change. Now run a file compare against the baseline future dated output and the changed programs' future dated output.

    Interviewing Suggestions
    If you do not recognize a term ask for further definition. You may know the methodology/term but you have used a different name for it.
    Always keep in mind that the employer wants to know what you are going to do for them, with that you should always stay/be positive.

    Preinterview Questions
    What is the structure of the company?
    Who is going to do the interview-possible background information of interviewer?
    What is the employer's environment (platforms, tools, etc.)?
    What are the employer's methods and processes used in software arena?
    What is the employer's philosophy?
    What is the project all about you are interviewing for-as much information as possible.
    Any terminologies that the company may use.

    (該文轉載自Matrix,原文地址:http://www.matrix.org.cn/resource/article/44/44430_software+test.html



    Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=791907

    posted @ 2006-12-24 22:49 海思 閱讀(458) | 評論 (0)編輯 收藏

         摘要: 李濤,Sun中國工程研究院工程師 概述 1:三個新加的多線程包 ...  閱讀全文
    posted @ 2006-12-24 22:37 海思 閱讀(354) | 評論 (1)編輯 收藏

    2006年12月21日 #

    利用XMLBean輕輕松松讀寫XML

    作者:葉楓




    版權聲明:本文可以自由轉載,轉載時請務必以超鏈接形式標明文章原始出處和作者信息及本聲明
    作者:葉楓(http://blog.matrix.org.cn/page/葉楓)
    原文:[http://www.matrix.org.cn/resource/article/44/44027_XMLBean.html]http://www.matrix.org.cn/resource/article/44/44027_XMLBean.html[/url]
    關鍵字:XML XMLBean Parser

    一、關于XML解析

    ??XML在Java應用程序里變得越來越重要, 廣泛應用于數(shù)據(jù)存儲和
    交換. 比如我們常見的配置文件,都是以XML方式存儲的. XML還應用
    于Java Message Service和Web Services等技術作為數(shù)據(jù)交換.
    因此,正確讀寫XML文檔是XML應用的基礎.
    ??Java提供了SAX和DOM兩種方式用于解析XML,但即便如此,要讀寫一個
    稍微復雜的XML,也不是一件容易的事.

    二、XMLBean簡介

    ????Hibernate已經(jīng)成為目前流行的面向Java環(huán)境的對象/關系數(shù)據(jù)庫映射工具.
    在Hibernate等對象/關系數(shù)據(jù)庫映射工具出現(xiàn)之前,對數(shù)據(jù)庫的操作是
    通過JDBC來實現(xiàn)的,對數(shù)據(jù)庫的任何操作,開發(fā)人員都要自己寫SQL語句
    來實現(xiàn). 對象/關系數(shù)據(jù)庫映射工具出現(xiàn)后,對數(shù)據(jù)庫的操作轉成對
    JavaBean的操作,極大方便了數(shù)據(jù)庫開發(fā). 所以如果有一個類似的工具能夠
    實現(xiàn)將對XML的讀寫轉成對JavaBean的操作,將會簡化XML的讀寫,即使對XML
    不熟悉的開發(fā)人員也能方便地讀寫XML. 這個工具就是XMLBean.

    三、準備XMLBean和XML文檔

    ?? XMLBean是Apache的一個開源項目,可以從http://www.apache.org下載,
    最新的版本是2.0. 解壓后目錄如下:
    xmlbean2.0.0
    ???? +---bin
    ???? +---docs
    ???? +---lib
    ???? +---samples
    ???? +---schemas


    另外還要準備一個XML文檔(customers.xml),
    在本文的例子里,我們將對這個文檔進行讀寫操作. 文檔源碼如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <Customers>
    ????<customer>
    ????????????<id>1</id>
    ????????????<gender>female</gender>
    ????????????<firstname>Jessica</firstname>
    ????????????<lastname>Lim</lastname>
    ????????????<phoneNumber>1234567</phoneNumber>
    ????????????<address>
    ????????????????<primaryAddress>
    ????????????????????????<postalCode>350106</postalCode>
    ????????????????????????<addressLine1>#25-1</addressLine1>
    ????????????????????????<addressLine2>SHINSAYAMA 2-CHOME</addressLine2>
    ????????????????</primaryAddress>
    ????????????????<billingAddress>
    ????????????????????????<receiver>Ms Danielle</receiver>
    ????????????????????????<postalCode>350107</postalCode>
    ????????????????????????<addressLine1>#167</addressLine1>
    ????????????????????????<addressLine2>NORTH TOWER HARBOUR CITY</addressLine2>
    ????????????????</billingAddress>
    ????????????</address>
    ????</customer>
    ????<customer>
    ????????????<id>2</id>
    ????????????<gender>male</gender>
    ????????????<firstname>David</firstname>
    ????????????<lastname>Bill</lastname>
    ????????????<phoneNumber>808182</phoneNumber>
    ????????????<address>
    ????????????????<primaryAddress>
    ????????????????????????<postalCode>319087</postalCode>
    ????????????????????????<addressLine1>1033 WS St.</addressLine1>
    ????????????????????????<addressLine2>Tima Road</addressLine2>
    ????????????????</primaryAddress>
    ????????????????<billingAddress>
    ????????????????????????<receiver>Mr William</receiver>
    ????????????????????????<postalCode>672993</postalCode>
    ????????????????????????<addressLine1>1033 WS St.</addressLine1>
    ????????????????????????<addressLine2>Tima Road</addressLine2>
    ????????????????</billingAddress>
    ????????????</address>
    ????</customer>
    </Customers>


    這是一個客戶的數(shù)據(jù)模型,每個客戶都有客戶編號(ID),姓名,性別(gender),
    電話號碼(phoneNumber)和地址,其中地址有兩個: 首要地址(PrimaryAddress)
    和帳單地址(BillingAddress),每個地址有郵編,地址1,和地址2組成.
    其中帳單地址還有收件人(receiver).

    ????此外,還要準備一個配置文件(文件名customer.xsdconfig),這個文件的
    作用我后面會講,它的內(nèi)容如下:

    <xb:config xmlns:xb="http://xml.apache.org/xmlbeans/2004/02/xbean/config">

    ??<xb:namespace>
    ????<xb:package>sample.xmlbean</xb:package>
    ??</xb:namespace>

    </xb:config>


    四、XMLBean使用步驟

    ????和其他面向Java環(huán)境的對象/關系數(shù)據(jù)庫映射工具的使用步驟一樣,
    在正式使用XMLBean前,我們要作兩個準備.

    ????1. 生成XML Schema文件

    ?????? 什么是XML Schema文件? 正常情況下,每個XML文件都有一個Schema文件,
    ?????? XML Schema文件是一個XML的約束文件,它定義了XML文件的結構和元素.
    ?????? 以及對元素和結構的約束. 通俗地講,如果說XML文件是數(shù)據(jù)庫里的記錄,
    ?????? 那么Schema就是表結構定義.

    ?????? 為什么需要這個文件? XMLBean需要通過這個文件知道一個XML文件的
    ?????? 結構以及約束,比如數(shù)據(jù)類型等. 利用這個Schema文件,XMLBean將會產(chǎn)生
    ?????? 一系列相關的Java Classes來實現(xiàn)對XML的操作. 而作為開發(fā)人員,則是
    ?????? 利用XMLBean產(chǎn)生的Java Classes來完成對XML的操作而不需要SAX或DOM.

    ?????? 怎樣產(chǎn)生這個Schema文件呢? 如果對于熟悉XML的開發(fā)人員,可以自己來
    ?????? 寫這個Schema文件,對于不熟悉XML的開發(fā)人員,可以通過一些工具來完成.
    ?????? 比較有名的如XMLSPY和Stylus Studio都可以通過XML文件來生成Schema
    ?????? 文件. 加入我們已經(jīng)生成這個Schema文件(customer.xsd):
    ??????

    ?????? <?xml version="1.0" encoding="UTF-8"?>
    ?????? <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    ??????????????????elementFormDefault="qualified">
    ???????? <xs:element name="Customers">
    ?????????? <xs:complexType>
    ???????????? <xs:sequence>
    ?????????????? <xs:element maxOccurs="unbounded" name="customer"
    ?????????????????????????? type="customerType"/>
    ???????????? </xs:sequence>
    ?????????? </xs:complexType>
    ???????? </xs:element>
    ?????? <xs:complexType name="customerType">
    ???????????? <xs:sequence>
    ?????????????? <xs:element name="id" type="xs:int"/>
    ?????????????? <xs:element name="gender" type="xs:string"/>
    ?????????????? <xs:element name="firstname" type="xs:string"/>
    ?????????????? <xs:element name="lastname" type="xs:string"/>
    ?????????????? <xs:element name="phoneNumber" type="xs:string"/>
    ?????????????? <xs:element name="address" type="addressType"/>
    ???????????? </xs:sequence>
    ?????? </xs:complexType>
    ???????? <xs:complexType name="addressType">
    ???????????? <xs:sequence>
    ?????????????? <xs:element name="primaryAddress" type="primaryAddressType"/>
    ?????????????? <xs:element name="billingAddress" type="billingAddressType"/>
    ???????????? </xs:sequence>
    ???????? </xs:complexType>

    ???????? <xs:complexType name="primaryAddressType">
    ???????????? <xs:sequence>
    ?????????????? <xs:element name="postalCode" type="xs:string"/>
    ?????????????? <xs:element name="addressLine1" type="xs:string"/>
    ?????????????? <xs:element name="addressLine2" type="xs:string"/>
    ???????????? </xs:sequence>
    ???????? </xs:complexType>
    ???????? <xs:complexType name="billingAddressType">
    ???????????? <xs:sequence>
    ?????? ????????????<xs:element name="receiver" type="xs:string"/>
    ?????????????? <xs:element name="postalCode" type="xs:string"/>
    ?????????????? <xs:element name="addressLine1" type="xs:string"/>
    ?????????????? <xs:element name="addressLine2" type="xs:string"/>
    ???????????? </xs:sequence>
    ???????? </xs:complexType>
    ?????? </xs:schema>
    ??????


    ????2. 利用scomp來生成Java Classes

    ?????? scomp是XMLBean提供的一個編譯工具,它在bin的目錄下. 通過這個工具,
    ?????? 我們可以將以上的Schema文件生成Java Classes.
    ?????? scomp的語法如下:-

    ??????

    ?????? scomp [options] [dirs]* [schemaFile.xsd]* [service.wsdl]* [config.xsdconfig]*
    ??????


    ?????? 主要參數(shù)說明:
    ?????? -src [dir]??????????????????-- 生成的Java Classes存放目錄
    ???? -srconly??????????????????-- 不編譯Java Classes,不產(chǎn)生Jar文件
    ???? -out [jarFileName]??-- 生成的Jar文件,缺省是xmltypes.jar
    ?????? -compiler???????????????? -- Java編譯器的路徑,即Javac的位置
    ?????? schemaFile.xsd????-- XML Schema文件位置
    ?????? config.xsdconfig?? -- xsdconfig文件的位置, 這個文件主要用來制定生成的Java Class
    ??????????????????????????????的一些文件名規(guī)則和Package的名稱,在本文,package是sample.xmlbean

    ?????? 在本文,我是這樣運行的:
    ??????

    ?????? scomp -src build\src??-out build\customerXmlBean.jar schema\customer.xsd
    ???????????? -compiler C:\jdk142_04\bin\javac customer.xsdconfig
    ??????


    ?????? 這個命令行的意思是告訴scomp生成customerXmlBean.jar,放在build目錄下,同時
    ?????? 生成源代碼放在build\src下, Schema文件是customer.xsd,xsdconfig文件是customer.xsdconfig.

    ?????? 其實, 生成的Java源代碼沒有多大作用,我們要的是jar文件.我們先看一下build\src\sample\xmlbean下生成的Classes.
    ??????

    ??????????CustomersDocument.java????-- 整個XML文檔的Java Class映射
    ?????? CustomerType.java??????????????-- 節(jié)點sustomer的映射
    ?????? AddressType.java???????????????? -- 節(jié)點address的映射
    ?????? BillingAddressType.java????????-- 節(jié)點billingAddress的映射
    ?????? PrimaryAddressType.java??????-- 節(jié)點primaryAddress的映射
    ????


    ?????? 好了,到此我們所有的準備工作已經(jīng)完成了. 下面就開始進入重點:利用剛才生成的jar文件讀寫XML.

    五、利用XMLBean讀XML文件

    ????新建一個Java Project,將XMLBean2.0.0\lib\下的Jar文件和剛才我們生成的customerXmlBean.jar加入
    ????到Project的ClassPath.

    ????新建一個Java Class: CustomerXMLBean.??源碼如下:
    ????

    ????package com.sample.reader;

    ????import java.io.File;
    ????
    ????import sample.xmlbean.*;
    ????import org.apache.commons.beanutils.BeanUtils;
    ????import org.apache.xmlbeans.XmlOptions;
    ????public class CustomerXMLBean {
    ????private String filename = null;
    ????
    ????public CustomerXMLBean(String filename) {
    ????????????super();
    ????????????this.filename = filename;
    ????}

    ????public void customerReader() {
    ????????????try {
    ??????????????File xmlFile = new File(filename);
    ??????????????CustomersDocument doc = CustomersDocument.Factory.parse(xmlFile);
    ??????????????CustomerType[] customers = doc.getCustomers().getCustomerArray();
    ??????????
    ??????????????for (int i = 0; i < customers.length; i++) {
    ????????????????CustomerType customer = customers[i];
    ????????????????println("Customer#" + i);
    ????????????????println("Customer ID:" + customer.getId());
    ????????????????println("First name:" + customer.getFirstname());
    ????????????????println("Last name:" + customer.getLastname());
    ????????????????println("Gender:" + customer.getGender());
    ????????????????println("PhoneNumber:" + customer.getPhoneNumber());
    ????????????????// Primary address
    ????????????????PrimaryAddressType primaryAddress = customer.getAddress().getPrimaryAddress();
    ????????????????println("PrimaryAddress:");
    ????????????????println("PostalCode:" + primaryAddress.getPostalCode());
    ????????????????println("AddressLine1:" + primaryAddress.getAddressLine1());
    ????????????????println("AddressLine2:" + primaryAddress.getAddressLine2());
    ????????????????// Billing address
    ????????????????BillingAddressType billingAddress = customer.getAddress().getBillingAddress();
    ????????????????println("BillingAddress:");
    ????????????????println("Receiver:" + billingAddress.getReceiver());
    ????????????????println("PostalCode:" + billingAddress.getPostalCode());
    ????????????????println("AddressLine1:" + billingAddress.getAddressLine1());
    ????????????????println("AddressLine2:" + billingAddress.getAddressLine2());
    ????????????
    ??????????????}
    ????????????} catch (Exception ex) {
    ????????????????????ex.printStackTrace();
    ????????????}
    ????}
    ????private void println(String str) {
    ??????????System.out.println(str);
    ????}
    ?? public static void main(String[] args) {
    ??????String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers.xml";
    ??????????????????
    ???? CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
    ?????????????????? customerXMLBean.customerReader();
    ????}

    ????}
    ????


    ????運行它,參看輸出結果:
    ????

    ?????? Customer#0
    ?????? Customer ID:1
    ?????? First name:Jessica
    ?????? Last name:Lim
    ?????? Gender:female
    ?????? PhoneNumber:1234567
    ?????? PrimaryAddress:
    ?????? PostalCode:350106
    ?????? AddressLine1:#25-1
    ?????? AddressLine2:SHINSAYAMA 2-CHOME
    ?????? BillingAddress:
    ?????? Receiver:Ms Danielle
    ?????? PostalCode:350107
    ?????? AddressLine1:#167
    ?????? AddressLine2:NORTH TOWER HARBOUR CITY

    ?????? Customer#1
    ?????? Customer ID:2
    ?????? First name:David
    ?????? Last name:Bill
    ?????? Gender:male
    ?????? PhoneNumber:808182
    ?????? PrimaryAddress:
    ?????? PostalCode:319087
    ?????? AddressLine1:1033 WS St.
    ?????? AddressLine2:Tima Road
    ?????? BillingAddress:
    ?????? Receiver:Mr William
    ?????? PostalCode:672993
    ?????? AddressLine1:1033 WS St.
    ?????? AddressLine2:Tima Road
    ????

    ????怎么樣,是不是很輕松? XMLBean的威力.

    六、利用XMLBean寫XML文件

    ????利用XMLBean創(chuàng)建一個XML文檔也是一件輕而易舉的事.我們再增加一個Method,
    ????請看一下的Java Class:
    ????

    ????public void createCustomer() {
    ????try {
    ????????// Create Document
    ????????CustomersDocument doc = CustomersDocument.Factory.newInstance();
    ????????// Add new customer
    ????????CustomerType customer = doc.addNewCustomers().addNewCustomer();
    ????????// set customer info
    ????????customer.setId(3);
    ????????customer.setFirstname("Jessica");
    ????????customer.setLastname("Lim");
    ????????customer.setGender("female");
    ????????customer.setPhoneNumber("1234567");
    ????????// Add new address
    ????????AddressType address = customer.addNewAddress();
    ????????// Add new PrimaryAddress
    ????????PrimaryAddressType primaryAddress = address.addNewPrimaryAddress();
    ????????primaryAddress.setPostalCode("350106");
    ????????primaryAddress.setAddressLine1("#25-1");
    ????????primaryAddress.setAddressLine2("SHINSAYAMA 2-CHOME");

    ????????// Add new BillingAddress
    ????????BillingAddressType billingAddress = address.addNewBillingAddress();
    ????????billingAddress.setReceiver("Ms Danielle");
    ????????billingAddress.setPostalCode("350107");
    ????????billingAddress.setAddressLine1("#167");
    ????????billingAddress.setAddressLine2("NORTH TOWER HARBOUR CITY");

    ????????File xmlFile = new File(filename);
    ????????doc.save(xmlFile);
    ????????} catch (Exception ex) {
    ????????????????ex.printStackTrace();
    ????????}

    ??}
    ????

    ????修改main method.
    ????

    ????public static void main(String[] args) {
    ????String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers_new.xml";
    ????????CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
    ????????customerXMLBean.createCustomer();
    ????}
    ????

    ????運行,打開customers_new.xml:
    ????

    ????<?xml version="1.0" encoding="UTF-8"?>
    ????<Customers>
    ????<customer>
    ????????????<id>3</id>
    ????????????<gender>female</gender>
    ????????????<firstname>Jessica</firstname>
    ????????????<lastname>Lim</lastname>
    ????????????<phoneNumber>1234567</phoneNumber>
    ????????????<address>
    ????????????????????<primaryAddress>
    ???????????????????????? <postalCode>350106</postalCode>
    ???????????????????????? <addressLine1>#25-1</addressLine1>
    ?????????????????????????????????????? <addressLine2>SHINSAYAMA 2-CHOME</addressLine2>
    ????????????????????</primaryAddress>
    ????????????????????<billingAddress>
    ????????????????????????<receiver>Ms Danielle</receiver>
    ????????????????????????<postalCode>350107</postalCode>
    ?????????????????????? <addressLine1>#167</addressLine1>
    ?????????????????????? <addressLine2>NORTH TOWER HARBOUR CITY</addressLine2>
    ????????????????????</billingAddress>
    ????????????????????</address>
    ????????????</customer>
    ????</Customers>
    ????



    七、利用XMLBean修改XML文件

    ????我們再增加一個Method:
    ????

    ??????public void updateCustomer(int id,String lastname) {
    ???????? try {
    ????????File xmlFile = new File(filename);
    ????????CustomersDocument doc = CustomersDocument.Factory.parse(xmlFile);
    ????????CustomerType[] customers = doc.getCustomers().getCustomerArray();
    ??????
    ????????for (int i = 0; i < customers.length; i++) {
    ?????????? CustomerType customer = customers[i];
    ??????????if(customer.getId()==id){
    ????????????????customer.setLastname(lastname);
    ????????????????break;
    ????????????}
    ????????}
    ????????doc.save(xmlFile);
    ???????? } catch (Exception ex) {
    ??????????ex.printStackTrace();
    ???????? }
    ?? ????????}
    ????

    ????main method:
    ????

    ????public static void main(String[] args) {
    ???? String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers_new.xml";
    ????????????????????
    ????CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
    ????????????????????
    ????customerXMLBean.updateCustomer(3,"last");
    ????}
    ????

    ????運行之后,我們將會看到客戶編號為3的客戶的lastname已經(jīng)改為last.

    八、利用XMLBean刪除一個customer

    ????再增加一個Method:
    ????

    ????public void deleteCustomer(int id) {
    ???? try {
    ??????File xmlFile = new File(filename);
    ???? CustomersDocument doc = CustomersDocument.Factory.parse(xmlFile);
    ????CustomerType[] customers = doc.getCustomers().getCustomerArray();

    ?? for (int i = 0; i < customers.length; i++) {
    ????????CustomerType customer = customers[i];
    ????????if(customer.getId()==id){
    ????????????????????????customer.setNil() ;
    ????????????????????????break;
    ?????????????? }
    ?? }
    ?? doc.save(xmlFile);
    ?? } catch (Exception ex) {
    ????????ex.printStackTrace();
    ????????}
    ?? }


    ???????? main method:
    ????

    ????public static void main(String[] args) {
    ????String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers_new.xml";
    ????????????????????
    ????CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
    ????????????????????
    ????customerXMLBean.deleteCustomer(3);
    ????}

    ????????
    運行,我們將會看到客戶編號為3的客戶的資料已經(jīng)被刪除.

    九、查詢XML

    ????除了本文在以上講述的,利用XMLBean能輕輕松松完成XML的讀寫操作外,結合XPath和XQuery,
    ?? XMLBean還能完成象SQL查詢數(shù)據(jù)庫一樣方便地查詢XML數(shù)據(jù). 關于XML查詢以及如何創(chuàng)建XML數(shù)據(jù)庫, 我將在另一篇文章里討論.



    十、結束語
    ????XMLBean能幫助我們輕易讀寫XML,這將有助于我們降低XML的學習和使用,有了這個基礎,
    ????開發(fā)人員將為學習更多地XML相關技術和Web Services,JMS等其他J2EE技術打下良好地基礎.


    關于作者:
    葉楓:熱愛Java和Oracle. 在軟件開發(fā)有近10年, 目前在國外一家美國大公司擔任SA, 負責技術研究。作者Blog:http://blog.matrix.org.cn/page/葉楓
    posted @ 2006-12-21 23:10 海思 閱讀(263) | 評論 (0)編輯 收藏

         摘要: 作者的blog: http://yuwang881.blog.sohu.com/http://blog.csdn.net/javachannel/archive/2006/05/24/752437.aspx王昱 yuwang881@gmail.com?? 博客地址http://yuwang881.blog.sohu.com摘要:單點登錄(SSO)的技術被越來越廣泛地運用到各個領域的軟件系統(tǒng)當中。本...  閱讀全文
    posted @ 2006-12-21 22:42 海思 閱讀(392) | 評論 (0)編輯 收藏

    公民身份號碼是特征組合碼,由十七位數(shù)字本體碼和一位數(shù)字校驗碼組成.排列順序從左至右依次為:六位數(shù)字地址碼,八位數(shù)字出生日期碼,三位數(shù)字順序碼和一位數(shù)字校驗碼。1、地址碼表示編碼對象常住戶口所在縣(市、旗、區(qū))的行政區(qū)劃代碼,按GB/T2260的規(guī)定執(zhí)行。

      2、出生日期碼表示編碼對象出生的年、月、日,按GB/T7408的規(guī)定執(zhí)行。年、月、日代碼之間不用分隔符。例:某人出生日期為1966年10月26日,其出生日期碼為19661026。

      3、順序碼表示在同一地址碼所標識的區(qū)域范圍內(nèi),對同年、同月、同日出生的人編定的順序號,順序碼的奇數(shù)分配給男性,偶數(shù)千分配給女性。

      4、校驗碼校驗碼采用ISO7064:1983,MOD11-2校驗碼系統(tǒng)。

      1)十七位數(shù)字本體碼加權求和公式 S=Sum(Ai*Wi),i=0,...,16,先對前17位數(shù)字的權求和 Ai:表示第i位置上的身份證號碼數(shù)字值 Wi:表示第i位置上的加權因子 Wi:7910584216379105842

      2)計算模 Y=mod(S,11)

      3)通過模得到對應的校驗碼 :012345678910 驗碼:10X98765432

      下面是java實現(xiàn)的代碼

      /**IDCard.javaCreatedon2004-11-517:03:37**/packageorg.yz21.study.idcard;

      /***@authorviolin2004-11-517:03:37*Copyrightwww.yz21.org2003-2004*/publicclassIDCard{//wi=2(n-1)(mod11)finalint[]wi={7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2,1};

      //verifydigitfinalint[]vi={1,0,X,9,8,7,6,5,4,3,2};

      privateint[]ai=newint[18];

      publicIDCard(){}

      //verifypublicbooleanVerify(Stringidcard){if(idcard.length()==15){idcard=uptoeighteen(idcard);}if(idcard.length()!=18){returnfalse;}Stringverify=idcard.substring(17,18);if(verify.equals(getVerify(idcard))){returntrue;}returnfalse;}

      //getverifypublicStringgetVerify(Stringeightcardid){intremaining=0;

      if(eightcardid.length()==18){eightcardid=eightcardid.substring(0,17);}

      if(eightcardid.length()==17){intsum=0;for(inti=0;i<17;i++){Stringk=eightcardid.substring(i,i+1);ai=Integer.parseInt(k);}

      for(inti=0;i<17;i++){sum=sum+wi*ai;}remaining=sum%11;}

      returnremaining==2?"X":String.valueOf(vi[remaining]);}

      //15updateto18publicStringuptoeighteen(Stringfifteencardid){Stringeightcardid=fifteencardid.substring(0,6);eightcardid=eightcardid+"19";eightcardid=eightcardid+fifteencardid.substring(6,15);eightcardid=eightcardid+getVerify(eightcardid);returneightcardid;}

      }

      測試代碼:使用的單元測試工具是junit

      /**IDCardTest.javaCreatedon2004-11-517:32:12**/packageorg.yz21.study.idcard;

      importjunit.framework.Test;importjunit.framework.TestCase;importjunit.framework.TestSuite;

      /***@authorviolin2004-11-517:32:12*Copyrightwww.yz21.org2003-2004*/publicclassIDCardTestextendsTestCase{

      privateStringidcard1="11010519491231002X";privateStringidcard2="440524188001010014";

      publicvoidtestVerify(){IDCardidcard=newIDCard();this.assertTrue(idcard.Verify(idcard1));this.assertTrue(idcard.Verify(idcard2));}

      publicstaticTestsuite(){returnnewTestSuite(IDCardTest.class);}

      publicstaticvoidmain(String[]args){junit.textui.TestRunner.run(suite());}}
    posted @ 2006-12-21 21:47 海思 閱讀(369) | 評論 (0)編輯 收藏

    僅列出標題  下一頁
    主站蜘蛛池模板: 免费一级毛片不卡不收费| 男女超爽刺激视频免费播放| 色www永久免费| **实干一级毛片aa免费| 在线免费观看污网站| 亚洲第一网站男人都懂| 亚洲成AV人片天堂网无码| 亚洲人成网站日本片| 福利片免费一区二区三区| 99久久精品毛片免费播放| 亚欧在线精品免费观看一区| 宅男666在线永久免费观看| 亚洲色成人中文字幕网站| 亚洲精品偷拍无码不卡av| 亚洲AV成人无码网站| a毛片免费全部播放完整成| 91精品免费在线观看| 亚洲M码 欧洲S码SSS222| 久久国产精品亚洲综合| 亚洲精品无播放器在线播放| 久久国产精品免费一区| 美女被免费喷白浆视频| 又粗又大又猛又爽免费视频| 亚洲制服中文字幕第一区| 无码亚洲成a人在线观看| 国产激情免费视频在线观看| 女人与禽交视频免费看| 国产精品亚洲一区二区三区在线| 亚洲五月丁香综合视频| 九九热久久免费视频| 最近中文字幕无免费视频| 亚洲啪啪AV无码片| 亚洲中文字幕久久无码| 麻豆精品成人免费国产片| 四虎永久在线精品免费观看地址| 亚洲成人激情在线| 男女作爱免费网站| 在线视频观看免费视频18| 亚洲国产精品嫩草影院在线观看 | 亚洲六月丁香六月婷婷蜜芽| 菠萝菠萝蜜在线免费视频|