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

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

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

    JAVA學習點點滴滴

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

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

    2006年1月21日 #

    創建型模式

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

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

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

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

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

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

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

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

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

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

    結構型模式

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    行為模式

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

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

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

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

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

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

    ?

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

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

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

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

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

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

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

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

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

    ……

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    ?

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

    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
    文檔選項
    將此頁作為電子郵件發送

    將此頁作為電子郵件發送

    未顯示需要 JavaScript 的文檔選項

    樣例代碼


    拓展 Tomcat 應用

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


    級別: 初級

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

    2007 年 1 月 18 日

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

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

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

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

    關于這個系列

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

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

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

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

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

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

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

    立即開始

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

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



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

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

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



    圖 1. Hello, world
    Hello, World.

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



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

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



    圖 2. 延遲執行
    延遲執行




    回頁首


    高階函數

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



    清單 3. 用變量操縱函數
    				
    <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>
    

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



    圖 3. 操縱函數

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

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



    清單 4. 高階函數
    				
    <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>
    

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



    圖 4. 高階函數
    高階函數

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





    回頁首


    動態類型

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

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

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

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

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

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



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

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



    圖 5. 引入屬性
     引入屬性

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

    可以輕松地重寫 清單 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 的不同概念之間可以如此輕松地來回變換,其含義上的變化很大 —— 比如,是引入行為還是引入數據 —— 但語法上的變化卻很小。該語言很好的延展性是它的一種優勢,但同樣也是其缺點所在。實際上,該語言本身的對象模型就是 JavaScript 延展程度的一種體現。





    回頁首


    對象模型

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

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

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



    清單 7. 創建一個構造函數
    				
    <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. 創建一個構造函數
    構造函數

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

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

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

    現在我還要更深入一步。您還可以使用名為 prototype 實例變量來指定對象的基礎。方法是設置 prototype 實例變量使其指向繼承鏈的父。如此設置 prototype 之后,您所創建的對象會為未指定的那些對象繼承屬性和函數。這樣一來,您就可以模仿面向對象的繼承概念。以清單 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 中,創建了一個 Dog 原型。此原型基于 AnimalDog 重定義 speak() 方法但卻不會對 name() 方法做任何改動。隨后,將原型 Dog 設置成 Animal。圖 7 顯示了其結果:



    圖 7. 通過原型繼承
    繼承

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

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

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

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

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





    回頁首


    結束語

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

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

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


    參考資料

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

    1、取出剛剛插入(刪除)的數據SELECT 字段名 FROM INSERTED(DELETED)
    2、對于UPDATE實際上是先DELETE然后再INSERT所以如果想得到UPDATE前后的數據值,應該先從DELETED取出,然后從INSERTED取出;
    3、IF UPDATE(列名)可以判斷更新或插入哪一個字段的值;
    4、@@ROWCOUNT可以判斷上一行查詢操作得到的列數;
    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--從游標中取出數據
    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 海思 閱讀(215) | 評論 (0)編輯 收藏

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

    摘要:

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


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

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


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


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

    AccessDecisionVoter
    ?????? 注意上節的accessDecisionManager是一個AffirmativeBased類,它對于用戶授權的投票策略是,只要通過其中的一個授權投票檢查,即可通過;它的allowIfAllAbstainDecisions屬性值是false,意思是如果所有的授權投票是都是棄權,則通不過授權檢查。
    ?????? Acegi安全系統包括了幾個基于投票策略的AccessDecisionManager,上節的RoleVoter就是其中的一個投票策略實現,它是AccessDecisionVoter的一個子類。AccessDecisionVoter的具體實現類通過投票來進行授權決策,AccessDecisionManager則根據投票結果來決定是通過授權檢查,還是拋出AccessDeniedException例外。
    ?????? AccessDecisionVoter接口共有三個方法:
    public int vote(Authentication authentication, Object object, ConfigAttributeDefinition config);
    public boolean supports(ConfigAttribute attribute);
    public boolean supports(Class clazz);
    ?????? 其中的vote方法返回int返回值,它們是AccessDecisionVoter的三個靜態成員屬性:ACCESS_ABSTAIN,,ACCESS_DENIED和ACCESS_GRANTED,它們分別是棄權,否決和贊成。
    ?????? Acegi安全系統中,使用投票策略的AccessDecisionManager共有三個具體實現類:AffirmativeBased、ConsensusBased和UnanimousBased。它們的投票策略是,AffirmativeBased類只需有一個投票贊成即可通過;ConsensusBased類需要大多數投票贊成即可通過;而UnanimousBased類需要所有的投票贊成才能通過。
    ?????? RoleVoter類是一個Acegi安全系統AccessDecisionVoter接口的實現。如果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 允許開發人員定義多個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,當輸出時,只有級別高過配置中規定的 級別的信息才能真正的輸出,這樣就很方便的來配置不同情況下要輸出的內容,而不需要更改代碼,這點實在是方便啊。

    2、Log4j的配置文件
    ??雖然可以不用配置文件,而在程序中實現配置,但這種方法在如今的系統開發中顯然是不可取的,能采用配置文件的地方一定一定要用配置文件。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, ...,其中level就是設置需要輸出信息的級別,后面是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(每天產生一個日志文件)
    ??org.apache.log4j.RollingFileAppender(文件大小到達指定尺寸的時候產生新文件)
    ??org.apache.log4j.WriterAppender(將日志信息以流格式發送到任意指定的地方)
    配置日志信息的格式(布局),其語法為:
    ??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(包含日志產生的時間、線程、類別等等信息)

    3、Log4j在程序中的使用
    ??要在自己的類中使用Log4j,首先聲明一個靜態變量Logger logger=Logger.getLog("classname");在使用之前,用PropertyConfigurator.configure ("配置文件")配置一下,現在就可以使用了,用法如下: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,就其目前提供的功能,應該可以滿足絕大多數應用的需求。

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

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

    [web.xml]
    實現認證和授權的最常用的方法是通過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"相關內容注釋掉即可;
    3) 如果你的應用不需要Spring提供的遠程訪問機制,如Hessian and Burlap,將"Acegi HTTP BASIC Authorization
    Filter"相關內容注釋掉即可。

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

    1) 首先,你的數據庫中必須具有保存用戶名和密碼的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) 添加訪問你的數據庫的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中定義哪些頁面需要權限訪問,需要根據自己的應用需求進行修改,我上面給出
    的定義的意思是這樣的:
    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可實現對對象中的方法的權限控制,使用方法可參看Acegi自帶的文檔
    和contact范例。

    [最后要說的]
    本來以為只是說明如何使用Acegi而已,應該非常簡單,但真正寫起來才發現想要條理清楚的理順所有需要的bean還是很
    困難的,但愿我沒有遺漏太多東西,如果我的文章有什么遺漏或錯誤的話,還請參看Acegi自帶的quick-start范例,但請
    注意,這個范例是不能直接拿來用的。
    分析和學習Spring中的jpetstore用戶管理
    ??存在用戶的系統,必然需要用戶的登錄和認證,今天就通過分析Spring中自帶的jpetstore的例子來學習一下如何實現在Spring構架的系統中用戶登錄。
    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的構造函數中得到,原來為EditAccountForm;??
    2). EditoAccountForm.jsp中顯得非常亂,其實沒有多少難理解的地方,最主要的是這個form既是添加新用戶的,又是編輯用戶信息的,所以顯得有點亂糟糟的。
    2、添加好了新用戶,接下來看看如何登錄,在jpetstore-servlet中發現這兩個相關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實現了preHandle,因此在請求上面的map頁面時,首先要經過這個Interceptor,看看 SignonInterceptor的源碼,原來在其中為signon.jsp賦予一個signonForwardAction對象,呵呵,總算明白了。
    3). 接下來去學習一下SignonController,其主體部分中可以看出,首先取出用戶輸入的username和password,然后到數據庫中驗證 有沒有這個用戶,如果沒有這個用戶,返回各錯誤頁面;如果成功,首先生成一個UserSession對象,在request的session加入這個 userSession,注意這部分代碼中給出了PagedListHolder分頁的簡單使用方法,關于分頁顯示,以后再學習吧。
    3、登錄成功后,就可以根據不同的用戶設施不同的行為了,取得用戶信息,無非就是從session取出userSession即可。
    posted @ 2006-12-27 23:20 海思 閱讀(222) | 評論 (0)編輯 收藏

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

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

    更多問題,可以查看以下內容:

    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 海思 閱讀(459) | 評論 (0)編輯 收藏

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

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

    二、XMLBean簡介

    ????Hibernate已經成為目前流行的面向Java環境的對象/關系數據庫映射工具.
    在Hibernate等對象/關系數據庫映射工具出現之前,對數據庫的操作是
    通過JDBC來實現的,對數據庫的任何操作,開發人員都要自己寫SQL語句
    來實現. 對象/關系數據庫映射工具出現后,對數據庫的操作轉成對
    JavaBean的操作,極大方便了數據庫開發. 所以如果有一個類似的工具能夠
    實現將對XML的讀寫轉成對JavaBean的操作,將會簡化XML的讀寫,即使對XML
    不熟悉的開發人員也能方便地讀寫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>


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

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

    <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環境的對象/關系數據庫映射工具的使用步驟一樣,
    在正式使用XMLBean前,我們要作兩個準備.

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

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

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

    ?????? 怎樣產生這個Schema文件呢? 如果對于熟悉XML的開發人員,可以自己來
    ?????? 寫這個Schema文件,對于不熟悉XML的開發人員,可以通過一些工具來完成.
    ?????? 比較有名的如XMLSPY和Stylus Studio都可以通過XML文件來生成Schema
    ?????? 文件. 加入我們已經生成這個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]*
    ??????


    ?????? 主要參數說明:
    ?????? -src [dir]??????????????????-- 生成的Java Classes存放目錄
    ???? -srconly??????????????????-- 不編譯Java Classes,不產生Jar文件
    ???? -out [jarFileName]??-- 生成的Jar文件,缺省是xmltypes.jar
    ?????? -compiler???????????????? -- Java編譯器的路徑,即Javac的位置
    ?????? schemaFile.xsd????-- XML Schema文件位置
    ?????? config.xsdconfig?? -- xsdconfig文件的位置, 這個文件主要用來制定生成的Java Class
    ??????????????????????????????的一些文件名規則和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??????????????-- 節點sustomer的映射
    ?????? AddressType.java???????????????? -- 節點address的映射
    ?????? BillingAddressType.java????????-- 節點billingAddress的映射
    ?????? PrimaryAddressType.java??????-- 節點primaryAddress的映射
    ????


    ?????? 好了,到此我們所有的準備工作已經完成了. 下面就開始進入重點:利用剛才生成的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創建一個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已經改為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的客戶的資料已經被刪除.

    九、查詢XML

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



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


    關于作者:
    葉楓:熱愛Java和Oracle. 在軟件開發有近10年, 目前在國外一家美國大公司擔任SA, 負責技術研究。作者Blog:http://blog.matrix.org.cn/page/葉楓
    posted @ 2006-12-21 23:10 海思 閱讀(264) | 評論 (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)的技術被越來越廣泛地運用到各個領域的軟件系統當中。本...  閱讀全文
    posted @ 2006-12-21 22:42 海思 閱讀(392) | 評論 (0)編輯 收藏

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

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

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

      4、校驗碼校驗碼采用ISO7064:1983,MOD11-2校驗碼系統。

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

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

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

      下面是java實現的代碼

      /**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 海思 閱讀(370) | 評論 (0)編輯 收藏

    說明:復制表(只復制結構,源表名:a  新表名:b)
    SQL:  select  *  into  b  from  a  where  1<>1
    說明:拷貝表(拷貝數據,源表名:a  目標表名:b)
    SQL:  insert  into  b(a,  b,  c)  select  d,e,f  from  b;
    說明:顯示文章、提交人和最后回復時間
    SQL:  select  a.title,a.username,b.adddate  from  table  a,(select  max(adddate)  adddate  from  table  where  table.title=a.title)  b
    說明:外連接查詢(表名1:a  表名2:b)
    SQL:  select  a.a,  a.b,  a.c,  b.c,  b.d,  b.f  from  a  LEFT  OUT  JOIN  b  ON  a.a  =  b.c
    說明:日程安排提前五分鐘提醒
    SQL:    select  *  from  日程安排  where  datediff('minute',f開始時間,getdate())>5
    說明:兩張關聯表,刪除主表中已經在副表中沒有的信息
    SQL:    
    delete  from  info  where  not  exists  (  select  *  from  infobz  where  info.infid=infobz.infid  )  
    說明:--
    SQL:    
    SELECT  A.NUM,  A.NAME,  B.UPD_DATE,  B.PREV_UPD_DATE
       FROM  TABLE1,  
           (SELECT  X.NUM,  X.UPD_DATE,  Y.UPD_DATE  PREV_UPD_DATE
                   FROM  (SELECT  NUM,  UPD_DATE,  INBOUND_QTY,  STOCK_ONHAND
                                   FROM  TABLE2
                               WHERE  TO_CHAR(UPD_DATE,'YYYY/MM')  =  TO_CHAR(SYSDATE,  'YYYY/MM'))  X,  
                           (SELECT  NUM,  UPD_DATE,  STOCK_ONHAND
                                   FROM  TABLE2
                               WHERE  TO_CHAR(UPD_DATE,'YYYY/MM')  =  
                                           TO_CHAR(TO_DATE(TO_CHAR(SYSDATE,  'YYYY/MM')  ||  '/01','YYYY/MM/DD')  -  1,  'YYYY/MM')  )  Y,  
                   WHERE  X.NUM  =  Y.NUM  (+)
                       AND  X.INBOUND_QTY  +  NVL(Y.STOCK_ONHAND,0)  <>  X.STOCK_ONHAND  )  B
    WHERE  A.NUM  =  B.NUM
    說明:--
    SQL:    
    select  *  from  studentinfo  where  not  exists(select  *  from  student  where  studentinfo.id=student.id)  and  系名稱='"&strdepartmentname&"'  and  專業名稱='"&strprofessionname&"'  order  by  性別,生源地,高考總成績
    說明:
    從數據庫中去一年的各單位電話費統計(電話費定額賀電化肥清單兩個表來源)
    SQL:  
    SELECT  a.userper,  a.tel,  a.standfee,  TO_CHAR(a.telfeedate,  'yyyy')  AS  telyear,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '01',  a.factration))  AS  JAN,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '02',  a.factration))  AS  FRI,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '03',  a.factration))  AS  MAR,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '04',  a.factration))  AS  APR,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '05',  a.factration))  AS  MAY,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '06',  a.factration))  AS  JUE,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '07',  a.factration))  AS  JUL,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '08',  a.factration))  AS  AGU,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '09',  a.factration))  AS  SEP,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '10',  a.factration))  AS  OCT,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '11',  a.factration))  AS  NOV,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '12',  a.factration))  AS  DEC
    FROM  (SELECT  a.userper,  a.tel,  a.standfee,  b.telfeedate,  b.factration
                   FROM  TELFEESTAND  a,  TELFEE  b
                   WHERE  a.tel  =  b.telfax)  a
    GROUP  BY  a.userper,  a.tel,  a.standfee,  TO_CHAR(a.telfeedate,  'yyyy')
    說明:四表聯查問題:
    SQL:  select  *  from  a  left  inner  join  b  on  a.a=b.b  right  inner  join  c  on  a.a=c.c    inner  join  d  on  a.a=d.d  where  .....

    說明:得到表中最小的未使用的ID號
    SQL:
    SELECT  (CASE  WHEN  EXISTS(SELECT  *  FROM  Handle  b  WHERE  b.HandleID  =  1)  THEN  MIN(HandleID)  +  1  ELSE  1  END)  as  HandleID
    FROM    Handle
    WHERE  NOT  HandleID  IN  (SELECT  a.HandleID  -  1  FROM  Handle  a)
    posted @ 2006-02-22 22:04 海思 閱讀(185) | 評論 (0)編輯 收藏

    0.  精彩網址
    http://www.cfanclub.net/fav.htm
    1.vc++技術內幕第四版  (潘愛民)
    ftp://210.32.157.56/課件/c++primer/vc++技術內幕IV(潘愛民).rar
    2.C++經典對話系列
    中文:http://www.jka77.com/book/cvst_cn.chm

    3.MFC  Windows  程序設計(第二版)
    英文版:http://www.jka77.com/book/progmfc2.chm
    中文版:暫無,制作中...
    4.Effective  C++中文版:
    http://dlb.pchome.net/development/reference/effectiveCplus.zip
    5.More  Effective  C++中文版-zhc譯
    http://cable.pchome.net/development/reference/MEC0410.zip

    6.More  Effective  C++中文版-候捷譯
    http://www.nethovel.com/resources/MoreEffectiveC++(WQ).zip

    7.Essential  C++中文版(全)-候捷譯
    http://www.nethovel.com/resources/Essential%20C++中文版(全).rar

    8.深入淺出MFC  2/e
    http://218.30.21.125:8084/ebook/programme/mfc2e.zip

    9.代碼大全中文版
    http://www.delphidevelopers.com/  ...  /CodeComplet110.zip

    11.C++經典對話系列
    中文:http://www.jka77.com/book/cvst_cn.chm

    12.MFC  Windows  程序設計(第二版)
    英文版:http://www.jka77.com/book/progmfc2.chm
    中文版:暫無,制作中...

    13.數據結構  C++  語言描述(中文版)
    http://www.code-labs.com/manual/c_c015.zip

    14.Java編程思想中文版
    ftp://202.118.72.12/pub/doc-book/Java/Java編程思想.zip

    15.C++標準庫英文版
    ftp://166.111.64.4/incoming/新文件夾/f/The%20C++%20Standard%20Library(with%20TOC).pdf

    16.Windows核心編程  
    英文:http://www.fmdstudio.net/book/prgapps4.zip

    17.TCP-IP詳解卷1:協議
    ftp://202.204.4.161/學習資料/TCPIP/TCP-IP詳解卷1:協議.pdf

    18.TCP-IP詳解卷2:實現
    ftp://202.204.4.161/學習資料/TCPIP/TCP-IP詳解卷3:TCP事務協議,HTTP,NNTP.pdf

    19.TCP-IP詳解卷3:TCP事務協議
    ftp://202.204.4.161/學習資料/TCPIP/TCP-IP詳解卷2:實現.pdf

    20.實用算法的分析與程序設計
    ftp://202.204.8.10/[4]%20編程資源/[%20書籍資料%20]/[算法與數據結構]/實用算法的分析與程序設計.rar

    21.vc++技術內幕第四版  (潘愛民)
    ftp://210.32.157.56/課件/c++primer/vc++技術內幕IV(潘愛民).rar

    22.C++  Primer英文版:
    http://computerstep.w18.net/C/C++%20Primer.zip

    23.Effective  C++中文版:
    http://dlb.pchome.net/development/reference/effectiveCplus.zip

    24.More  Effective  C++中文版-zhc譯
    http://cable.pchome.net/development/reference/MEC0410.zip

    25.More  Effective  C++中文版-候捷譯
    http://www.nethovel.com/resources/MoreEffectiveC++(WQ).zip

    26.Essential  C++中文版(全)-候捷譯
    http://www.nethovel.com/resources/Essential%20C++中文版(全).rar

    27.Programming  Windows程式開發設計指南-Petzoldi著  余孟學  譯
    中文版:http://www.nethovel.com/resources/ProgrammingWindows_tw.chm
    英文版:http://www.nethovel.com/resources/Petzoldi.chm

    28.WinAsm32匯編教程-  Iczelion
    http://www.nethovel.com/resources/winasm.chm

    29.Windows  95  程序設計指南-候捷譯
    http://www.nethovel.com/resources/win95adg.zip

    30.Thinking  in  C++  2nd  Edition(C++編程思想)
    英文版:http://www.nethovel.com/resources/ThinkinginC++.zip
    中文版:http://www.dingbing.com/book/thinkc.zip

    31.人月神話-中文版
    http://www.goodassister.com/book/rysh.pdf

    32.The  C++  Programming  Language英文
    http://computerstep.w18.net/C/Th  ...  ming%20Language.rar

    33.VC技術內幕第五版  http://www.helpwork.com/downdata  ...  k/vc++2/invcpp5.chm

    34.com技術內幕
    http://www.helpwork.com/book/html/user/download.asp?id=1123

    35.com+技術內幕
    http://www.helpwork.com/book/html/user/download.asp?id=952

    36.新編  Windows  API參考大全
    http://www.4046.com/nnsrc/down/WindowsAPIdq.rar

    37.The  C  programming  Language  //  By  Brian  W.  Kernighan  and  Dennis  M.  Ritchie
    下載地址:http://www.jka77.com/book/The_C_programmin.chm

    38.C語言編程手冊
    下載地址:http://www.jka77.com/book/CL.chm

    39.Delphi  7高效數據庫程序設計  
    By  李維
    下載地址:http://www.codestudy.net/book/download.asp?id=1163&sort=5

    40.Windows網絡編程(第2版)
    By  Anthony  Jones,Jim  Ohlund  清華大學出版社
    下載地址:英文版:http://www.guxiang.com/epubcn/re  ...  rog_for_win_2nd.zip

    41.Windows2000編程技術內幕
    By  Mickey  Williams  機械工業出版社
    下載地址:ftp://ftp.frontfree.net/Pub/Books/C&C++/VC/Windows2000編程技術內幕.rar

    42.數據倉庫
    By  W.H.Inmon  清華大學出版社
    下載地址1:http://tips.9hao.com/vvbksd/20011120/數據倉庫.zip
    下載地址2:  ftp://ftp.math.nankai.edu.cn/Ebo  ...  %BE%DD%B2%D6%BF%E2/

    43.編碼的奧秘
    By  Charles  Petzold  機械工業出版社
    下載地址:ftp://ftp.math.nankai.edu.cn/Ebo  ...  %B5%C4%B0%C2%C3%D8/

    44.編譯原理及實踐
    By  Louden,  K.C  機械工業出版社
    下載地址:ftp://ftp.math.nankai.edu.cn/Ebo  ...  %BC%B0%CA%B5%BC%F9/

    45.Inside  C++  Object  Model(深度探索C++對象模型)
    By  Lippman  候捷譯
    下載地址:http://www.jka77.com/book/inside-the-cpp-object-model.pdf

    46.C++標準程序庫
    By  Josuttis  
    下載地址1:http://www.codestudy.net/book/download.asp?id=1205&sort=5
    下載地址2:  ftp://ftp.math.nankai.edu.cn/Ebook/C_C++/The  Cpp  Standard  Library.pdf

    47.STL源碼剖析
    By  候捷
    下載地址:ftp://ftp.math.nankai.edu.cn/Ebook/C_C++/STL源碼剖析--侯捷.pdf

    48.C++批判(第三版)  -看看C++的壞話!
    By  I  don't  know
    下載地址:http://www.jka77.com/book/CPPPP.pdf

    49.程序設計實踐
    下載地址:ftp://ftp.math.nankai.edu.cn/Ebo  ...  %BC%C6%CA%B5%BC%F9/

    50.c++沉思錄
    By  Andrew  Koenig  Barbara  Moo  人民郵電出版社
    下載地址:http://www.codestudy.net/book/download.asp?id=1261&sort=5

    51.C++Builder4技術內幕  (這本書俺不知道好不好:-))
    By  I  don't  Know
    下載地址:http://www.codestudy.net/book/download.asp?id=1254&sort=5

    52.下面兩本書一般大家硬盤里都有的吧,而且很老了,但是為了全面,就提上來吧
    (1)Windows  95  程式設計指南  -  候捷
    下載地址:http://jjhou.csdn.net/win95-a-developers-guide.pdf
    (2)Windows  95  系統程式設計大奧秘  -  候捷
    下載地址:http://jjhou.csdn.net/windows95-system-programming-secrets.pdf

    53.  中國大百科全書·數學
    下載地址:ftp://ftp.math.nankai.edu.cn/Ebook/中國大百科全書/中國大百科全書·數學.pdf

    54、4.0M  Bjarne  Stroustrup  -  The  C++  Programming  Language
    http://www.u-n-f.com/books/archi  ...  g%20Language.tar.gz

    55、1.0M  Richard  Stevens  -  TCP-IP  Illustrated
    http://www.u-n-f.com/books/archive/TCP-IP%20Illustrated.tar.gz

    56、4.5M  Randall  Hyde  -  Art  Of  Assembly
    http://www.u-n-f.com/books/archi  ...  f%20Assembly.tar.gz

    57、2.1M  M.  Abrash  -  Zen  of  Graphics  Programming
    http://www.u-n-f.com/books/archi  ...  s%20Programming.zip

    58、249k  Kernighan  and  Ritche  -  The  C  Programming  Language
    http://www.u-n-f.com/books/archi  ...  ming%20Language.zip

    59、3.3M  Bruce  Schneier  -  Applied  Cryptography
    http://www.u-n-f.com/books/archi  ...  %20Cryptography.zip

    60、PHP4_Grundlagen_und_Profiwissen
    http://www.u-n-f.com/books/archi  ...  und_Profiwissen.pdf

    61.《C++  Builder高級編程技術》  
    http://www.dingbing.com/book/builder.zip

    62.《VC++  6.0  TLR  模板庫參考手冊》
    http://www.easysea.com/diannao/download/prog/c/mbkc.zip

    63.《BORLAND  C++  BUILDER  實用培訓教程》  
    http://202.101.232.120/book/open  ...  name=BC98_CB526.zip

    64.《Delphi高級開發指南》  
    http://www.pcbookcn.com/s10899bo  ...  phi_gjkfzn_for3.rar

    65.《新編  Windows  API參考大全》  
    ftp://book:book@down.pcbookcn.com/pro/delphi/新編Windows_API_參考大全.rar

    66.《Delphi深度歷險-附書源碼》  
    http://www.pcbookcn.com/s10899bo  ...  elphi_sdlx_code.rar

    67.《Delphi  7高效數據庫程序設計》
    ftp://book:book@down.pcbookcn.com/pro/delphi/李維的新書《Delphi7高效數據庫程序設計》.rar

    68.《Delphi7開發指南》
    ftp://book:book@down.pcbookcn.com/pro/delphi/delphi7開發指南.rar

    69.《Delphi6集成開發環境》  
    ftp://book:book@down.pcbookcn.com/pro/delphi/Delphi6集成開發環境.rar

    70.《Delphi6數據庫編程》  
    ftp://book:book@down.pcbookcn.com/pro/delphi/Delphi6數據庫編程.rar

    72.《Delphi5.xADO_MTS_COM+高級程序設計篇》
    ftp://book:book@down.pcbookcn.co  ...  lphi5.xADO_MTS_COM+高級程序設計篇.rar

    73.《VISUAL  BASIC  編程標準》  
    http://www.dingbing.com/book/vb.zip

    74.《Visual  Basic6.0中文版程序員指南》  
    http://www.easysea.com/diannao/download/prog/vb/zwbc.zip

    75.《Visual  Basic  6.0  控件參考手冊》  
    http://www.easysea.com/diannao/download/prog/vb/kjck.zip

    76.《Visual  Basic  6.0中文版語言參考手冊》  
    http://www.easysea.com/diannao/download/prog/vb/zwby.zip

    77.《Visual  Basic  6.0  開發寶典》  
    http://www.easysea.com/diannao/download/prog/vb/kfbd.zip

    78.《Visual  Basic  6.0  實例教程》  
    http://www.easysea.com/diannao/download/prog/vb/sljc.zip

    79.《VB  6.0  中文版實用參考手冊》  
    http://www.easysea.com/diannao/download/prog/vb/syck.zip

    80.《Visual  Basic  6開發人員指南》  
    http://www.easysea.com/diannao/download/prog/vb/kfzn.zip

    81.《VB  和  SQL  Server  編程指南(第五版)》  
    http://www.easysea.com/diannao/download/prog/vb/bczn.zip

    82.《Jbuilder  5  中文幫助》  
    http://www.pdown.net/download.asp?downid=2&id=991

    83.《JBuilder開發人員指南》  
    http://youth.dlmu.edu.cn/book/list_down.php?bkid=224

    84.《Win32的Internet函數說明》  
    檔案大小:  245248K  
    http://www.easysea.com/diannao/download/prog/windows/win32int.zip

    85.《Visual  InterDev  從入門到精通》  
    http://www.easysea.com/diannao/download/prog/interdev/crmd.wdl

    86.《Visual  InterDev  6.0  Web  參考手冊  》  
    http://www.easysea.com/diannao/download/prog/interdev/jsck.zip

    87.《Visual  InterDev  6.0  Guide  程序員》
    http://www.easysea.com/diannao/download/prog/interdev/cxyz.zip

    88.《javascript  程序開發手冊》  
    http://www.cty99.com/Templet/bookdownmore.asp?booktype=script#

    89.《JAVA  大全》  
    http://www.easysea.com/diannao/download/prog/java/cxkf.zip

    90.《Visual  J++  6.0  WFC  類庫參考手冊》  
    http://www.easysea.com/diannao/download/prog/java/lkck.zip

    91.《Java聯想(中文)》  
    http://www.easysea.com/diannao/download/prog/java/lkck.zip

    92.《Oracle  8  實用大全》
    http://www.easysea.com/diannao/download/prog/oracle/sydq.zip

    93.《Microsoft  SQL  Server  管理員手冊》  
    http://www.easysea.com/diannao/download/prog/sql/glys.zip

    94.《掌握ACCESS開發》  
    http://www.easysea.com/diannao/download/prog/sql/glys.zip

    95.《Oracle  Performance  Tuning  and  Optimization》  
    http://www.oradb.net/book/oracle_pt.zip

    96.《Oracle  ProC  程序設計》  
    http://www.oradb.net/book/oracleproc.zip

    97.《Oracle8初學者指南》  
    http://www.easysea.com/diannao/download/prog/oracle/cxzz.zip

    98.《RED  HAT  LINUX  6大全》  
    http://www.dingbing.com/book/redhatall.zip

    99.《RED  HAT  LINUX  6管理工具》  
    http://www.dingbing.com/book/redhatman.zip

    100.《VC++高級編程》  
    http://www.easysea.com/diannao/download/prog/c/vcgj.zip
    posted @ 2006-02-22 22:03 海思 閱讀(338) | 評論 (0)編輯 收藏

    本文章對:
    發送普通郵件,接受普通郵件
    發送帶有附件的郵件,接收帶有附件的郵件
    發送html形式的郵件,接受html形式的郵件
    [b[發送帶有圖片的郵件等做了一個總結。
    程序代碼:  
    程序代碼:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import com.borland.jbcl.layout.*;
    import javax.mail.*;
    import java.util.*;
    import javax.mail.internet.*;
    import java.io.*;
    import javax.activation.*;


    public String host="smtp.163.com";
    public String username="abcdefg";
    public String password="abcdefg";
    public String mail_head_name="this is head of this mail";
    public String mail_head_value="this is head of this mail";
    public String mail_to="xyz@163.com";
    public String mail_from="abcdefg@163.com";
    public String mail_subject="this is the subject of this test mail";
    public String mail_body="this is the mail_body of this test mail";
    //此段代碼用來發送普通電子郵件
    void jButton1_actionPerformed(ActionEvent e) {
    try
    {
    Properties props = new Properties();//獲取系統環境
    Authenticator auth = new Email_Autherticator();//進行郵件服務器用戶認證

    props.put("mail.smtp.host",host);
    props.put("mail.smtp.auth","true");
    Session session = Session.getDefaultInstance(props,auth);
    //設置session,和郵件服務器進行通訊。
    MimeMessage message = new MimeMessage(session);
    message.setContent("Hello","text/plain");//設置郵件格式
    message.setSubject(mail_subject);//設置郵件主題
    message.setText(mail_body);//設置郵件正文
    message.setHeader(mail_head_name,mail_head_value);//設置郵件標題
    message.setSentDate(new Date());//設置郵件發送日期

    Address address = new InternetAddress(mail_from,"sunxiaoming");
    message.setFrom(address); //設置郵件發送者的地址

    //如果要對郵件發送者進行多個參數的設置,可以用以下語句
    // Address address[] = {new InternetAddress("sunxm@oaklet.co.jp","sunxmatoaklet"),new InternetAddress("firstsxm@hotmail.com","sunxmathotmail")};
    // message.addFrom(address);

    Address toAddress = new InternetAddress(mail_to);//設置郵件接收方的地址
    message.addRecipient(Message.RecipientType.TO,toAddress);
    // Address ccAddress = new InternetAddress("firstsxm@hotmail.com");//設置郵件抄送者的地址
    // message.addRecipient(Message.RecipientType.CC,ccAddress);


    Transport.send(message);//發送郵件
    /* // to get a specific instance from the session for your protocol.pass along the username and password
    // (blank if unnecessary).send the message,and close the connection;
    message.saveChanges();
    Transport transport = session.getTransport("smtp");
    transport.connect(host,username,password);
    transport.sendMessage(message,message.getAllRecipients());
    transport.close();
    */

    System.out.println("send ok!");
    }
    catch(Exception ex)
    {
    System.out.println("faild"+ex);
    }
    }

    //此段代碼用來進行服務器對用戶的認證
    public class Email_Autherticator extends Authenticator
    {
    public Email_Autherticator()
    {
    super();
    }
    public PasswordAuthentication getPasswordAuthentication()
    {
    return new PasswordAuthentication(username,password);
    }
    }
    //該程序為接收郵件
    void jButton2_actionPerformed(ActionEvent e) {
    try
    {
    Properties props = System.getProperties(); //獲取系統變量
    Authenticator auth = new Email_Autherticator();
    props.put("mail.smtp.host",host);
    props.put("mail.smtp.auth","true");
    Session session = Session.getDefaultInstance(props,auth); //建立session
    Store store = session.getStore("pop3");
    store.connect(host,username,password);

    //After connecting to the Store,you can get a Folder,which must be opened before you can read messages from it:
    Folder folder = store.getFolder("INBOX");//連接到Store后,取得一個文件夾,一般默認的是INDEX
    folder.open(Folder.READ_WRITE);//READ_ONLY為打開方式
    Message message[] = folder.getMessages();//從文件夾獲取郵件信息

    //可以用兩種方式去獲得郵件信息,getContent()用來獲得郵件的主體信息。而WriteTo()可以用來獲得郵件的全部信息,包括頭部信息
    // System.out.println(((MimeMessage)message).getContent());
    for (int i=0,n=message.length;i
    {

    String out_from_person = ((InternetAddress)message.getFrom()[0]).getPersonal();
    String out_from_address = ((InternetAddress)message.getFrom()[0]).getAddress();
    System.out.println("From:"+out_from_person+"t");
    System.out.println("Address:"+out_from_address+"t");

    String out_subject = message.getSubject();
    System.out.println("Subject:"+out_subject+"t");

    //以下代碼用來獲得郵件的正文信息
    Part messagePart = message;
    Object out_content = messagePart.getContent();
    if (out_content instanceof Multipart)
    {
    messagePart = ((Multipart)out_content).getBodyPart(0);
    System.out.println("[ Multipart Message ]");
    }
    String out_content_type = messagePart.getContentType();
    System.out.println("CONTENT:"+out_content_type);

    if (out_content_type.startsWith("text/plain") | | out_content_type.startsWith("text/html"))
    {
    InputStream ipstm = messagePart.getInputStream();
    BufferedReader bufreader = new BufferedReader(new InputStreamReader(ipstm));
    String thisLine = bufreader.readLine();
    while (thisLine != null)
    {
    System.out.println("thisLine: "+thisLine);
    thisLine = bufreader.readLine();
    }
    }
    System.out.println("------------------------------------------------------------");
    message.setFlag(Flags.Flag.DELETED,true);//最后刪除服務器端的郵件
    }
    //DELETED,ANSWERED,DRAFT,FLAGGED,RECENT,SEEN,USER
    folder.close(true);//true的話,徹底刪除已經標記為DELETE的郵件,如果為false的話,就不刪除
    store.close();//關閉
    }
    catch(Exception ej2)
    {
    System.out.println(ej2);
    }
    }

    void jButton4_actionPerformed(ActionEvent e) {
    try
    {//該程序為回復郵件
    Properties props = System.getProperties(); //獲取系統變量
    Authenticator auth = new Email_Autherticator(); //取得穃uFFFD衿魅現?
    props.put("mail.smtp.host",host);
    props.put("mail.smtp.auth","true");
    Session session = Session.getDefaultInstance(props,auth); //建立session
    Store store = session.getStore("pop3");
    store.connect(host,username,password);

    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_WRITE);
    Message message[] = folder.getMessages();

    for (int i=0,n=message.length;i
    {
    // String out_from_person = ((InternetAddress)message.getFrom()[0]).getPersonal();//獲取郵件發信人的署名

    String out_from_address = ((InternetAddress)message.getFrom()[0]).getAddress();
    System.out.println(out_from_address);

    Message forward = new MimeMessage(session);
    forward.setSubject("Fwd:"+message.getSubject());
    forward.setFrom(new InternetAddress(mail_to));
    forward.addRecipient(Message.RecipientType.TO,new InternetAddress(out_from_address));

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText("Here you go with the original message:nn");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(message.getDataHandler());

    multipart.addBodyPart(messageBodyPart);
    forward.setContent(multipart);

    Transport.send(forward);
    message.setFlag(Flags.Flag.DELETED,true);//DELETED,ANSWERED,DRAFT,FLAGGED,RECENT,SEEN,USER
    }
    folder.close(true);
    store.close();//關閉
    }
    catch(Exception ej2)
    {
    System.out.println(ej2);
    }

    }

    void jButton5_actionPerformed(ActionEvent e) {
    try
    {
    Properties props = new Properties();
    Authenticator auth = new Email_Autherticator();

    props.put("mail.smtp.host",host);
    props.put("mail.smtp.auth","true");
    Session session = Session.getDefaultInstance(props,auth);
    MimeMessage message = new MimeMessage(session);
    message.setContent("Hello","text/plain");
    message.setSubject(mail_subject);
    message.setText(mail_body);
    message.setHeader(mail_head_name,mail_head_value);
    message.setSentDate(new Date());
    message.setFrom(new InternetAddress(mail_from,"sunxiaoming")); //to signal man 
    //原理:可以將郵件看成有多個部分組成的,如正文是一個部分,附件也是一個部分,所以用BodyPart來設置郵件的格式
    程序代碼:  
    程序代碼:
    message.addRecipient(Message.RecipientType.TO,new InternetAddress(mail_to));
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText("Pardon Ideas");
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource("./20020423/test.zip");//此處設置郵件的附件
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName("test.zip");
    multipart.addBodyPart(messageBodyPart);
    message.setContent(multipart);
    Transport.send(message);
    System.out.println("send ok!");
    }
    catch(Exception ex)
    {
    System.out.println("faild"+ex);
    }

    }
    //此段代碼用來發送帶有附件的郵件
    void jButton6_actionPerformed(ActionEvent e) {
    try
    {
    Properties props = System.getProperties();
    Authenticator auth = new Email_Autherticator();
    props.put("mail.smtp.host",host);
    props.put("mail.smtp.auth","true");
    Session session = Session.getDefaultInstance(props,auth); //建立session
    Store store = session.getStore("pop3");
    store.connect(host,username,password);

    //After connecting to the Store,you can get a Folder,which must be opened before you can read messages from it:
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_WRITE);
    Message message[] = folder.getMessages();

    for (int i=0,n=message.length;i
    {
    //獲得郵件的部分信息,如頭部信息,送信人的署名,送信人的郵件地址
    String out_from_person = ((InternetAddress)message.getFrom()[0]).getPersonal();
    String out_from_address = ((InternetAddress)message.getFrom()[0]).getAddress();
    System.out.println("From:"+out_from_person+"t");
    System.out.println("Address:"+out_from_address+"t");
    String out_subject = message.getSubject();
    System.out.println("Subject:"+out_subject+"t");

    //以下代碼用來獲取郵件的主體信息
    Part messagePart = message;
    Object out_content = messagePart.getContent();
    if (out_content instanceof Multipart)
    {
    messagePart = ((Multipart)out_content).getBodyPart(0);
    System.out.println("[ Multipart Message ]");
    }
    String out_content_type = messagePart.getContentType();
    System.out.println("CONTENT:"+out_content_type);

    if (out_content_type.startsWith("text/plain") | | out_content_type.startsWith("text/html"))
    {
    InputStream ipstm = messagePart.getInputStream();
    BufferedReader bufreader = new BufferedReader(new InputStreamReader(ipstm));
    String thisLine = bufreader.readLine();
    while (thisLine != null)
    {
    System.out.println("thisLine: "+thisLine);
    thisLine = bufreader.readLine();
    }
    }
    //獲取附件
    Multipart mp = (Multipart)message.getContent();
    for (int j=0,m=mp.getCount();j
    {
    System.out.println("***"+m+"***");
    Part part = mp.getBodyPart(j);
    String disposition = part.getDisposition();
    if ((disposition != null) && ((disposition.equals(part.ATTACHMENT)) | | (disposition.equals(part.INLINE))))
    {

    //以下代碼將獲得的附件保存到當前目錄下,以part.getFileName()為文件名,也既是附件的名稱。
    File filename = new File(part.getFileName());
    for (int k=0;filename.exists();k++)
    {
    filename = new File(part.getFileName()+k);
    }
    FileOutputStream myFileoutputstream = new FileOutputStream(filename);
    int chunk = part.getSize();//獲得附件的大小,不一定很準確。

    byte [] buffer = new byte[chunk];
    InputStream instream = part.getInputStream();
    instream.read(buffer,0,chunk);
    myFileoutputstream.write(buffer,0,chunk);
    instream.close();
    myFileoutputstream.close();
    }
    }
    System.out.println("------------------------------------------------------------");
    message.setFlag(Flags.Flag.DELETED,true);
    }
    folder.close(true);
    store.close();//關閉
    }
    catch(Exception ej2)
    {
    System.out.println(ej2);
    }
    }

    //此段代碼用來發送帶有html信息的郵件
    void jButton8_actionPerformed(ActionEvent e) {
    try
    {
    Properties props = new Properties();
    Authenticator auth = new Email_Autherticator();
    props.put("mail.smtp.host",host);
    props.put("mail.smtp.auth","true");
    Session session = Session.getDefaultInstance(props,auth);
    MimeMessage message = new MimeMessage(session);
    //設置郵件正文
    String htmltext="< h1>hello< /h1>"+"< a href="http://www.sina.com.cn" target="_blank">click me please!< /a>";
    message.setContent(htmltext,"text/html");//text/plain設置郵件的格式因為是帶有html文檔的,所以用text/html格式

    message.setSubject(mail_subject);
    // message.setText(mail_body);在使用message.setContent()時候,好象不能用message.setText()
    message.setHeader(mail_head_name,mail_head_value);
    message.setSentDate(new Date());
    Address address = new InternetAddress(mail_from,"sunxiaoming");
    message.setFrom(address);
    Address toAddress = new InternetAddress(mail_to);
    message.addRecipient(Message.RecipientType.TO,toAddress);
    Transport.send(message);
    System.out.println("send ok!");
    }
    catch(Exception ex)
    {
    System.out.println("faild"+ex);
    }

    }

    //此段代碼用來發送帶有圖片的郵件
    void jButton9_actionPerformed(ActionEvent e) {
    try
    {
    String file = "./20020423/test.gif";
    Properties props = new Properties();
    Authenticator auth = new Email_Autherticator();

    props.put("mail.smtp.host",host);
    props.put("mail.smtp.auth","true");
    Session session = Session.getDefaultInstance(props,auth);
    MimeMessage message = new MimeMessage(session);

    message.setSubject("Embedded Image");
    Address address = new InternetAddress(mail_from,"sunxiaoming");
    message.setFrom(address);
    Address toAddress = new InternetAddress(mail_to);
    message.addRecipient(Message.RecipientType.TO,toAddress);
    message.setHeader(mail_head_name,mail_head_value);
    message.setSentDate(new Date());

    BodyPart messageBodyPart = new MimeBodyPart();
    String htmlText = "< h1>< /h1>"+"< img src="cid:memememe">";//加入圖片
    messageBodyPart.setContent(htmlText,"text/html");
    //原理同發送附件一樣,將郵件看成有多個部分組成的,先設置每一個部分,然后再全部將它們合起來即可。
    //Create a related multi-part to combine the parts
    MimeMultipart multipart = new MimeMultipart("related");
    multipart.addBodyPart(messageBodyPart);

    //Create part for the image
    messageBodyPart = new MimeBodyPart();

    //Fetch the image and associate to part
    DataSource fds = new FileDataSource(file);
    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID","memememe");

    //Add part to multi-part
    multipart.addBodyPart(messageBodyPart);

    //Associate multi-part with message
    message.setContent(multipart);

    Transport.send(message);
    System.out.println("send ok!");
    }
    catch(Exception ex)
    {
    System.out.println("faild"+ex);
    }

    }

    //該程序用來接受帶有html信息的郵件
    void jButton7_actionPerformed(ActionEvent e) {
    try
    {
    Properties props = System.getProperties();
    Authenticator auth = new Email_Autherticator();
    props.put("mail.smtp.host",host);
    props.put("mail.smtp.auth","true");
    Session session = Session.getDefaultInstance(props,auth);
    Store store = session.getStore("pop3");
    store.connect(host,username,password);

    //After connecting to the Store,you can get a Folder,which must be opened before you can read messages from it:
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_WRITE);
    Message message[] = folder.getMessages();

    for (int i=0,n=message.length;i
    // for (int i=0,n=1;i
    {
    String out_from_person = ((InternetAddress)message.getFrom()[0]).getPersonal();
    String out_from_address = ((InternetAddress)message.getFrom()[0]).getAddress();
    System.out.println("From:"+out_from_person+"t");
    System.out.println("Address:"+out_from_address+"t");

    String out_subject = message.getSubject();
    System.out.println("Subject:"+out_subject+"t");

    //獲取郵件的信息,并且對其每一部分進行操作
    Part messagePart = message;
    Object out_content = messagePart.getContent();
    if (out_content instanceof Multipart)
    {
    messagePart = ((Multipart)out_content).getBodyPart(0);
    System.out.println("[ Multipart Message ]");
    }
    String out_content_type = messagePart.getContentType();
    System.out.println("CONTENT:"+out_content_type);

    jEditorPane1.setText("");//將其顯示在jEditorPanel上
    jEditorPane1.setContentType("text/html");
    jEditorPane1.setText((String)out_content);
    jEditorPane1.setEditable(false);

    /*
    if (out_content_type.startsWith("text/plain") | | out_content_type.startsWith("text/html"))
    {
    InputStream ipstm = messagePart.getInputStream();
    BufferedReader bufreader = new BufferedReader(new InputStreamReader(ipstm));
    String thisLine = bufreader.readLine();
    while (thisLine != null)
    {
    System.out.println("thisLine: "+thisLine);
    thisLine = bufreader.readLine();
    }
    }
    */

    System.out.println("------------------------------------------------------------");
    message.setFlag(Flags.Flag.DELETED,true);
    }
    folder.close(true);
    store.close();
    }
    catch(Exception ej2)
    {
    System.out.println(ej2);
    }

    posted @ 2006-02-18 19:40 海思 閱讀(421) | 評論 (0)編輯 收藏

    一、jsp連接Oracle8/8i/9i數據庫(用thin模式)  
    testoracle.jsp如下:  
    <%@  page  contentType="text/html;charset=gb2312"%>  
    <%@  page  import="java.sql.*"%>  
    <html>  
    <body>  
    <%Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();  
    String  url="jdbc:oracle:thin:@localhost:1521:orcl";  
    //orcl為你的數據庫的SID  
    String  user="scott";  
    String  password="tiger";  
    Connection  conn=  DriverManager.getConnection(url,user,password);  
    Statement  stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);  
    String  sql="select  *  from  test";  
    ResultSet  rs=stmt.executeQuery(sql);  
    while(rs.next())  {%>  
    您的第一個字段內容為:<%=rs.getString(1)%>  
    您的第二個字段內容為:<%=rs.getString(2)%>  
    <%}%>  
    <%out.print("數據庫操作成功,恭喜你");%>  
    <%rs.close();  
    stmt.close();  
    conn.close();  
    %>  
    </body>  
    </html>  



    二、jsp連接Sql  Server7.0/2000數據庫  
    testsqlserver.jsp如下:  
    <%@  page  contentType="text/html;charset=gb2312"%>  
    <%@  page  import="java.sql.*"%>  
    <html>  
    <body>  
    <%Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();  
    String  url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs";  
    //pubs為你的數據庫的  
    String  user="sa";  
    String  password="";  
    Connection  conn=  DriverManager.getConnection(url,user,password);  
    Statement  stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);  
    String  sql="select  *  from  test";  
    ResultSet  rs=stmt.executeQuery(sql);  
    while(rs.next())  {%>  
    您的第一個字段內容為:<%=rs.getString(1)%>  
    您的第二個字段內容為:<%=rs.getString(2)%>  
    <%}%>  
    <%out.print("數據庫操作成功,恭喜你");%>  
    <%rs.close();  
    stmt.close();  
    conn.close();  
    %>  
    </body>  
    </html>  



    三、jsp連接DB2數據庫  
    testdb2.jsp如下:  
    <%@  page  contentType="text/html;charset=gb2312"%>  
    <%@  page  import="java.sql.*"%>  
    <html>  
    <body>  
    <%Class.forName("com.ibm.db2.jdbc.app.DB2Driver  ").newInstance();  
    String  url="jdbc:db2://localhost:5000/sample";  
    //sample為你的數據庫名  
    String  user="admin";  
    String  password="";  
    Connection  conn=  DriverManager.getConnection(url,user,password);  
    Statement  stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);  
    String  sql="select  *  from  test";  
    ResultSet  rs=stmt.executeQuery(sql);  
    while(rs.next())  {%>  
    您的第一個字段內容為:<%=rs.getString(1)%>  
    您的第二個字段內容為:<%=rs.getString(2)%>  
    <%}%>  
    <%out.print("數據庫操作成功,恭喜你");%>  
    <%rs.close();  
    stmt.close();  
    conn.close();  
    %>  
    </body>  
    </html>  



    四、jsp連接Informix數據庫  
    testinformix.jsp如下:  
    <%@  page  contentType="text/html;charset=gb2312"%>  
    <%@  page  import="java.sql.*"%>  
    <html>  
    <body>  
    <%Class.forName("com.informix.jdbc.IfxDriver").newInstance();  
    String  url  =  
    "jdbc:informix-sqli://123.45.67.89:1533/testDB:INFORMIXSERVER=myserver;  
    user=testuser;password=testpassword";  
    //testDB為你的數據庫名  
    Connection  conn=  DriverManager.getConnection(url);  
    Statement  stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);  
    String  sql="select  *  from  test";  
    ResultSet  rs=stmt.executeQuery(sql);  
    while(rs.next())  {%>  
    您的第一個字段內容為:<%=rs.getString(1)%>  
    您的第二個字段內容為:<%=rs.getString(2)%>  
    <%}%>  
    <%out.print("數據庫操作成功,恭喜你");%>  
    <%rs.close();  
    stmt.close();  
    conn.close();  
    %>  
    </body>  
    </html>  



    五、jsp連接Access數據庫  
    <%@page  import="java.sql.*"  
    import  ="java.util.*"  
    import  ="java.io.*"  
    import="java.text.*"  
    contentType="text/html;  charset=gb2312"  
    buffer="20kb"  
    %><%!  int  all,i,m_count;  
    String  odbcQuery;  
    Connection  odbcconn;  
    Statement  odbcstmt;  
    ResultSet  odbcrs;  
    String  username,title,content,work,email,url,time,date;  
    String  datetime;  
    %>  
    <%  
    try{  
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  
    }catch  (ClassNotFoundException  e)  
    {  out.print  ("驅動程序不存在");  
    }    
    try{  
    odbcconn  =  DriverManager.getConnection("jdbc:odbc:db1");  
    odbcstmt  =  odbcconn.createStatement();            
    odbcQuery="Select  *  From  book  where  datetime>2001-4-26  Order  By  datetime  DESC";  
    odbcrs=odbcstmt.executeQuery(odbcQuery);  
    int  i=0;  
    while  (i<130)  odbcrs.next();  
    while  (odbcrs.next())  
    {  
    //*/////////////////////////顯示數據庫的內容用于調試程序是用//  
    int  ii;  
    try{  
    try{  
    for  (ii=1;;ii++)  
    out.print  ("<br>Cloumn  "+ii+"  is:  "+odbcrs.getString(ii));  
    }catch  (NullPointerException  e)  {  
    out.print  ("有空的指針");  
    }  
    }catch  (SQLException  e){  
    }  
    }  
    odbcrs.close();  
    odbcstmt.close();  
    odbcconn.close();  
    }catch  (SQLException  e)  
    {  out.print  (e);  
    }  
    %>

    六.MYSQL
    import java.sql.*;

    public class MysqlTest {

    public static void main(String[] args) throws ClassNotFoundException, SQLException {
    // TODO Auto-generated method stub

    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs =null;

    String url = "jdbc:mysql://localhost:3306/mysql";
    conn = DriverManager.getConnection(url,"root","");
    stmt = conn.createStatement();

    rs = stmt.executeQuery("select * from user");

    while(rs.next())
    {
    System.out.println(rs.getObject(1));
    }
    stmt.close();
    conn.close();
    }
    }

    posted @ 2006-02-18 19:34 海思 閱讀(117) | 評論 (0)編輯 收藏

    中國與印度軟件工程師之比較
    shenkai 轉貼  (參與分:4519,專家分:680)   發表:2006-01-16 17:52   版本:1.0   閱讀:693

    在工作中,接觸到印度軟件公司開發出來的軟件: 整個體系架構非常清晰,按照我們的要求實現了全部功能,而且相當穩定。但是打開具體的代碼一看,拖沓冗長,水平不咋樣。我們自己的一些程序員就有怪話了,說他們水平真低。但是! 印度人能夠把軟件整體把握得很好,能夠完成軟件,并得到相當好的設計文檔。而中國人在那里琢磨數據結構、算法,界面人員就還沒編碼就想著是Outlook式的還是Visual Studio式的界面。到最后就成為Code 高手,對某些特定的開發工具精通,但是就是不能保證能夠把一個軟件穩當、完整的開發出來。

    ??舉個簡單的例子:

    ??軟件中需要一個列表,用來表示我們處理的事務。該類表在業務繁忙的時候將變得很大。中國人就用雙向鏈表,抱著《數據結構》書在那里寫鏈表的類。印度人開了一個大數組,然后就開始干。為什么印度人不用鏈表,他們說:1、你們給出的設備(小型機),最少具備512M內存,浪費一些沒有什么。2、數組方式訪問方便、效率高。 看出了一拿到東西就吭哧吭哧作Code,和好好進行軟件分析的不同了嗎?正好前幾天我有幾個同事從印度回來和我們交流,那家公司是CMM4級公司. 我感受的幾點:

    ??1. 流程重于項目

    ??2. QC(就是QA)獨立于研發部門,專門檢查研發部門的開發流程是不是按照既定流程走.如果QC覺得流程不對,他會直接上報高層, 項目肯定就此停止.

    ??3. 所謂的項目經理(PC)一般也是從編碼人員升上來的,并不是所謂的不懂技術,一般都至少有四年以上的經驗

    ??4. PC主要就是制定開發計劃,負責協調,填寫各種表格.

    ??5. 所有的東西(包括草稿)都有文檔.

    ??6. 詳細文檔要求達到只有這個文檔就可以編碼的程度,一般寫文檔時間占60%,編碼時間極少

    ??7. 有各種詳細的review(同行評審),項目組內的,項目組之間的,客戶的...

    ??8. 計劃很詳細,的確能達到小時級,但是實際情況還是誤差比較大,所以他們也有加班.

    ??先學習UML和Rose以及RUP,不要總是要找著證據。在中國的軟件開發水平下,很難給你一個好的例子,OK?中國人總是要看到一個東西有了試驗田,而且稻子長得好,才換稻種。要知道在國外上述的軟件開發模式的應用,大可以看看Rational網頁上的story。Just do it! 一句話,中國的軟件開發水平低得很。趕不上印度人,印度的軟件公司可以讓高中生編代碼,它的軟件工程水平可想而知。當然,你如果是個很牛的程序員。估計夠嗆,因為中國的氣氛中,很牛的程序員都很難接受軟件工程的。你可以測試一下自己, 看看自己適不適合現在學習軟件工程:

    ??1、你是不是不能忍受一個編程序不如你的人做你的項目經理?

    ??2、你是不是覺得你的老板對客戶吹牛皮、夸大自己而感到不舒服?

    ??3、你是不是一個拿到一個需求腦袋里第一念頭就是如何實現的人?

    ??4、你是不是很崇拜Stallman,Linus,很討厭Microsoft?

    ??5、你是不是曾經在深夜編碼的時候,突然感覺到一種乏味,對Code的生涯感到一種無趣?


    ??1、以管窺豹──印度神話 作者:"Kino" 我們現在處于深深的自卑當中,感到中國的軟件工程水平的低下已經是牽涉到民族劣根性的問題了。

    ??他們的軟件教育水平: 我們招聘印度人,給應聘者出了一份與國內差不多的試卷,有基礎概念和編程題目。 等到他們完成后,我們這些中國的自認高手驚呆了!他們的編程題目簡直象是抄襲的?程序結構,注釋,變量命名就不說了吧,全部都是極其類似!反觀中國的牛人、高手,每個人有自己的一套。到了新的崗位,先把前任的程序貶損一通,然后自己再開發更多的問題的代碼來代替。我的公司統計,一個軟件中有4個以上 CSocket版本,

    ??每個人都覺得別人做得差,自己再搞一套。中國人,就是這個樣子,還會辯解說“我們這樣有創造性”。 其實軟件發展,早就走過了求伯君那個編碼英雄的年代,程序員已經是個坐辦公室的藍領了。你具備擰好一個螺絲釘的能力就可以了。Code是最低級的事情了。

    ??2、他們許多公司的項目經理根本就不懂技術。 中國的項目經理如果不能在技術上壓服下屬,那么下屬將與他搞鬼,越是高手越喜歡搞鬼,根本不知道作軟件的終極目的是從別人兜里掏錢,而在內部搞不團結。技術高手都會糾集一些對他技術上崇拜的菜鳥,與管理層作對。而印度的軟件經理根本就不懂正在做的東西,許多甚至直接就是MBA,或者是領域專家 (工業設計、地理專家等),而不是編碼的專家。但是卻能夠領導大群素質良好的程序員把工作做好,沒有內部不團結的情況。許多印度的程序員加入一個公司很長時間,都不知道自己整天編的代碼是干什么用的。給他們的任務可能就是一個函數的聲明以及該函數要實現的功能。我們呢?

    ??3、他們的編程人員的流動率達到30%! 他們的編程人員流動率(包括內部項目之間的流動)高達30%,可以想見他們的文檔水平如何。他們的產品不依賴任何一個人,誰都可以立即辭職,產品的開發還是會正常進行。 而中國,是老板怕總工。技術骨干擁兵自重,抗拒管理。任何制定好的計劃,都有可能被技術人員推翻或者跟你消極怠工。

    ??4、他們的開發計劃能夠做到小時級別。 如果一個印度公司的項目經理沒有上班,那么他的下屬將可能不知道作什么。他們的計劃一般都定到天,每個基層開發人員每天的工作量就是8小時。而我們能夠給出月度計劃的公司就很少,而給出的月度計劃要么不可能實現,要么就可 能被取消。開發人員被初略的給個任務,他在月初,可以慢慢琢磨是做成什么樣子,然 后上上網,聊聊天。到了月中和月末,就開始熬夜編碼。
    posted @ 2006-01-21 16:58 海思 閱讀(243) | 評論 (0)編輯 收藏

    主站蜘蛛池模板: 亚洲人AV永久一区二区三区久久| 日本免费污片中国特一级| 亚洲精品无码久久| 亚洲人成人无码.www石榴| 亚洲xxxx视频| 亚洲综合av一区二区三区| 亚洲日韩精品国产一区二区三区| 亚洲kkk4444在线观看| 亚洲狠狠色丁香婷婷综合| 一本色道久久88亚洲精品综合 | 四虎在线播放免费永久视频| 午夜神器成在线人成在线人免费| 成人午夜视频免费| 日本特黄a级高清免费大片| 免费大黄网站在线观| 亚洲人成无码网WWW| 亚洲精品国产品国语在线| 久久伊人久久亚洲综合| 亚洲精品国产手机| 色偷偷亚洲女人天堂观看欧| 亚洲精品永久在线观看| 美女啪啪网站又黄又免费| 中文字幕免费播放| 99久久久国产精品免费牛牛 | 在线观看的免费网站无遮挡| 在线观看www日本免费网站| 人禽杂交18禁网站免费| 国产一精品一aⅴ一免费| 久久影视国产亚洲| 99久久精品国产亚洲| 精品亚洲456在线播放| 黄色毛片免费网站| 日本黄色动图免费在线观看| 2020久久精品国产免费| 日本免费网站观看| 好看的亚洲黄色经典| 亚洲国产综合第一精品小说| 亚洲av无码专区在线电影天堂| 国产福利免费视频 | 亚洲国产精品特色大片观看完整版| 99人中文字幕亚洲区|